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, ShowScrollbar,
   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                        let color_swatch = completion
 1232                            .color()
 1233                            .map(|color| div().size_4().bg(color).rounded_sm());
 1234
 1235                        div().min_w(px(220.)).max_w(px(540.)).child(
 1236                            ListItem::new(mat.candidate_id)
 1237                                .inset(true)
 1238                                .selected(item_ix == selected_item)
 1239                                .on_click(cx.listener(move |editor, _event, cx| {
 1240                                    cx.stop_propagation();
 1241                                    if let Some(task) = editor.confirm_completion(
 1242                                        &ConfirmCompletion {
 1243                                            item_ix: Some(item_ix),
 1244                                        },
 1245                                        cx,
 1246                                    ) {
 1247                                        task.detach_and_log_err(cx)
 1248                                    }
 1249                                }))
 1250                                .start_slot::<Div>(color_swatch)
 1251                                .child(h_flex().overflow_hidden().child(completion_label))
 1252                                .end_slot::<Label>(documentation_label),
 1253                        )
 1254                    })
 1255                    .collect()
 1256            },
 1257        )
 1258        .occlude()
 1259        .max_h(max_height)
 1260        .track_scroll(self.scroll_handle.clone())
 1261        .with_width_from_item(widest_completion_ix)
 1262        .with_sizing_behavior(ListSizingBehavior::Infer);
 1263
 1264        Popover::new()
 1265            .child(list)
 1266            .when_some(multiline_docs, |popover, multiline_docs| {
 1267                popover.aside(multiline_docs)
 1268            })
 1269            .into_any_element()
 1270    }
 1271
 1272    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1273        let mut matches = if let Some(query) = query {
 1274            fuzzy::match_strings(
 1275                &self.match_candidates,
 1276                query,
 1277                query.chars().any(|c| c.is_uppercase()),
 1278                100,
 1279                &Default::default(),
 1280                executor,
 1281            )
 1282            .await
 1283        } else {
 1284            self.match_candidates
 1285                .iter()
 1286                .enumerate()
 1287                .map(|(candidate_id, candidate)| StringMatch {
 1288                    candidate_id,
 1289                    score: Default::default(),
 1290                    positions: Default::default(),
 1291                    string: candidate.string.clone(),
 1292                })
 1293                .collect()
 1294        };
 1295
 1296        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1297        if let Some(query) = query {
 1298            if let Some(query_start) = query.chars().next() {
 1299                matches.retain(|string_match| {
 1300                    split_words(&string_match.string).any(|word| {
 1301                        // Check that the first codepoint of the word as lowercase matches the first
 1302                        // codepoint of the query as lowercase
 1303                        word.chars()
 1304                            .flat_map(|codepoint| codepoint.to_lowercase())
 1305                            .zip(query_start.to_lowercase())
 1306                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1307                    })
 1308                });
 1309            }
 1310        }
 1311
 1312        let completions = self.completions.read();
 1313        if self.sort_completions {
 1314            matches.sort_unstable_by_key(|mat| {
 1315                // We do want to strike a balance here between what the language server tells us
 1316                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1317                // `Creat` and there is a local variable called `CreateComponent`).
 1318                // So what we do is: we bucket all matches into two buckets
 1319                // - Strong matches
 1320                // - Weak matches
 1321                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1322                // and the Weak matches are the rest.
 1323                //
 1324                // For the strong matches, we sort by the language-servers score first and for the weak
 1325                // matches, we prefer our fuzzy finder first.
 1326                //
 1327                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1328                // us into account when it's obviously a bad match.
 1329
 1330                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1331                enum MatchScore<'a> {
 1332                    Strong {
 1333                        sort_text: Option<&'a str>,
 1334                        score: Reverse<OrderedFloat<f64>>,
 1335                        sort_key: (usize, &'a str),
 1336                    },
 1337                    Weak {
 1338                        score: Reverse<OrderedFloat<f64>>,
 1339                        sort_text: Option<&'a str>,
 1340                        sort_key: (usize, &'a str),
 1341                    },
 1342                }
 1343
 1344                let completion = &completions[mat.candidate_id];
 1345                let sort_key = completion.sort_key();
 1346                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1347                let score = Reverse(OrderedFloat(mat.score));
 1348
 1349                if mat.score >= 0.2 {
 1350                    MatchScore::Strong {
 1351                        sort_text,
 1352                        score,
 1353                        sort_key,
 1354                    }
 1355                } else {
 1356                    MatchScore::Weak {
 1357                        score,
 1358                        sort_text,
 1359                        sort_key,
 1360                    }
 1361                }
 1362            });
 1363        }
 1364
 1365        for mat in &mut matches {
 1366            let completion = &completions[mat.candidate_id];
 1367            mat.string.clone_from(&completion.label.text);
 1368            for position in &mut mat.positions {
 1369                *position += completion.label.filter_range.start;
 1370            }
 1371        }
 1372        drop(completions);
 1373
 1374        self.matches = matches.into();
 1375        self.selected_item = 0;
 1376    }
 1377}
 1378
 1379struct AvailableCodeAction {
 1380    excerpt_id: ExcerptId,
 1381    action: CodeAction,
 1382    provider: Arc<dyn CodeActionProvider>,
 1383}
 1384
 1385#[derive(Clone)]
 1386struct CodeActionContents {
 1387    tasks: Option<Arc<ResolvedTasks>>,
 1388    actions: Option<Arc<[AvailableCodeAction]>>,
 1389}
 1390
 1391impl CodeActionContents {
 1392    fn len(&self) -> usize {
 1393        match (&self.tasks, &self.actions) {
 1394            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1395            (Some(tasks), None) => tasks.templates.len(),
 1396            (None, Some(actions)) => actions.len(),
 1397            (None, None) => 0,
 1398        }
 1399    }
 1400
 1401    fn is_empty(&self) -> bool {
 1402        match (&self.tasks, &self.actions) {
 1403            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1404            (Some(tasks), None) => tasks.templates.is_empty(),
 1405            (None, Some(actions)) => actions.is_empty(),
 1406            (None, None) => true,
 1407        }
 1408    }
 1409
 1410    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1411        self.tasks
 1412            .iter()
 1413            .flat_map(|tasks| {
 1414                tasks
 1415                    .templates
 1416                    .iter()
 1417                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1418            })
 1419            .chain(self.actions.iter().flat_map(|actions| {
 1420                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1421                    excerpt_id: available.excerpt_id,
 1422                    action: available.action.clone(),
 1423                    provider: available.provider.clone(),
 1424                })
 1425            }))
 1426    }
 1427    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1428        match (&self.tasks, &self.actions) {
 1429            (Some(tasks), Some(actions)) => {
 1430                if index < tasks.templates.len() {
 1431                    tasks
 1432                        .templates
 1433                        .get(index)
 1434                        .cloned()
 1435                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1436                } else {
 1437                    actions.get(index - tasks.templates.len()).map(|available| {
 1438                        CodeActionsItem::CodeAction {
 1439                            excerpt_id: available.excerpt_id,
 1440                            action: available.action.clone(),
 1441                            provider: available.provider.clone(),
 1442                        }
 1443                    })
 1444                }
 1445            }
 1446            (Some(tasks), None) => tasks
 1447                .templates
 1448                .get(index)
 1449                .cloned()
 1450                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1451            (None, Some(actions)) => {
 1452                actions
 1453                    .get(index)
 1454                    .map(|available| CodeActionsItem::CodeAction {
 1455                        excerpt_id: available.excerpt_id,
 1456                        action: available.action.clone(),
 1457                        provider: available.provider.clone(),
 1458                    })
 1459            }
 1460            (None, None) => None,
 1461        }
 1462    }
 1463}
 1464
 1465#[allow(clippy::large_enum_variant)]
 1466#[derive(Clone)]
 1467enum CodeActionsItem {
 1468    Task(TaskSourceKind, ResolvedTask),
 1469    CodeAction {
 1470        excerpt_id: ExcerptId,
 1471        action: CodeAction,
 1472        provider: Arc<dyn CodeActionProvider>,
 1473    },
 1474}
 1475
 1476impl CodeActionsItem {
 1477    fn as_task(&self) -> Option<&ResolvedTask> {
 1478        let Self::Task(_, task) = self else {
 1479            return None;
 1480        };
 1481        Some(task)
 1482    }
 1483    fn as_code_action(&self) -> Option<&CodeAction> {
 1484        let Self::CodeAction { action, .. } = self else {
 1485            return None;
 1486        };
 1487        Some(action)
 1488    }
 1489    fn label(&self) -> String {
 1490        match self {
 1491            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1492            Self::Task(_, task) => task.resolved_label.clone(),
 1493        }
 1494    }
 1495}
 1496
 1497struct CodeActionsMenu {
 1498    actions: CodeActionContents,
 1499    buffer: Model<Buffer>,
 1500    selected_item: usize,
 1501    scroll_handle: UniformListScrollHandle,
 1502    deployed_from_indicator: Option<DisplayRow>,
 1503}
 1504
 1505impl CodeActionsMenu {
 1506    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1507        self.selected_item = 0;
 1508        self.scroll_handle.scroll_to_item(self.selected_item);
 1509        cx.notify()
 1510    }
 1511
 1512    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1513        if self.selected_item > 0 {
 1514            self.selected_item -= 1;
 1515        } else {
 1516            self.selected_item = self.actions.len() - 1;
 1517        }
 1518        self.scroll_handle.scroll_to_item(self.selected_item);
 1519        cx.notify();
 1520    }
 1521
 1522    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1523        if self.selected_item + 1 < self.actions.len() {
 1524            self.selected_item += 1;
 1525        } else {
 1526            self.selected_item = 0;
 1527        }
 1528        self.scroll_handle.scroll_to_item(self.selected_item);
 1529        cx.notify();
 1530    }
 1531
 1532    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1533        self.selected_item = self.actions.len() - 1;
 1534        self.scroll_handle.scroll_to_item(self.selected_item);
 1535        cx.notify()
 1536    }
 1537
 1538    fn visible(&self) -> bool {
 1539        !self.actions.is_empty()
 1540    }
 1541
 1542    fn render(
 1543        &self,
 1544        cursor_position: DisplayPoint,
 1545        _style: &EditorStyle,
 1546        max_height: Pixels,
 1547        cx: &mut ViewContext<Editor>,
 1548    ) -> (ContextMenuOrigin, AnyElement) {
 1549        let actions = self.actions.clone();
 1550        let selected_item = self.selected_item;
 1551        let element = uniform_list(
 1552            cx.view().clone(),
 1553            "code_actions_menu",
 1554            self.actions.len(),
 1555            move |_this, range, cx| {
 1556                actions
 1557                    .iter()
 1558                    .skip(range.start)
 1559                    .take(range.end - range.start)
 1560                    .enumerate()
 1561                    .map(|(ix, action)| {
 1562                        let item_ix = range.start + ix;
 1563                        let selected = selected_item == item_ix;
 1564                        let colors = cx.theme().colors();
 1565                        div()
 1566                            .px_1()
 1567                            .rounded_md()
 1568                            .text_color(colors.text)
 1569                            .when(selected, |style| {
 1570                                style
 1571                                    .bg(colors.element_active)
 1572                                    .text_color(colors.text_accent)
 1573                            })
 1574                            .hover(|style| {
 1575                                style
 1576                                    .bg(colors.element_hover)
 1577                                    .text_color(colors.text_accent)
 1578                            })
 1579                            .whitespace_nowrap()
 1580                            .when_some(action.as_code_action(), |this, action| {
 1581                                this.on_mouse_down(
 1582                                    MouseButton::Left,
 1583                                    cx.listener(move |editor, _, cx| {
 1584                                        cx.stop_propagation();
 1585                                        if let Some(task) = editor.confirm_code_action(
 1586                                            &ConfirmCodeAction {
 1587                                                item_ix: Some(item_ix),
 1588                                            },
 1589                                            cx,
 1590                                        ) {
 1591                                            task.detach_and_log_err(cx)
 1592                                        }
 1593                                    }),
 1594                                )
 1595                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1596                                .child(SharedString::from(action.lsp_action.title.clone()))
 1597                            })
 1598                            .when_some(action.as_task(), |this, task| {
 1599                                this.on_mouse_down(
 1600                                    MouseButton::Left,
 1601                                    cx.listener(move |editor, _, cx| {
 1602                                        cx.stop_propagation();
 1603                                        if let Some(task) = editor.confirm_code_action(
 1604                                            &ConfirmCodeAction {
 1605                                                item_ix: Some(item_ix),
 1606                                            },
 1607                                            cx,
 1608                                        ) {
 1609                                            task.detach_and_log_err(cx)
 1610                                        }
 1611                                    }),
 1612                                )
 1613                                .child(SharedString::from(task.resolved_label.clone()))
 1614                            })
 1615                    })
 1616                    .collect()
 1617            },
 1618        )
 1619        .elevation_1(cx)
 1620        .p_1()
 1621        .max_h(max_height)
 1622        .occlude()
 1623        .track_scroll(self.scroll_handle.clone())
 1624        .with_width_from_item(
 1625            self.actions
 1626                .iter()
 1627                .enumerate()
 1628                .max_by_key(|(_, action)| match action {
 1629                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1630                    CodeActionsItem::CodeAction { action, .. } => {
 1631                        action.lsp_action.title.chars().count()
 1632                    }
 1633                })
 1634                .map(|(ix, _)| ix),
 1635        )
 1636        .with_sizing_behavior(ListSizingBehavior::Infer)
 1637        .into_any_element();
 1638
 1639        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1640            ContextMenuOrigin::GutterIndicator(row)
 1641        } else {
 1642            ContextMenuOrigin::EditorPoint(cursor_position)
 1643        };
 1644
 1645        (cursor_position, element)
 1646    }
 1647}
 1648
 1649#[derive(Debug)]
 1650struct ActiveDiagnosticGroup {
 1651    primary_range: Range<Anchor>,
 1652    primary_message: String,
 1653    group_id: usize,
 1654    blocks: HashMap<CustomBlockId, Diagnostic>,
 1655    is_valid: bool,
 1656}
 1657
 1658#[derive(Serialize, Deserialize, Clone, Debug)]
 1659pub struct ClipboardSelection {
 1660    pub len: usize,
 1661    pub is_entire_line: bool,
 1662    pub first_line_indent: u32,
 1663}
 1664
 1665#[derive(Debug)]
 1666pub(crate) struct NavigationData {
 1667    cursor_anchor: Anchor,
 1668    cursor_position: Point,
 1669    scroll_anchor: ScrollAnchor,
 1670    scroll_top_row: u32,
 1671}
 1672
 1673#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1674enum GotoDefinitionKind {
 1675    Symbol,
 1676    Declaration,
 1677    Type,
 1678    Implementation,
 1679}
 1680
 1681#[derive(Debug, Clone)]
 1682enum InlayHintRefreshReason {
 1683    Toggle(bool),
 1684    SettingsChange(InlayHintSettings),
 1685    NewLinesShown,
 1686    BufferEdited(HashSet<Arc<Language>>),
 1687    RefreshRequested,
 1688    ExcerptsRemoved(Vec<ExcerptId>),
 1689}
 1690
 1691impl InlayHintRefreshReason {
 1692    fn description(&self) -> &'static str {
 1693        match self {
 1694            Self::Toggle(_) => "toggle",
 1695            Self::SettingsChange(_) => "settings change",
 1696            Self::NewLinesShown => "new lines shown",
 1697            Self::BufferEdited(_) => "buffer edited",
 1698            Self::RefreshRequested => "refresh requested",
 1699            Self::ExcerptsRemoved(_) => "excerpts removed",
 1700        }
 1701    }
 1702}
 1703
 1704pub(crate) struct FocusedBlock {
 1705    id: BlockId,
 1706    focus_handle: WeakFocusHandle,
 1707}
 1708
 1709impl Editor {
 1710    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1711        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1712        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1713        Self::new(
 1714            EditorMode::SingleLine { auto_width: false },
 1715            buffer,
 1716            None,
 1717            false,
 1718            cx,
 1719        )
 1720    }
 1721
 1722    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1723        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1724        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1725        Self::new(EditorMode::Full, buffer, None, false, cx)
 1726    }
 1727
 1728    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1729        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1730        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1731        Self::new(
 1732            EditorMode::SingleLine { auto_width: true },
 1733            buffer,
 1734            None,
 1735            false,
 1736            cx,
 1737        )
 1738    }
 1739
 1740    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1741        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1742        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1743        Self::new(
 1744            EditorMode::AutoHeight { max_lines },
 1745            buffer,
 1746            None,
 1747            false,
 1748            cx,
 1749        )
 1750    }
 1751
 1752    pub fn for_buffer(
 1753        buffer: Model<Buffer>,
 1754        project: Option<Model<Project>>,
 1755        cx: &mut ViewContext<Self>,
 1756    ) -> Self {
 1757        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1758        Self::new(EditorMode::Full, buffer, project, false, cx)
 1759    }
 1760
 1761    pub fn for_multibuffer(
 1762        buffer: Model<MultiBuffer>,
 1763        project: Option<Model<Project>>,
 1764        show_excerpt_controls: bool,
 1765        cx: &mut ViewContext<Self>,
 1766    ) -> Self {
 1767        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1768    }
 1769
 1770    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1771        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1772        let mut clone = Self::new(
 1773            self.mode,
 1774            self.buffer.clone(),
 1775            self.project.clone(),
 1776            show_excerpt_controls,
 1777            cx,
 1778        );
 1779        self.display_map.update(cx, |display_map, cx| {
 1780            let snapshot = display_map.snapshot(cx);
 1781            clone.display_map.update(cx, |display_map, cx| {
 1782                display_map.set_state(&snapshot, cx);
 1783            });
 1784        });
 1785        clone.selections.clone_state(&self.selections);
 1786        clone.scroll_manager.clone_state(&self.scroll_manager);
 1787        clone.searchable = self.searchable;
 1788        clone
 1789    }
 1790
 1791    pub fn new(
 1792        mode: EditorMode,
 1793        buffer: Model<MultiBuffer>,
 1794        project: Option<Model<Project>>,
 1795        show_excerpt_controls: bool,
 1796        cx: &mut ViewContext<Self>,
 1797    ) -> Self {
 1798        let style = cx.text_style();
 1799        let font_size = style.font_size.to_pixels(cx.rem_size());
 1800        let editor = cx.view().downgrade();
 1801        let fold_placeholder = FoldPlaceholder {
 1802            constrain_width: true,
 1803            render: Arc::new(move |fold_id, fold_range, cx| {
 1804                let editor = editor.clone();
 1805                div()
 1806                    .id(fold_id)
 1807                    .bg(cx.theme().colors().ghost_element_background)
 1808                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1809                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1810                    .rounded_sm()
 1811                    .size_full()
 1812                    .cursor_pointer()
 1813                    .child("")
 1814                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1815                    .on_click(move |_, cx| {
 1816                        editor
 1817                            .update(cx, |editor, cx| {
 1818                                editor.unfold_ranges(
 1819                                    [fold_range.start..fold_range.end],
 1820                                    true,
 1821                                    false,
 1822                                    cx,
 1823                                );
 1824                                cx.stop_propagation();
 1825                            })
 1826                            .ok();
 1827                    })
 1828                    .into_any()
 1829            }),
 1830            merge_adjacent: true,
 1831        };
 1832        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1833        let display_map = cx.new_model(|cx| {
 1834            DisplayMap::new(
 1835                buffer.clone(),
 1836                style.font(),
 1837                font_size,
 1838                None,
 1839                show_excerpt_controls,
 1840                file_header_size,
 1841                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1842                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1843                fold_placeholder,
 1844                cx,
 1845            )
 1846        });
 1847
 1848        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1849
 1850        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1851
 1852        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1853            .then(|| language_settings::SoftWrap::None);
 1854
 1855        let mut project_subscriptions = Vec::new();
 1856        if mode == EditorMode::Full {
 1857            if let Some(project) = project.as_ref() {
 1858                if buffer.read(cx).is_singleton() {
 1859                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1860                        cx.emit(EditorEvent::TitleChanged);
 1861                    }));
 1862                }
 1863                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1864                    if let project::Event::RefreshInlayHints = event {
 1865                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1866                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1867                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1868                            let focus_handle = editor.focus_handle(cx);
 1869                            if focus_handle.is_focused(cx) {
 1870                                let snapshot = buffer.read(cx).snapshot();
 1871                                for (range, snippet) in snippet_edits {
 1872                                    let editor_range =
 1873                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1874                                    editor
 1875                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1876                                        .ok();
 1877                                }
 1878                            }
 1879                        }
 1880                    }
 1881                }));
 1882                let task_inventory = project.read(cx).task_inventory().clone();
 1883                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1884                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1885                }));
 1886            }
 1887        }
 1888
 1889        let inlay_hint_settings = inlay_hint_settings(
 1890            selections.newest_anchor().head(),
 1891            &buffer.read(cx).snapshot(cx),
 1892            cx,
 1893        );
 1894        let focus_handle = cx.focus_handle();
 1895        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1896        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1897            .detach();
 1898        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1899            .detach();
 1900        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1901
 1902        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1903            Some(false)
 1904        } else {
 1905            None
 1906        };
 1907
 1908        let mut code_action_providers = Vec::new();
 1909        if let Some(project) = project.clone() {
 1910            code_action_providers.push(Arc::new(project) as Arc<_>);
 1911        }
 1912
 1913        let mut this = Self {
 1914            focus_handle,
 1915            show_cursor_when_unfocused: false,
 1916            last_focused_descendant: None,
 1917            buffer: buffer.clone(),
 1918            display_map: display_map.clone(),
 1919            selections,
 1920            scroll_manager: ScrollManager::new(cx),
 1921            columnar_selection_tail: None,
 1922            add_selections_state: None,
 1923            select_next_state: None,
 1924            select_prev_state: None,
 1925            selection_history: Default::default(),
 1926            autoclose_regions: Default::default(),
 1927            snippet_stack: Default::default(),
 1928            select_larger_syntax_node_stack: Vec::new(),
 1929            ime_transaction: Default::default(),
 1930            active_diagnostics: None,
 1931            soft_wrap_mode_override,
 1932            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1933            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1934            project,
 1935            blink_manager: blink_manager.clone(),
 1936            show_local_selections: true,
 1937            mode,
 1938            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1939            show_gutter: mode == EditorMode::Full,
 1940            show_line_numbers: None,
 1941            use_relative_line_numbers: None,
 1942            show_git_diff_gutter: None,
 1943            show_code_actions: None,
 1944            show_runnables: None,
 1945            show_wrap_guides: None,
 1946            show_indent_guides,
 1947            placeholder_text: None,
 1948            highlight_order: 0,
 1949            highlighted_rows: HashMap::default(),
 1950            background_highlights: Default::default(),
 1951            gutter_highlights: TreeMap::default(),
 1952            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1953            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1954            nav_history: None,
 1955            context_menu: RwLock::new(None),
 1956            mouse_context_menu: None,
 1957            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1958            completion_tasks: Default::default(),
 1959            signature_help_state: SignatureHelpState::default(),
 1960            auto_signature_help: None,
 1961            find_all_references_task_sources: Vec::new(),
 1962            next_completion_id: 0,
 1963            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1964            next_inlay_id: 0,
 1965            code_action_providers,
 1966            available_code_actions: Default::default(),
 1967            code_actions_task: Default::default(),
 1968            document_highlights_task: Default::default(),
 1969            linked_editing_range_task: Default::default(),
 1970            pending_rename: Default::default(),
 1971            searchable: true,
 1972            cursor_shape: EditorSettings::get_global(cx)
 1973                .cursor_shape
 1974                .unwrap_or_default(),
 1975            current_line_highlight: None,
 1976            autoindent_mode: Some(AutoindentMode::EachLine),
 1977            collapse_matches: false,
 1978            workspace: None,
 1979            input_enabled: true,
 1980            use_modal_editing: mode == EditorMode::Full,
 1981            read_only: false,
 1982            use_autoclose: true,
 1983            use_auto_surround: true,
 1984            auto_replace_emoji_shortcode: false,
 1985            leader_peer_id: None,
 1986            remote_id: None,
 1987            hover_state: Default::default(),
 1988            hovered_link_state: Default::default(),
 1989            inline_completion_provider: None,
 1990            active_inline_completion: None,
 1991            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1992            expanded_hunks: ExpandedHunks::default(),
 1993            gutter_hovered: false,
 1994            pixel_position_of_newest_cursor: None,
 1995            last_bounds: None,
 1996            expect_bounds_change: None,
 1997            gutter_dimensions: GutterDimensions::default(),
 1998            style: None,
 1999            show_cursor_names: false,
 2000            hovered_cursors: Default::default(),
 2001            next_editor_action_id: EditorActionId::default(),
 2002            editor_actions: Rc::default(),
 2003            show_inline_completions_override: None,
 2004            enable_inline_completions: true,
 2005            custom_context_menu: None,
 2006            show_git_blame_gutter: false,
 2007            show_git_blame_inline: false,
 2008            show_selection_menu: None,
 2009            show_git_blame_inline_delay_task: None,
 2010            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2011            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2012                .session
 2013                .restore_unsaved_buffers,
 2014            blame: None,
 2015            blame_subscription: None,
 2016            file_header_size,
 2017            tasks: Default::default(),
 2018            _subscriptions: vec![
 2019                cx.observe(&buffer, Self::on_buffer_changed),
 2020                cx.subscribe(&buffer, Self::on_buffer_event),
 2021                cx.observe(&display_map, Self::on_display_map_changed),
 2022                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2023                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2024                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2025                cx.observe_window_activation(|editor, cx| {
 2026                    let active = cx.is_window_active();
 2027                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2028                        if active {
 2029                            blink_manager.enable(cx);
 2030                        } else {
 2031                            blink_manager.disable(cx);
 2032                        }
 2033                    });
 2034                }),
 2035            ],
 2036            tasks_update_task: None,
 2037            linked_edit_ranges: Default::default(),
 2038            previous_search_ranges: None,
 2039            breadcrumb_header: None,
 2040            focused_block: None,
 2041            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2042            addons: HashMap::default(),
 2043            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2044        };
 2045        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2046        this._subscriptions.extend(project_subscriptions);
 2047
 2048        this.end_selection(cx);
 2049        this.scroll_manager.show_scrollbar(cx);
 2050
 2051        if mode == EditorMode::Full {
 2052            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2053            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2054
 2055            if this.git_blame_inline_enabled {
 2056                this.git_blame_inline_enabled = true;
 2057                this.start_git_blame_inline(false, cx);
 2058            }
 2059        }
 2060
 2061        this.report_editor_event("open", None, cx);
 2062        this
 2063    }
 2064
 2065    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2066        self.mouse_context_menu
 2067            .as_ref()
 2068            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2069    }
 2070
 2071    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2072        let mut key_context = KeyContext::new_with_defaults();
 2073        key_context.add("Editor");
 2074        let mode = match self.mode {
 2075            EditorMode::SingleLine { .. } => "single_line",
 2076            EditorMode::AutoHeight { .. } => "auto_height",
 2077            EditorMode::Full => "full",
 2078        };
 2079
 2080        if EditorSettings::jupyter_enabled(cx) {
 2081            key_context.add("jupyter");
 2082        }
 2083
 2084        key_context.set("mode", mode);
 2085        if self.pending_rename.is_some() {
 2086            key_context.add("renaming");
 2087        }
 2088        if self.context_menu_visible() {
 2089            match self.context_menu.read().as_ref() {
 2090                Some(ContextMenu::Completions(_)) => {
 2091                    key_context.add("menu");
 2092                    key_context.add("showing_completions")
 2093                }
 2094                Some(ContextMenu::CodeActions(_)) => {
 2095                    key_context.add("menu");
 2096                    key_context.add("showing_code_actions")
 2097                }
 2098                None => {}
 2099            }
 2100        }
 2101
 2102        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2103        if !self.focus_handle(cx).contains_focused(cx)
 2104            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2105        {
 2106            for addon in self.addons.values() {
 2107                addon.extend_key_context(&mut key_context, cx)
 2108            }
 2109        }
 2110
 2111        if let Some(extension) = self
 2112            .buffer
 2113            .read(cx)
 2114            .as_singleton()
 2115            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2116        {
 2117            key_context.set("extension", extension.to_string());
 2118        }
 2119
 2120        if self.has_active_inline_completion(cx) {
 2121            key_context.add("copilot_suggestion");
 2122            key_context.add("inline_completion");
 2123        }
 2124
 2125        key_context
 2126    }
 2127
 2128    pub fn new_file(
 2129        workspace: &mut Workspace,
 2130        _: &workspace::NewFile,
 2131        cx: &mut ViewContext<Workspace>,
 2132    ) {
 2133        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2134            "Failed to create buffer",
 2135            cx,
 2136            |e, _| match e.error_code() {
 2137                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2138                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2139                e.error_tag("required").unwrap_or("the latest version")
 2140            )),
 2141                _ => None,
 2142            },
 2143        );
 2144    }
 2145
 2146    pub fn new_in_workspace(
 2147        workspace: &mut Workspace,
 2148        cx: &mut ViewContext<Workspace>,
 2149    ) -> Task<Result<View<Editor>>> {
 2150        let project = workspace.project().clone();
 2151        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2152
 2153        cx.spawn(|workspace, mut cx| async move {
 2154            let buffer = create.await?;
 2155            workspace.update(&mut cx, |workspace, cx| {
 2156                let editor =
 2157                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2158                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2159                editor
 2160            })
 2161        })
 2162    }
 2163
 2164    fn new_file_vertical(
 2165        workspace: &mut Workspace,
 2166        _: &workspace::NewFileSplitVertical,
 2167        cx: &mut ViewContext<Workspace>,
 2168    ) {
 2169        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2170    }
 2171
 2172    fn new_file_horizontal(
 2173        workspace: &mut Workspace,
 2174        _: &workspace::NewFileSplitHorizontal,
 2175        cx: &mut ViewContext<Workspace>,
 2176    ) {
 2177        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2178    }
 2179
 2180    fn new_file_in_direction(
 2181        workspace: &mut Workspace,
 2182        direction: SplitDirection,
 2183        cx: &mut ViewContext<Workspace>,
 2184    ) {
 2185        let project = workspace.project().clone();
 2186        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2187
 2188        cx.spawn(|workspace, mut cx| async move {
 2189            let buffer = create.await?;
 2190            workspace.update(&mut cx, move |workspace, cx| {
 2191                workspace.split_item(
 2192                    direction,
 2193                    Box::new(
 2194                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2195                    ),
 2196                    cx,
 2197                )
 2198            })?;
 2199            anyhow::Ok(())
 2200        })
 2201        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2202            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2203                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2204                e.error_tag("required").unwrap_or("the latest version")
 2205            )),
 2206            _ => None,
 2207        });
 2208    }
 2209
 2210    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2211        self.leader_peer_id
 2212    }
 2213
 2214    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2215        &self.buffer
 2216    }
 2217
 2218    pub fn workspace(&self) -> Option<View<Workspace>> {
 2219        self.workspace.as_ref()?.0.upgrade()
 2220    }
 2221
 2222    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2223        self.buffer().read(cx).title(cx)
 2224    }
 2225
 2226    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2227        let git_blame_gutter_max_author_length = self
 2228            .render_git_blame_gutter(cx)
 2229            .then(|| {
 2230                if let Some(blame) = self.blame.as_ref() {
 2231                    let max_author_length =
 2232                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2233                    Some(max_author_length)
 2234                } else {
 2235                    None
 2236                }
 2237            })
 2238            .flatten();
 2239
 2240        EditorSnapshot {
 2241            mode: self.mode,
 2242            show_gutter: self.show_gutter,
 2243            show_line_numbers: self.show_line_numbers,
 2244            show_git_diff_gutter: self.show_git_diff_gutter,
 2245            show_code_actions: self.show_code_actions,
 2246            show_runnables: self.show_runnables,
 2247            git_blame_gutter_max_author_length,
 2248            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2249            scroll_anchor: self.scroll_manager.anchor(),
 2250            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2251            placeholder_text: self.placeholder_text.clone(),
 2252            is_focused: self.focus_handle.is_focused(cx),
 2253            current_line_highlight: self
 2254                .current_line_highlight
 2255                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2256            gutter_hovered: self.gutter_hovered,
 2257        }
 2258    }
 2259
 2260    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2261        self.buffer.read(cx).language_at(point, cx)
 2262    }
 2263
 2264    pub fn file_at<T: ToOffset>(
 2265        &self,
 2266        point: T,
 2267        cx: &AppContext,
 2268    ) -> Option<Arc<dyn language::File>> {
 2269        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2270    }
 2271
 2272    pub fn active_excerpt(
 2273        &self,
 2274        cx: &AppContext,
 2275    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2276        self.buffer
 2277            .read(cx)
 2278            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2279    }
 2280
 2281    pub fn mode(&self) -> EditorMode {
 2282        self.mode
 2283    }
 2284
 2285    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2286        self.collaboration_hub.as_deref()
 2287    }
 2288
 2289    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2290        self.collaboration_hub = Some(hub);
 2291    }
 2292
 2293    pub fn set_custom_context_menu(
 2294        &mut self,
 2295        f: impl 'static
 2296            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2297    ) {
 2298        self.custom_context_menu = Some(Box::new(f))
 2299    }
 2300
 2301    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2302        self.completion_provider = Some(provider);
 2303    }
 2304
 2305    pub fn set_inline_completion_provider<T>(
 2306        &mut self,
 2307        provider: Option<Model<T>>,
 2308        cx: &mut ViewContext<Self>,
 2309    ) where
 2310        T: InlineCompletionProvider,
 2311    {
 2312        self.inline_completion_provider =
 2313            provider.map(|provider| RegisteredInlineCompletionProvider {
 2314                _subscription: cx.observe(&provider, |this, _, cx| {
 2315                    if this.focus_handle.is_focused(cx) {
 2316                        this.update_visible_inline_completion(cx);
 2317                    }
 2318                }),
 2319                provider: Arc::new(provider),
 2320            });
 2321        self.refresh_inline_completion(false, false, cx);
 2322    }
 2323
 2324    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2325        self.placeholder_text.as_deref()
 2326    }
 2327
 2328    pub fn set_placeholder_text(
 2329        &mut self,
 2330        placeholder_text: impl Into<Arc<str>>,
 2331        cx: &mut ViewContext<Self>,
 2332    ) {
 2333        let placeholder_text = Some(placeholder_text.into());
 2334        if self.placeholder_text != placeholder_text {
 2335            self.placeholder_text = placeholder_text;
 2336            cx.notify();
 2337        }
 2338    }
 2339
 2340    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2341        self.cursor_shape = cursor_shape;
 2342
 2343        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2344        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2345
 2346        cx.notify();
 2347    }
 2348
 2349    pub fn set_current_line_highlight(
 2350        &mut self,
 2351        current_line_highlight: Option<CurrentLineHighlight>,
 2352    ) {
 2353        self.current_line_highlight = current_line_highlight;
 2354    }
 2355
 2356    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2357        self.collapse_matches = collapse_matches;
 2358    }
 2359
 2360    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2361        if self.collapse_matches {
 2362            return range.start..range.start;
 2363        }
 2364        range.clone()
 2365    }
 2366
 2367    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2368        if self.display_map.read(cx).clip_at_line_ends != clip {
 2369            self.display_map
 2370                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2371        }
 2372    }
 2373
 2374    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2375        self.input_enabled = input_enabled;
 2376    }
 2377
 2378    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2379        self.enable_inline_completions = enabled;
 2380    }
 2381
 2382    pub fn set_autoindent(&mut self, autoindent: bool) {
 2383        if autoindent {
 2384            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2385        } else {
 2386            self.autoindent_mode = None;
 2387        }
 2388    }
 2389
 2390    pub fn read_only(&self, cx: &AppContext) -> bool {
 2391        self.read_only || self.buffer.read(cx).read_only()
 2392    }
 2393
 2394    pub fn set_read_only(&mut self, read_only: bool) {
 2395        self.read_only = read_only;
 2396    }
 2397
 2398    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2399        self.use_autoclose = autoclose;
 2400    }
 2401
 2402    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2403        self.use_auto_surround = auto_surround;
 2404    }
 2405
 2406    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2407        self.auto_replace_emoji_shortcode = auto_replace;
 2408    }
 2409
 2410    pub fn toggle_inline_completions(
 2411        &mut self,
 2412        _: &ToggleInlineCompletions,
 2413        cx: &mut ViewContext<Self>,
 2414    ) {
 2415        if self.show_inline_completions_override.is_some() {
 2416            self.set_show_inline_completions(None, cx);
 2417        } else {
 2418            let cursor = self.selections.newest_anchor().head();
 2419            if let Some((buffer, cursor_buffer_position)) =
 2420                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2421            {
 2422                let show_inline_completions =
 2423                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2424                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2425            }
 2426        }
 2427    }
 2428
 2429    pub fn set_show_inline_completions(
 2430        &mut self,
 2431        show_inline_completions: Option<bool>,
 2432        cx: &mut ViewContext<Self>,
 2433    ) {
 2434        self.show_inline_completions_override = show_inline_completions;
 2435        self.refresh_inline_completion(false, true, cx);
 2436    }
 2437
 2438    fn should_show_inline_completions(
 2439        &self,
 2440        buffer: &Model<Buffer>,
 2441        buffer_position: language::Anchor,
 2442        cx: &AppContext,
 2443    ) -> bool {
 2444        if let Some(provider) = self.inline_completion_provider() {
 2445            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2446                show_inline_completions
 2447            } else {
 2448                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2449            }
 2450        } else {
 2451            false
 2452        }
 2453    }
 2454
 2455    pub fn set_use_modal_editing(&mut self, to: bool) {
 2456        self.use_modal_editing = to;
 2457    }
 2458
 2459    pub fn use_modal_editing(&self) -> bool {
 2460        self.use_modal_editing
 2461    }
 2462
 2463    fn selections_did_change(
 2464        &mut self,
 2465        local: bool,
 2466        old_cursor_position: &Anchor,
 2467        show_completions: bool,
 2468        cx: &mut ViewContext<Self>,
 2469    ) {
 2470        cx.invalidate_character_coordinates();
 2471
 2472        // Copy selections to primary selection buffer
 2473        #[cfg(target_os = "linux")]
 2474        if local {
 2475            let selections = self.selections.all::<usize>(cx);
 2476            let buffer_handle = self.buffer.read(cx).read(cx);
 2477
 2478            let mut text = String::new();
 2479            for (index, selection) in selections.iter().enumerate() {
 2480                let text_for_selection = buffer_handle
 2481                    .text_for_range(selection.start..selection.end)
 2482                    .collect::<String>();
 2483
 2484                text.push_str(&text_for_selection);
 2485                if index != selections.len() - 1 {
 2486                    text.push('\n');
 2487                }
 2488            }
 2489
 2490            if !text.is_empty() {
 2491                cx.write_to_primary(ClipboardItem::new_string(text));
 2492            }
 2493        }
 2494
 2495        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2496            self.buffer.update(cx, |buffer, cx| {
 2497                buffer.set_active_selections(
 2498                    &self.selections.disjoint_anchors(),
 2499                    self.selections.line_mode,
 2500                    self.cursor_shape,
 2501                    cx,
 2502                )
 2503            });
 2504        }
 2505        let display_map = self
 2506            .display_map
 2507            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2508        let buffer = &display_map.buffer_snapshot;
 2509        self.add_selections_state = None;
 2510        self.select_next_state = None;
 2511        self.select_prev_state = None;
 2512        self.select_larger_syntax_node_stack.clear();
 2513        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2514        self.snippet_stack
 2515            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2516        self.take_rename(false, cx);
 2517
 2518        let new_cursor_position = self.selections.newest_anchor().head();
 2519
 2520        self.push_to_nav_history(
 2521            *old_cursor_position,
 2522            Some(new_cursor_position.to_point(buffer)),
 2523            cx,
 2524        );
 2525
 2526        if local {
 2527            let new_cursor_position = self.selections.newest_anchor().head();
 2528            let mut context_menu = self.context_menu.write();
 2529            let completion_menu = match context_menu.as_ref() {
 2530                Some(ContextMenu::Completions(menu)) => Some(menu),
 2531
 2532                _ => {
 2533                    *context_menu = None;
 2534                    None
 2535                }
 2536            };
 2537
 2538            if let Some(completion_menu) = completion_menu {
 2539                let cursor_position = new_cursor_position.to_offset(buffer);
 2540                let (word_range, kind) =
 2541                    buffer.surrounding_word(completion_menu.initial_position, true);
 2542                if kind == Some(CharKind::Word)
 2543                    && word_range.to_inclusive().contains(&cursor_position)
 2544                {
 2545                    let mut completion_menu = completion_menu.clone();
 2546                    drop(context_menu);
 2547
 2548                    let query = Self::completion_query(buffer, cursor_position);
 2549                    cx.spawn(move |this, mut cx| async move {
 2550                        completion_menu
 2551                            .filter(query.as_deref(), cx.background_executor().clone())
 2552                            .await;
 2553
 2554                        this.update(&mut cx, |this, cx| {
 2555                            let mut context_menu = this.context_menu.write();
 2556                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2557                                return;
 2558                            };
 2559
 2560                            if menu.id > completion_menu.id {
 2561                                return;
 2562                            }
 2563
 2564                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2565                            drop(context_menu);
 2566                            cx.notify();
 2567                        })
 2568                    })
 2569                    .detach();
 2570
 2571                    if show_completions {
 2572                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2573                    }
 2574                } else {
 2575                    drop(context_menu);
 2576                    self.hide_context_menu(cx);
 2577                }
 2578            } else {
 2579                drop(context_menu);
 2580            }
 2581
 2582            hide_hover(self, cx);
 2583
 2584            if old_cursor_position.to_display_point(&display_map).row()
 2585                != new_cursor_position.to_display_point(&display_map).row()
 2586            {
 2587                self.available_code_actions.take();
 2588            }
 2589            self.refresh_code_actions(cx);
 2590            self.refresh_document_highlights(cx);
 2591            refresh_matching_bracket_highlights(self, cx);
 2592            self.discard_inline_completion(false, cx);
 2593            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2594            if self.git_blame_inline_enabled {
 2595                self.start_inline_blame_timer(cx);
 2596            }
 2597        }
 2598
 2599        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2600        cx.emit(EditorEvent::SelectionsChanged { local });
 2601
 2602        if self.selections.disjoint_anchors().len() == 1 {
 2603            cx.emit(SearchEvent::ActiveMatchChanged)
 2604        }
 2605        cx.notify();
 2606    }
 2607
 2608    pub fn change_selections<R>(
 2609        &mut self,
 2610        autoscroll: Option<Autoscroll>,
 2611        cx: &mut ViewContext<Self>,
 2612        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2613    ) -> R {
 2614        self.change_selections_inner(autoscroll, true, cx, change)
 2615    }
 2616
 2617    pub fn change_selections_inner<R>(
 2618        &mut self,
 2619        autoscroll: Option<Autoscroll>,
 2620        request_completions: bool,
 2621        cx: &mut ViewContext<Self>,
 2622        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2623    ) -> R {
 2624        let old_cursor_position = self.selections.newest_anchor().head();
 2625        self.push_to_selection_history();
 2626
 2627        let (changed, result) = self.selections.change_with(cx, change);
 2628
 2629        if changed {
 2630            if let Some(autoscroll) = autoscroll {
 2631                self.request_autoscroll(autoscroll, cx);
 2632            }
 2633            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2634
 2635            if self.should_open_signature_help_automatically(
 2636                &old_cursor_position,
 2637                self.signature_help_state.backspace_pressed(),
 2638                cx,
 2639            ) {
 2640                self.show_signature_help(&ShowSignatureHelp, cx);
 2641            }
 2642            self.signature_help_state.set_backspace_pressed(false);
 2643        }
 2644
 2645        result
 2646    }
 2647
 2648    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2649    where
 2650        I: IntoIterator<Item = (Range<S>, T)>,
 2651        S: ToOffset,
 2652        T: Into<Arc<str>>,
 2653    {
 2654        if self.read_only(cx) {
 2655            return;
 2656        }
 2657
 2658        self.buffer
 2659            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2660    }
 2661
 2662    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2663    where
 2664        I: IntoIterator<Item = (Range<S>, T)>,
 2665        S: ToOffset,
 2666        T: Into<Arc<str>>,
 2667    {
 2668        if self.read_only(cx) {
 2669            return;
 2670        }
 2671
 2672        self.buffer.update(cx, |buffer, cx| {
 2673            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2674        });
 2675    }
 2676
 2677    pub fn edit_with_block_indent<I, S, T>(
 2678        &mut self,
 2679        edits: I,
 2680        original_indent_columns: Vec<u32>,
 2681        cx: &mut ViewContext<Self>,
 2682    ) where
 2683        I: IntoIterator<Item = (Range<S>, T)>,
 2684        S: ToOffset,
 2685        T: Into<Arc<str>>,
 2686    {
 2687        if self.read_only(cx) {
 2688            return;
 2689        }
 2690
 2691        self.buffer.update(cx, |buffer, cx| {
 2692            buffer.edit(
 2693                edits,
 2694                Some(AutoindentMode::Block {
 2695                    original_indent_columns,
 2696                }),
 2697                cx,
 2698            )
 2699        });
 2700    }
 2701
 2702    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2703        self.hide_context_menu(cx);
 2704
 2705        match phase {
 2706            SelectPhase::Begin {
 2707                position,
 2708                add,
 2709                click_count,
 2710            } => self.begin_selection(position, add, click_count, cx),
 2711            SelectPhase::BeginColumnar {
 2712                position,
 2713                goal_column,
 2714                reset,
 2715            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2716            SelectPhase::Extend {
 2717                position,
 2718                click_count,
 2719            } => self.extend_selection(position, click_count, cx),
 2720            SelectPhase::Update {
 2721                position,
 2722                goal_column,
 2723                scroll_delta,
 2724            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2725            SelectPhase::End => self.end_selection(cx),
 2726        }
 2727    }
 2728
 2729    fn extend_selection(
 2730        &mut self,
 2731        position: DisplayPoint,
 2732        click_count: usize,
 2733        cx: &mut ViewContext<Self>,
 2734    ) {
 2735        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2736        let tail = self.selections.newest::<usize>(cx).tail();
 2737        self.begin_selection(position, false, click_count, cx);
 2738
 2739        let position = position.to_offset(&display_map, Bias::Left);
 2740        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2741
 2742        let mut pending_selection = self
 2743            .selections
 2744            .pending_anchor()
 2745            .expect("extend_selection not called with pending selection");
 2746        if position >= tail {
 2747            pending_selection.start = tail_anchor;
 2748        } else {
 2749            pending_selection.end = tail_anchor;
 2750            pending_selection.reversed = true;
 2751        }
 2752
 2753        let mut pending_mode = self.selections.pending_mode().unwrap();
 2754        match &mut pending_mode {
 2755            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2756            _ => {}
 2757        }
 2758
 2759        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2760            s.set_pending(pending_selection, pending_mode)
 2761        });
 2762    }
 2763
 2764    fn begin_selection(
 2765        &mut self,
 2766        position: DisplayPoint,
 2767        add: bool,
 2768        click_count: usize,
 2769        cx: &mut ViewContext<Self>,
 2770    ) {
 2771        if !self.focus_handle.is_focused(cx) {
 2772            self.last_focused_descendant = None;
 2773            cx.focus(&self.focus_handle);
 2774        }
 2775
 2776        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2777        let buffer = &display_map.buffer_snapshot;
 2778        let newest_selection = self.selections.newest_anchor().clone();
 2779        let position = display_map.clip_point(position, Bias::Left);
 2780
 2781        let start;
 2782        let end;
 2783        let mode;
 2784        let auto_scroll;
 2785        match click_count {
 2786            1 => {
 2787                start = buffer.anchor_before(position.to_point(&display_map));
 2788                end = start;
 2789                mode = SelectMode::Character;
 2790                auto_scroll = true;
 2791            }
 2792            2 => {
 2793                let range = movement::surrounding_word(&display_map, position);
 2794                start = buffer.anchor_before(range.start.to_point(&display_map));
 2795                end = buffer.anchor_before(range.end.to_point(&display_map));
 2796                mode = SelectMode::Word(start..end);
 2797                auto_scroll = true;
 2798            }
 2799            3 => {
 2800                let position = display_map
 2801                    .clip_point(position, Bias::Left)
 2802                    .to_point(&display_map);
 2803                let line_start = display_map.prev_line_boundary(position).0;
 2804                let next_line_start = buffer.clip_point(
 2805                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2806                    Bias::Left,
 2807                );
 2808                start = buffer.anchor_before(line_start);
 2809                end = buffer.anchor_before(next_line_start);
 2810                mode = SelectMode::Line(start..end);
 2811                auto_scroll = true;
 2812            }
 2813            _ => {
 2814                start = buffer.anchor_before(0);
 2815                end = buffer.anchor_before(buffer.len());
 2816                mode = SelectMode::All;
 2817                auto_scroll = false;
 2818            }
 2819        }
 2820
 2821        let point_to_delete: Option<usize> = {
 2822            let selected_points: Vec<Selection<Point>> =
 2823                self.selections.disjoint_in_range(start..end, cx);
 2824
 2825            if !add || click_count > 1 {
 2826                None
 2827            } else if !selected_points.is_empty() {
 2828                Some(selected_points[0].id)
 2829            } else {
 2830                let clicked_point_already_selected =
 2831                    self.selections.disjoint.iter().find(|selection| {
 2832                        selection.start.to_point(buffer) == start.to_point(buffer)
 2833                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2834                    });
 2835
 2836                clicked_point_already_selected.map(|selection| selection.id)
 2837            }
 2838        };
 2839
 2840        let selections_count = self.selections.count();
 2841
 2842        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2843            if let Some(point_to_delete) = point_to_delete {
 2844                s.delete(point_to_delete);
 2845
 2846                if selections_count == 1 {
 2847                    s.set_pending_anchor_range(start..end, mode);
 2848                }
 2849            } else {
 2850                if !add {
 2851                    s.clear_disjoint();
 2852                } else if click_count > 1 {
 2853                    s.delete(newest_selection.id)
 2854                }
 2855
 2856                s.set_pending_anchor_range(start..end, mode);
 2857            }
 2858        });
 2859    }
 2860
 2861    fn begin_columnar_selection(
 2862        &mut self,
 2863        position: DisplayPoint,
 2864        goal_column: u32,
 2865        reset: bool,
 2866        cx: &mut ViewContext<Self>,
 2867    ) {
 2868        if !self.focus_handle.is_focused(cx) {
 2869            self.last_focused_descendant = None;
 2870            cx.focus(&self.focus_handle);
 2871        }
 2872
 2873        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2874
 2875        if reset {
 2876            let pointer_position = display_map
 2877                .buffer_snapshot
 2878                .anchor_before(position.to_point(&display_map));
 2879
 2880            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2881                s.clear_disjoint();
 2882                s.set_pending_anchor_range(
 2883                    pointer_position..pointer_position,
 2884                    SelectMode::Character,
 2885                );
 2886            });
 2887        }
 2888
 2889        let tail = self.selections.newest::<Point>(cx).tail();
 2890        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2891
 2892        if !reset {
 2893            self.select_columns(
 2894                tail.to_display_point(&display_map),
 2895                position,
 2896                goal_column,
 2897                &display_map,
 2898                cx,
 2899            );
 2900        }
 2901    }
 2902
 2903    fn update_selection(
 2904        &mut self,
 2905        position: DisplayPoint,
 2906        goal_column: u32,
 2907        scroll_delta: gpui::Point<f32>,
 2908        cx: &mut ViewContext<Self>,
 2909    ) {
 2910        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2911
 2912        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2913            let tail = tail.to_display_point(&display_map);
 2914            self.select_columns(tail, position, goal_column, &display_map, cx);
 2915        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2916            let buffer = self.buffer.read(cx).snapshot(cx);
 2917            let head;
 2918            let tail;
 2919            let mode = self.selections.pending_mode().unwrap();
 2920            match &mode {
 2921                SelectMode::Character => {
 2922                    head = position.to_point(&display_map);
 2923                    tail = pending.tail().to_point(&buffer);
 2924                }
 2925                SelectMode::Word(original_range) => {
 2926                    let original_display_range = original_range.start.to_display_point(&display_map)
 2927                        ..original_range.end.to_display_point(&display_map);
 2928                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2929                        ..original_display_range.end.to_point(&display_map);
 2930                    if movement::is_inside_word(&display_map, position)
 2931                        || original_display_range.contains(&position)
 2932                    {
 2933                        let word_range = movement::surrounding_word(&display_map, position);
 2934                        if word_range.start < original_display_range.start {
 2935                            head = word_range.start.to_point(&display_map);
 2936                        } else {
 2937                            head = word_range.end.to_point(&display_map);
 2938                        }
 2939                    } else {
 2940                        head = position.to_point(&display_map);
 2941                    }
 2942
 2943                    if head <= original_buffer_range.start {
 2944                        tail = original_buffer_range.end;
 2945                    } else {
 2946                        tail = original_buffer_range.start;
 2947                    }
 2948                }
 2949                SelectMode::Line(original_range) => {
 2950                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2951
 2952                    let position = display_map
 2953                        .clip_point(position, Bias::Left)
 2954                        .to_point(&display_map);
 2955                    let line_start = display_map.prev_line_boundary(position).0;
 2956                    let next_line_start = buffer.clip_point(
 2957                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2958                        Bias::Left,
 2959                    );
 2960
 2961                    if line_start < original_range.start {
 2962                        head = line_start
 2963                    } else {
 2964                        head = next_line_start
 2965                    }
 2966
 2967                    if head <= original_range.start {
 2968                        tail = original_range.end;
 2969                    } else {
 2970                        tail = original_range.start;
 2971                    }
 2972                }
 2973                SelectMode::All => {
 2974                    return;
 2975                }
 2976            };
 2977
 2978            if head < tail {
 2979                pending.start = buffer.anchor_before(head);
 2980                pending.end = buffer.anchor_before(tail);
 2981                pending.reversed = true;
 2982            } else {
 2983                pending.start = buffer.anchor_before(tail);
 2984                pending.end = buffer.anchor_before(head);
 2985                pending.reversed = false;
 2986            }
 2987
 2988            self.change_selections(None, cx, |s| {
 2989                s.set_pending(pending, mode);
 2990            });
 2991        } else {
 2992            log::error!("update_selection dispatched with no pending selection");
 2993            return;
 2994        }
 2995
 2996        self.apply_scroll_delta(scroll_delta, cx);
 2997        cx.notify();
 2998    }
 2999
 3000    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3001        self.columnar_selection_tail.take();
 3002        if self.selections.pending_anchor().is_some() {
 3003            let selections = self.selections.all::<usize>(cx);
 3004            self.change_selections(None, cx, |s| {
 3005                s.select(selections);
 3006                s.clear_pending();
 3007            });
 3008        }
 3009    }
 3010
 3011    fn select_columns(
 3012        &mut self,
 3013        tail: DisplayPoint,
 3014        head: DisplayPoint,
 3015        goal_column: u32,
 3016        display_map: &DisplaySnapshot,
 3017        cx: &mut ViewContext<Self>,
 3018    ) {
 3019        let start_row = cmp::min(tail.row(), head.row());
 3020        let end_row = cmp::max(tail.row(), head.row());
 3021        let start_column = cmp::min(tail.column(), goal_column);
 3022        let end_column = cmp::max(tail.column(), goal_column);
 3023        let reversed = start_column < tail.column();
 3024
 3025        let selection_ranges = (start_row.0..=end_row.0)
 3026            .map(DisplayRow)
 3027            .filter_map(|row| {
 3028                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3029                    let start = display_map
 3030                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3031                        .to_point(display_map);
 3032                    let end = display_map
 3033                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3034                        .to_point(display_map);
 3035                    if reversed {
 3036                        Some(end..start)
 3037                    } else {
 3038                        Some(start..end)
 3039                    }
 3040                } else {
 3041                    None
 3042                }
 3043            })
 3044            .collect::<Vec<_>>();
 3045
 3046        self.change_selections(None, cx, |s| {
 3047            s.select_ranges(selection_ranges);
 3048        });
 3049        cx.notify();
 3050    }
 3051
 3052    pub fn has_pending_nonempty_selection(&self) -> bool {
 3053        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3054            Some(Selection { start, end, .. }) => start != end,
 3055            None => false,
 3056        };
 3057
 3058        pending_nonempty_selection
 3059            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3060    }
 3061
 3062    pub fn has_pending_selection(&self) -> bool {
 3063        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3064    }
 3065
 3066    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3067        if self.clear_expanded_diff_hunks(cx) {
 3068            cx.notify();
 3069            return;
 3070        }
 3071        if self.dismiss_menus_and_popups(true, cx) {
 3072            return;
 3073        }
 3074
 3075        if self.mode == EditorMode::Full
 3076            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3077        {
 3078            return;
 3079        }
 3080
 3081        cx.propagate();
 3082    }
 3083
 3084    pub fn dismiss_menus_and_popups(
 3085        &mut self,
 3086        should_report_inline_completion_event: bool,
 3087        cx: &mut ViewContext<Self>,
 3088    ) -> bool {
 3089        if self.take_rename(false, cx).is_some() {
 3090            return true;
 3091        }
 3092
 3093        if hide_hover(self, cx) {
 3094            return true;
 3095        }
 3096
 3097        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3098            return true;
 3099        }
 3100
 3101        if self.hide_context_menu(cx).is_some() {
 3102            return true;
 3103        }
 3104
 3105        if self.mouse_context_menu.take().is_some() {
 3106            return true;
 3107        }
 3108
 3109        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3110            return true;
 3111        }
 3112
 3113        if self.snippet_stack.pop().is_some() {
 3114            return true;
 3115        }
 3116
 3117        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3118            self.dismiss_diagnostics(cx);
 3119            return true;
 3120        }
 3121
 3122        false
 3123    }
 3124
 3125    fn linked_editing_ranges_for(
 3126        &self,
 3127        selection: Range<text::Anchor>,
 3128        cx: &AppContext,
 3129    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3130        if self.linked_edit_ranges.is_empty() {
 3131            return None;
 3132        }
 3133        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3134            selection.end.buffer_id.and_then(|end_buffer_id| {
 3135                if selection.start.buffer_id != Some(end_buffer_id) {
 3136                    return None;
 3137                }
 3138                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3139                let snapshot = buffer.read(cx).snapshot();
 3140                self.linked_edit_ranges
 3141                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3142                    .map(|ranges| (ranges, snapshot, buffer))
 3143            })?;
 3144        use text::ToOffset as TO;
 3145        // find offset from the start of current range to current cursor position
 3146        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3147
 3148        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3149        let start_difference = start_offset - start_byte_offset;
 3150        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3151        let end_difference = end_offset - start_byte_offset;
 3152        // Current range has associated linked ranges.
 3153        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3154        for range in linked_ranges.iter() {
 3155            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3156            let end_offset = start_offset + end_difference;
 3157            let start_offset = start_offset + start_difference;
 3158            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3159                continue;
 3160            }
 3161            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3162                if s.start.buffer_id != selection.start.buffer_id
 3163                    || s.end.buffer_id != selection.end.buffer_id
 3164                {
 3165                    return false;
 3166                }
 3167                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3168                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3169            }) {
 3170                continue;
 3171            }
 3172            let start = buffer_snapshot.anchor_after(start_offset);
 3173            let end = buffer_snapshot.anchor_after(end_offset);
 3174            linked_edits
 3175                .entry(buffer.clone())
 3176                .or_default()
 3177                .push(start..end);
 3178        }
 3179        Some(linked_edits)
 3180    }
 3181
 3182    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3183        let text: Arc<str> = text.into();
 3184
 3185        if self.read_only(cx) {
 3186            return;
 3187        }
 3188
 3189        let selections = self.selections.all_adjusted(cx);
 3190        let mut bracket_inserted = false;
 3191        let mut edits = Vec::new();
 3192        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3193        let mut new_selections = Vec::with_capacity(selections.len());
 3194        let mut new_autoclose_regions = Vec::new();
 3195        let snapshot = self.buffer.read(cx).read(cx);
 3196
 3197        for (selection, autoclose_region) in
 3198            self.selections_with_autoclose_regions(selections, &snapshot)
 3199        {
 3200            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3201                // Determine if the inserted text matches the opening or closing
 3202                // bracket of any of this language's bracket pairs.
 3203                let mut bracket_pair = None;
 3204                let mut is_bracket_pair_start = false;
 3205                let mut is_bracket_pair_end = false;
 3206                if !text.is_empty() {
 3207                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3208                    //  and they are removing the character that triggered IME popup.
 3209                    for (pair, enabled) in scope.brackets() {
 3210                        if !pair.close && !pair.surround {
 3211                            continue;
 3212                        }
 3213
 3214                        if enabled && pair.start.ends_with(text.as_ref()) {
 3215                            bracket_pair = Some(pair.clone());
 3216                            is_bracket_pair_start = true;
 3217                            break;
 3218                        }
 3219                        if pair.end.as_str() == text.as_ref() {
 3220                            bracket_pair = Some(pair.clone());
 3221                            is_bracket_pair_end = true;
 3222                            break;
 3223                        }
 3224                    }
 3225                }
 3226
 3227                if let Some(bracket_pair) = bracket_pair {
 3228                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3229                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3230                    let auto_surround =
 3231                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3232                    if selection.is_empty() {
 3233                        if is_bracket_pair_start {
 3234                            let prefix_len = bracket_pair.start.len() - text.len();
 3235
 3236                            // If the inserted text is a suffix of an opening bracket and the
 3237                            // selection is preceded by the rest of the opening bracket, then
 3238                            // insert the closing bracket.
 3239                            let following_text_allows_autoclose = snapshot
 3240                                .chars_at(selection.start)
 3241                                .next()
 3242                                .map_or(true, |c| scope.should_autoclose_before(c));
 3243                            let preceding_text_matches_prefix = prefix_len == 0
 3244                                || (selection.start.column >= (prefix_len as u32)
 3245                                    && snapshot.contains_str_at(
 3246                                        Point::new(
 3247                                            selection.start.row,
 3248                                            selection.start.column - (prefix_len as u32),
 3249                                        ),
 3250                                        &bracket_pair.start[..prefix_len],
 3251                                    ));
 3252
 3253                            if autoclose
 3254                                && bracket_pair.close
 3255                                && following_text_allows_autoclose
 3256                                && preceding_text_matches_prefix
 3257                            {
 3258                                let anchor = snapshot.anchor_before(selection.end);
 3259                                new_selections.push((selection.map(|_| anchor), text.len()));
 3260                                new_autoclose_regions.push((
 3261                                    anchor,
 3262                                    text.len(),
 3263                                    selection.id,
 3264                                    bracket_pair.clone(),
 3265                                ));
 3266                                edits.push((
 3267                                    selection.range(),
 3268                                    format!("{}{}", text, bracket_pair.end).into(),
 3269                                ));
 3270                                bracket_inserted = true;
 3271                                continue;
 3272                            }
 3273                        }
 3274
 3275                        if let Some(region) = autoclose_region {
 3276                            // If the selection is followed by an auto-inserted closing bracket,
 3277                            // then don't insert that closing bracket again; just move the selection
 3278                            // past the closing bracket.
 3279                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3280                                && text.as_ref() == region.pair.end.as_str();
 3281                            if should_skip {
 3282                                let anchor = snapshot.anchor_after(selection.end);
 3283                                new_selections
 3284                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3285                                continue;
 3286                            }
 3287                        }
 3288
 3289                        let always_treat_brackets_as_autoclosed = snapshot
 3290                            .settings_at(selection.start, cx)
 3291                            .always_treat_brackets_as_autoclosed;
 3292                        if always_treat_brackets_as_autoclosed
 3293                            && is_bracket_pair_end
 3294                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3295                        {
 3296                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3297                            // and the inserted text is a closing bracket and the selection is followed
 3298                            // by the closing bracket then move the selection past the closing bracket.
 3299                            let anchor = snapshot.anchor_after(selection.end);
 3300                            new_selections.push((selection.map(|_| anchor), text.len()));
 3301                            continue;
 3302                        }
 3303                    }
 3304                    // If an opening bracket is 1 character long and is typed while
 3305                    // text is selected, then surround that text with the bracket pair.
 3306                    else if auto_surround
 3307                        && bracket_pair.surround
 3308                        && is_bracket_pair_start
 3309                        && bracket_pair.start.chars().count() == 1
 3310                    {
 3311                        edits.push((selection.start..selection.start, text.clone()));
 3312                        edits.push((
 3313                            selection.end..selection.end,
 3314                            bracket_pair.end.as_str().into(),
 3315                        ));
 3316                        bracket_inserted = true;
 3317                        new_selections.push((
 3318                            Selection {
 3319                                id: selection.id,
 3320                                start: snapshot.anchor_after(selection.start),
 3321                                end: snapshot.anchor_before(selection.end),
 3322                                reversed: selection.reversed,
 3323                                goal: selection.goal,
 3324                            },
 3325                            0,
 3326                        ));
 3327                        continue;
 3328                    }
 3329                }
 3330            }
 3331
 3332            if self.auto_replace_emoji_shortcode
 3333                && selection.is_empty()
 3334                && text.as_ref().ends_with(':')
 3335            {
 3336                if let Some(possible_emoji_short_code) =
 3337                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3338                {
 3339                    if !possible_emoji_short_code.is_empty() {
 3340                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3341                            let emoji_shortcode_start = Point::new(
 3342                                selection.start.row,
 3343                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3344                            );
 3345
 3346                            // Remove shortcode from buffer
 3347                            edits.push((
 3348                                emoji_shortcode_start..selection.start,
 3349                                "".to_string().into(),
 3350                            ));
 3351                            new_selections.push((
 3352                                Selection {
 3353                                    id: selection.id,
 3354                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3355                                    end: snapshot.anchor_before(selection.start),
 3356                                    reversed: selection.reversed,
 3357                                    goal: selection.goal,
 3358                                },
 3359                                0,
 3360                            ));
 3361
 3362                            // Insert emoji
 3363                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3364                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3365                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3366
 3367                            continue;
 3368                        }
 3369                    }
 3370                }
 3371            }
 3372
 3373            // If not handling any auto-close operation, then just replace the selected
 3374            // text with the given input and move the selection to the end of the
 3375            // newly inserted text.
 3376            let anchor = snapshot.anchor_after(selection.end);
 3377            if !self.linked_edit_ranges.is_empty() {
 3378                let start_anchor = snapshot.anchor_before(selection.start);
 3379
 3380                let is_word_char = text.chars().next().map_or(true, |char| {
 3381                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3382                    classifier.is_word(char)
 3383                });
 3384
 3385                if is_word_char {
 3386                    if let Some(ranges) = self
 3387                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3388                    {
 3389                        for (buffer, edits) in ranges {
 3390                            linked_edits
 3391                                .entry(buffer.clone())
 3392                                .or_default()
 3393                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3394                        }
 3395                    }
 3396                }
 3397            }
 3398
 3399            new_selections.push((selection.map(|_| anchor), 0));
 3400            edits.push((selection.start..selection.end, text.clone()));
 3401        }
 3402
 3403        drop(snapshot);
 3404
 3405        self.transact(cx, |this, cx| {
 3406            this.buffer.update(cx, |buffer, cx| {
 3407                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3408            });
 3409            for (buffer, edits) in linked_edits {
 3410                buffer.update(cx, |buffer, cx| {
 3411                    let snapshot = buffer.snapshot();
 3412                    let edits = edits
 3413                        .into_iter()
 3414                        .map(|(range, text)| {
 3415                            use text::ToPoint as TP;
 3416                            let end_point = TP::to_point(&range.end, &snapshot);
 3417                            let start_point = TP::to_point(&range.start, &snapshot);
 3418                            (start_point..end_point, text)
 3419                        })
 3420                        .sorted_by_key(|(range, _)| range.start)
 3421                        .collect::<Vec<_>>();
 3422                    buffer.edit(edits, None, cx);
 3423                })
 3424            }
 3425            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3426            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3427            let snapshot = this.buffer.read(cx).read(cx);
 3428            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3429                .zip(new_selection_deltas)
 3430                .map(|(selection, delta)| Selection {
 3431                    id: selection.id,
 3432                    start: selection.start + delta,
 3433                    end: selection.end + delta,
 3434                    reversed: selection.reversed,
 3435                    goal: SelectionGoal::None,
 3436                })
 3437                .collect::<Vec<_>>();
 3438
 3439            let mut i = 0;
 3440            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3441                let position = position.to_offset(&snapshot) + delta;
 3442                let start = snapshot.anchor_before(position);
 3443                let end = snapshot.anchor_after(position);
 3444                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3445                    match existing_state.range.start.cmp(&start, &snapshot) {
 3446                        Ordering::Less => i += 1,
 3447                        Ordering::Greater => break,
 3448                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3449                            Ordering::Less => i += 1,
 3450                            Ordering::Equal => break,
 3451                            Ordering::Greater => break,
 3452                        },
 3453                    }
 3454                }
 3455                this.autoclose_regions.insert(
 3456                    i,
 3457                    AutocloseRegion {
 3458                        selection_id,
 3459                        range: start..end,
 3460                        pair,
 3461                    },
 3462                );
 3463            }
 3464
 3465            drop(snapshot);
 3466            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3467            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3468                s.select(new_selections)
 3469            });
 3470
 3471            if !bracket_inserted {
 3472                if let Some(on_type_format_task) =
 3473                    this.trigger_on_type_formatting(text.to_string(), cx)
 3474                {
 3475                    on_type_format_task.detach_and_log_err(cx);
 3476                }
 3477            }
 3478
 3479            let editor_settings = EditorSettings::get_global(cx);
 3480            if bracket_inserted
 3481                && (editor_settings.auto_signature_help
 3482                    || editor_settings.show_signature_help_after_edits)
 3483            {
 3484                this.show_signature_help(&ShowSignatureHelp, cx);
 3485            }
 3486
 3487            let trigger_in_words = !had_active_inline_completion;
 3488            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3489            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3490            this.refresh_inline_completion(true, false, cx);
 3491        });
 3492    }
 3493
 3494    fn find_possible_emoji_shortcode_at_position(
 3495        snapshot: &MultiBufferSnapshot,
 3496        position: Point,
 3497    ) -> Option<String> {
 3498        let mut chars = Vec::new();
 3499        let mut found_colon = false;
 3500        for char in snapshot.reversed_chars_at(position).take(100) {
 3501            // Found a possible emoji shortcode in the middle of the buffer
 3502            if found_colon {
 3503                if char.is_whitespace() {
 3504                    chars.reverse();
 3505                    return Some(chars.iter().collect());
 3506                }
 3507                // If the previous character is not a whitespace, we are in the middle of a word
 3508                // and we only want to complete the shortcode if the word is made up of other emojis
 3509                let mut containing_word = String::new();
 3510                for ch in snapshot
 3511                    .reversed_chars_at(position)
 3512                    .skip(chars.len() + 1)
 3513                    .take(100)
 3514                {
 3515                    if ch.is_whitespace() {
 3516                        break;
 3517                    }
 3518                    containing_word.push(ch);
 3519                }
 3520                let containing_word = containing_word.chars().rev().collect::<String>();
 3521                if util::word_consists_of_emojis(containing_word.as_str()) {
 3522                    chars.reverse();
 3523                    return Some(chars.iter().collect());
 3524                }
 3525            }
 3526
 3527            if char.is_whitespace() || !char.is_ascii() {
 3528                return None;
 3529            }
 3530            if char == ':' {
 3531                found_colon = true;
 3532            } else {
 3533                chars.push(char);
 3534            }
 3535        }
 3536        // Found a possible emoji shortcode at the beginning of the buffer
 3537        chars.reverse();
 3538        Some(chars.iter().collect())
 3539    }
 3540
 3541    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3542        self.transact(cx, |this, cx| {
 3543            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3544                let selections = this.selections.all::<usize>(cx);
 3545                let multi_buffer = this.buffer.read(cx);
 3546                let buffer = multi_buffer.snapshot(cx);
 3547                selections
 3548                    .iter()
 3549                    .map(|selection| {
 3550                        let start_point = selection.start.to_point(&buffer);
 3551                        let mut indent =
 3552                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3553                        indent.len = cmp::min(indent.len, start_point.column);
 3554                        let start = selection.start;
 3555                        let end = selection.end;
 3556                        let selection_is_empty = start == end;
 3557                        let language_scope = buffer.language_scope_at(start);
 3558                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3559                            &language_scope
 3560                        {
 3561                            let leading_whitespace_len = buffer
 3562                                .reversed_chars_at(start)
 3563                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3564                                .map(|c| c.len_utf8())
 3565                                .sum::<usize>();
 3566
 3567                            let trailing_whitespace_len = buffer
 3568                                .chars_at(end)
 3569                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3570                                .map(|c| c.len_utf8())
 3571                                .sum::<usize>();
 3572
 3573                            let insert_extra_newline =
 3574                                language.brackets().any(|(pair, enabled)| {
 3575                                    let pair_start = pair.start.trim_end();
 3576                                    let pair_end = pair.end.trim_start();
 3577
 3578                                    enabled
 3579                                        && pair.newline
 3580                                        && buffer.contains_str_at(
 3581                                            end + trailing_whitespace_len,
 3582                                            pair_end,
 3583                                        )
 3584                                        && buffer.contains_str_at(
 3585                                            (start - leading_whitespace_len)
 3586                                                .saturating_sub(pair_start.len()),
 3587                                            pair_start,
 3588                                        )
 3589                                });
 3590
 3591                            // Comment extension on newline is allowed only for cursor selections
 3592                            let comment_delimiter = maybe!({
 3593                                if !selection_is_empty {
 3594                                    return None;
 3595                                }
 3596
 3597                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3598                                    return None;
 3599                                }
 3600
 3601                                let delimiters = language.line_comment_prefixes();
 3602                                let max_len_of_delimiter =
 3603                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3604                                let (snapshot, range) =
 3605                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3606
 3607                                let mut index_of_first_non_whitespace = 0;
 3608                                let comment_candidate = snapshot
 3609                                    .chars_for_range(range)
 3610                                    .skip_while(|c| {
 3611                                        let should_skip = c.is_whitespace();
 3612                                        if should_skip {
 3613                                            index_of_first_non_whitespace += 1;
 3614                                        }
 3615                                        should_skip
 3616                                    })
 3617                                    .take(max_len_of_delimiter)
 3618                                    .collect::<String>();
 3619                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3620                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3621                                })?;
 3622                                let cursor_is_placed_after_comment_marker =
 3623                                    index_of_first_non_whitespace + comment_prefix.len()
 3624                                        <= start_point.column as usize;
 3625                                if cursor_is_placed_after_comment_marker {
 3626                                    Some(comment_prefix.clone())
 3627                                } else {
 3628                                    None
 3629                                }
 3630                            });
 3631                            (comment_delimiter, insert_extra_newline)
 3632                        } else {
 3633                            (None, false)
 3634                        };
 3635
 3636                        let capacity_for_delimiter = comment_delimiter
 3637                            .as_deref()
 3638                            .map(str::len)
 3639                            .unwrap_or_default();
 3640                        let mut new_text =
 3641                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3642                        new_text.push('\n');
 3643                        new_text.extend(indent.chars());
 3644                        if let Some(delimiter) = &comment_delimiter {
 3645                            new_text.push_str(delimiter);
 3646                        }
 3647                        if insert_extra_newline {
 3648                            new_text = new_text.repeat(2);
 3649                        }
 3650
 3651                        let anchor = buffer.anchor_after(end);
 3652                        let new_selection = selection.map(|_| anchor);
 3653                        (
 3654                            (start..end, new_text),
 3655                            (insert_extra_newline, new_selection),
 3656                        )
 3657                    })
 3658                    .unzip()
 3659            };
 3660
 3661            this.edit_with_autoindent(edits, cx);
 3662            let buffer = this.buffer.read(cx).snapshot(cx);
 3663            let new_selections = selection_fixup_info
 3664                .into_iter()
 3665                .map(|(extra_newline_inserted, new_selection)| {
 3666                    let mut cursor = new_selection.end.to_point(&buffer);
 3667                    if extra_newline_inserted {
 3668                        cursor.row -= 1;
 3669                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3670                    }
 3671                    new_selection.map(|_| cursor)
 3672                })
 3673                .collect();
 3674
 3675            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3676            this.refresh_inline_completion(true, false, cx);
 3677        });
 3678    }
 3679
 3680    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3681        let buffer = self.buffer.read(cx);
 3682        let snapshot = buffer.snapshot(cx);
 3683
 3684        let mut edits = Vec::new();
 3685        let mut rows = Vec::new();
 3686
 3687        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3688            let cursor = selection.head();
 3689            let row = cursor.row;
 3690
 3691            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3692
 3693            let newline = "\n".to_string();
 3694            edits.push((start_of_line..start_of_line, newline));
 3695
 3696            rows.push(row + rows_inserted as u32);
 3697        }
 3698
 3699        self.transact(cx, |editor, cx| {
 3700            editor.edit(edits, cx);
 3701
 3702            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3703                let mut index = 0;
 3704                s.move_cursors_with(|map, _, _| {
 3705                    let row = rows[index];
 3706                    index += 1;
 3707
 3708                    let point = Point::new(row, 0);
 3709                    let boundary = map.next_line_boundary(point).1;
 3710                    let clipped = map.clip_point(boundary, Bias::Left);
 3711
 3712                    (clipped, SelectionGoal::None)
 3713                });
 3714            });
 3715
 3716            let mut indent_edits = Vec::new();
 3717            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3718            for row in rows {
 3719                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3720                for (row, indent) in indents {
 3721                    if indent.len == 0 {
 3722                        continue;
 3723                    }
 3724
 3725                    let text = match indent.kind {
 3726                        IndentKind::Space => " ".repeat(indent.len as usize),
 3727                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3728                    };
 3729                    let point = Point::new(row.0, 0);
 3730                    indent_edits.push((point..point, text));
 3731                }
 3732            }
 3733            editor.edit(indent_edits, cx);
 3734        });
 3735    }
 3736
 3737    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3738        let buffer = self.buffer.read(cx);
 3739        let snapshot = buffer.snapshot(cx);
 3740
 3741        let mut edits = Vec::new();
 3742        let mut rows = Vec::new();
 3743        let mut rows_inserted = 0;
 3744
 3745        for selection in self.selections.all_adjusted(cx) {
 3746            let cursor = selection.head();
 3747            let row = cursor.row;
 3748
 3749            let point = Point::new(row + 1, 0);
 3750            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3751
 3752            let newline = "\n".to_string();
 3753            edits.push((start_of_line..start_of_line, newline));
 3754
 3755            rows_inserted += 1;
 3756            rows.push(row + rows_inserted);
 3757        }
 3758
 3759        self.transact(cx, |editor, cx| {
 3760            editor.edit(edits, cx);
 3761
 3762            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3763                let mut index = 0;
 3764                s.move_cursors_with(|map, _, _| {
 3765                    let row = rows[index];
 3766                    index += 1;
 3767
 3768                    let point = Point::new(row, 0);
 3769                    let boundary = map.next_line_boundary(point).1;
 3770                    let clipped = map.clip_point(boundary, Bias::Left);
 3771
 3772                    (clipped, SelectionGoal::None)
 3773                });
 3774            });
 3775
 3776            let mut indent_edits = Vec::new();
 3777            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3778            for row in rows {
 3779                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3780                for (row, indent) in indents {
 3781                    if indent.len == 0 {
 3782                        continue;
 3783                    }
 3784
 3785                    let text = match indent.kind {
 3786                        IndentKind::Space => " ".repeat(indent.len as usize),
 3787                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3788                    };
 3789                    let point = Point::new(row.0, 0);
 3790                    indent_edits.push((point..point, text));
 3791                }
 3792            }
 3793            editor.edit(indent_edits, cx);
 3794        });
 3795    }
 3796
 3797    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3798        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3799            original_indent_columns: Vec::new(),
 3800        });
 3801        self.insert_with_autoindent_mode(text, autoindent, cx);
 3802    }
 3803
 3804    fn insert_with_autoindent_mode(
 3805        &mut self,
 3806        text: &str,
 3807        autoindent_mode: Option<AutoindentMode>,
 3808        cx: &mut ViewContext<Self>,
 3809    ) {
 3810        if self.read_only(cx) {
 3811            return;
 3812        }
 3813
 3814        let text: Arc<str> = text.into();
 3815        self.transact(cx, |this, cx| {
 3816            let old_selections = this.selections.all_adjusted(cx);
 3817            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3818                let anchors = {
 3819                    let snapshot = buffer.read(cx);
 3820                    old_selections
 3821                        .iter()
 3822                        .map(|s| {
 3823                            let anchor = snapshot.anchor_after(s.head());
 3824                            s.map(|_| anchor)
 3825                        })
 3826                        .collect::<Vec<_>>()
 3827                };
 3828                buffer.edit(
 3829                    old_selections
 3830                        .iter()
 3831                        .map(|s| (s.start..s.end, text.clone())),
 3832                    autoindent_mode,
 3833                    cx,
 3834                );
 3835                anchors
 3836            });
 3837
 3838            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3839                s.select_anchors(selection_anchors);
 3840            })
 3841        });
 3842    }
 3843
 3844    fn trigger_completion_on_input(
 3845        &mut self,
 3846        text: &str,
 3847        trigger_in_words: bool,
 3848        cx: &mut ViewContext<Self>,
 3849    ) {
 3850        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3851            self.show_completions(
 3852                &ShowCompletions {
 3853                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3854                },
 3855                cx,
 3856            );
 3857        } else {
 3858            self.hide_context_menu(cx);
 3859        }
 3860    }
 3861
 3862    fn is_completion_trigger(
 3863        &self,
 3864        text: &str,
 3865        trigger_in_words: bool,
 3866        cx: &mut ViewContext<Self>,
 3867    ) -> bool {
 3868        let position = self.selections.newest_anchor().head();
 3869        let multibuffer = self.buffer.read(cx);
 3870        let Some(buffer) = position
 3871            .buffer_id
 3872            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3873        else {
 3874            return false;
 3875        };
 3876
 3877        if let Some(completion_provider) = &self.completion_provider {
 3878            completion_provider.is_completion_trigger(
 3879                &buffer,
 3880                position.text_anchor,
 3881                text,
 3882                trigger_in_words,
 3883                cx,
 3884            )
 3885        } else {
 3886            false
 3887        }
 3888    }
 3889
 3890    /// If any empty selections is touching the start of its innermost containing autoclose
 3891    /// region, expand it to select the brackets.
 3892    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3893        let selections = self.selections.all::<usize>(cx);
 3894        let buffer = self.buffer.read(cx).read(cx);
 3895        let new_selections = self
 3896            .selections_with_autoclose_regions(selections, &buffer)
 3897            .map(|(mut selection, region)| {
 3898                if !selection.is_empty() {
 3899                    return selection;
 3900                }
 3901
 3902                if let Some(region) = region {
 3903                    let mut range = region.range.to_offset(&buffer);
 3904                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3905                        range.start -= region.pair.start.len();
 3906                        if buffer.contains_str_at(range.start, &region.pair.start)
 3907                            && buffer.contains_str_at(range.end, &region.pair.end)
 3908                        {
 3909                            range.end += region.pair.end.len();
 3910                            selection.start = range.start;
 3911                            selection.end = range.end;
 3912
 3913                            return selection;
 3914                        }
 3915                    }
 3916                }
 3917
 3918                let always_treat_brackets_as_autoclosed = buffer
 3919                    .settings_at(selection.start, cx)
 3920                    .always_treat_brackets_as_autoclosed;
 3921
 3922                if !always_treat_brackets_as_autoclosed {
 3923                    return selection;
 3924                }
 3925
 3926                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3927                    for (pair, enabled) in scope.brackets() {
 3928                        if !enabled || !pair.close {
 3929                            continue;
 3930                        }
 3931
 3932                        if buffer.contains_str_at(selection.start, &pair.end) {
 3933                            let pair_start_len = pair.start.len();
 3934                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3935                            {
 3936                                selection.start -= pair_start_len;
 3937                                selection.end += pair.end.len();
 3938
 3939                                return selection;
 3940                            }
 3941                        }
 3942                    }
 3943                }
 3944
 3945                selection
 3946            })
 3947            .collect();
 3948
 3949        drop(buffer);
 3950        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3951    }
 3952
 3953    /// Iterate the given selections, and for each one, find the smallest surrounding
 3954    /// autoclose region. This uses the ordering of the selections and the autoclose
 3955    /// regions to avoid repeated comparisons.
 3956    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3957        &'a self,
 3958        selections: impl IntoIterator<Item = Selection<D>>,
 3959        buffer: &'a MultiBufferSnapshot,
 3960    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3961        let mut i = 0;
 3962        let mut regions = self.autoclose_regions.as_slice();
 3963        selections.into_iter().map(move |selection| {
 3964            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3965
 3966            let mut enclosing = None;
 3967            while let Some(pair_state) = regions.get(i) {
 3968                if pair_state.range.end.to_offset(buffer) < range.start {
 3969                    regions = &regions[i + 1..];
 3970                    i = 0;
 3971                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3972                    break;
 3973                } else {
 3974                    if pair_state.selection_id == selection.id {
 3975                        enclosing = Some(pair_state);
 3976                    }
 3977                    i += 1;
 3978                }
 3979            }
 3980
 3981            (selection.clone(), enclosing)
 3982        })
 3983    }
 3984
 3985    /// Remove any autoclose regions that no longer contain their selection.
 3986    fn invalidate_autoclose_regions(
 3987        &mut self,
 3988        mut selections: &[Selection<Anchor>],
 3989        buffer: &MultiBufferSnapshot,
 3990    ) {
 3991        self.autoclose_regions.retain(|state| {
 3992            let mut i = 0;
 3993            while let Some(selection) = selections.get(i) {
 3994                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3995                    selections = &selections[1..];
 3996                    continue;
 3997                }
 3998                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3999                    break;
 4000                }
 4001                if selection.id == state.selection_id {
 4002                    return true;
 4003                } else {
 4004                    i += 1;
 4005                }
 4006            }
 4007            false
 4008        });
 4009    }
 4010
 4011    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4012        let offset = position.to_offset(buffer);
 4013        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4014        if offset > word_range.start && kind == Some(CharKind::Word) {
 4015            Some(
 4016                buffer
 4017                    .text_for_range(word_range.start..offset)
 4018                    .collect::<String>(),
 4019            )
 4020        } else {
 4021            None
 4022        }
 4023    }
 4024
 4025    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4026        self.refresh_inlay_hints(
 4027            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4028            cx,
 4029        );
 4030    }
 4031
 4032    pub fn inlay_hints_enabled(&self) -> bool {
 4033        self.inlay_hint_cache.enabled
 4034    }
 4035
 4036    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4037        if self.project.is_none() || self.mode != EditorMode::Full {
 4038            return;
 4039        }
 4040
 4041        let reason_description = reason.description();
 4042        let ignore_debounce = matches!(
 4043            reason,
 4044            InlayHintRefreshReason::SettingsChange(_)
 4045                | InlayHintRefreshReason::Toggle(_)
 4046                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4047        );
 4048        let (invalidate_cache, required_languages) = match reason {
 4049            InlayHintRefreshReason::Toggle(enabled) => {
 4050                self.inlay_hint_cache.enabled = enabled;
 4051                if enabled {
 4052                    (InvalidationStrategy::RefreshRequested, None)
 4053                } else {
 4054                    self.inlay_hint_cache.clear();
 4055                    self.splice_inlays(
 4056                        self.visible_inlay_hints(cx)
 4057                            .iter()
 4058                            .map(|inlay| inlay.id)
 4059                            .collect(),
 4060                        Vec::new(),
 4061                        cx,
 4062                    );
 4063                    return;
 4064                }
 4065            }
 4066            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4067                match self.inlay_hint_cache.update_settings(
 4068                    &self.buffer,
 4069                    new_settings,
 4070                    self.visible_inlay_hints(cx),
 4071                    cx,
 4072                ) {
 4073                    ControlFlow::Break(Some(InlaySplice {
 4074                        to_remove,
 4075                        to_insert,
 4076                    })) => {
 4077                        self.splice_inlays(to_remove, to_insert, cx);
 4078                        return;
 4079                    }
 4080                    ControlFlow::Break(None) => return,
 4081                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4082                }
 4083            }
 4084            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4085                if let Some(InlaySplice {
 4086                    to_remove,
 4087                    to_insert,
 4088                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4089                {
 4090                    self.splice_inlays(to_remove, to_insert, cx);
 4091                }
 4092                return;
 4093            }
 4094            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4095            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4096                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4097            }
 4098            InlayHintRefreshReason::RefreshRequested => {
 4099                (InvalidationStrategy::RefreshRequested, None)
 4100            }
 4101        };
 4102
 4103        if let Some(InlaySplice {
 4104            to_remove,
 4105            to_insert,
 4106        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4107            reason_description,
 4108            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4109            invalidate_cache,
 4110            ignore_debounce,
 4111            cx,
 4112        ) {
 4113            self.splice_inlays(to_remove, to_insert, cx);
 4114        }
 4115    }
 4116
 4117    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4118        self.display_map
 4119            .read(cx)
 4120            .current_inlays()
 4121            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4122            .cloned()
 4123            .collect()
 4124    }
 4125
 4126    pub fn excerpts_for_inlay_hints_query(
 4127        &self,
 4128        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4129        cx: &mut ViewContext<Editor>,
 4130    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4131        let Some(project) = self.project.as_ref() else {
 4132            return HashMap::default();
 4133        };
 4134        let project = project.read(cx);
 4135        let multi_buffer = self.buffer().read(cx);
 4136        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4137        let multi_buffer_visible_start = self
 4138            .scroll_manager
 4139            .anchor()
 4140            .anchor
 4141            .to_point(&multi_buffer_snapshot);
 4142        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4143            multi_buffer_visible_start
 4144                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4145            Bias::Left,
 4146        );
 4147        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4148        multi_buffer
 4149            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4150            .into_iter()
 4151            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4152            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4153                let buffer = buffer_handle.read(cx);
 4154                let buffer_file = project::File::from_dyn(buffer.file())?;
 4155                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4156                let worktree_entry = buffer_worktree
 4157                    .read(cx)
 4158                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4159                if worktree_entry.is_ignored {
 4160                    return None;
 4161                }
 4162
 4163                let language = buffer.language()?;
 4164                if let Some(restrict_to_languages) = restrict_to_languages {
 4165                    if !restrict_to_languages.contains(language) {
 4166                        return None;
 4167                    }
 4168                }
 4169                Some((
 4170                    excerpt_id,
 4171                    (
 4172                        buffer_handle,
 4173                        buffer.version().clone(),
 4174                        excerpt_visible_range,
 4175                    ),
 4176                ))
 4177            })
 4178            .collect()
 4179    }
 4180
 4181    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4182        TextLayoutDetails {
 4183            text_system: cx.text_system().clone(),
 4184            editor_style: self.style.clone().unwrap(),
 4185            rem_size: cx.rem_size(),
 4186            scroll_anchor: self.scroll_manager.anchor(),
 4187            visible_rows: self.visible_line_count(),
 4188            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4189        }
 4190    }
 4191
 4192    fn splice_inlays(
 4193        &self,
 4194        to_remove: Vec<InlayId>,
 4195        to_insert: Vec<Inlay>,
 4196        cx: &mut ViewContext<Self>,
 4197    ) {
 4198        self.display_map.update(cx, |display_map, cx| {
 4199            display_map.splice_inlays(to_remove, to_insert, cx);
 4200        });
 4201        cx.notify();
 4202    }
 4203
 4204    fn trigger_on_type_formatting(
 4205        &self,
 4206        input: String,
 4207        cx: &mut ViewContext<Self>,
 4208    ) -> Option<Task<Result<()>>> {
 4209        if input.len() != 1 {
 4210            return None;
 4211        }
 4212
 4213        let project = self.project.as_ref()?;
 4214        let position = self.selections.newest_anchor().head();
 4215        let (buffer, buffer_position) = self
 4216            .buffer
 4217            .read(cx)
 4218            .text_anchor_for_position(position, cx)?;
 4219
 4220        let settings = language_settings::language_settings(
 4221            buffer.read(cx).language_at(buffer_position).as_ref(),
 4222            buffer.read(cx).file(),
 4223            cx,
 4224        );
 4225        if !settings.use_on_type_format {
 4226            return None;
 4227        }
 4228
 4229        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4230        // hence we do LSP request & edit on host side only — add formats to host's history.
 4231        let push_to_lsp_host_history = true;
 4232        // If this is not the host, append its history with new edits.
 4233        let push_to_client_history = project.read(cx).is_via_collab();
 4234
 4235        let on_type_formatting = project.update(cx, |project, cx| {
 4236            project.on_type_format(
 4237                buffer.clone(),
 4238                buffer_position,
 4239                input,
 4240                push_to_lsp_host_history,
 4241                cx,
 4242            )
 4243        });
 4244        Some(cx.spawn(|editor, mut cx| async move {
 4245            if let Some(transaction) = on_type_formatting.await? {
 4246                if push_to_client_history {
 4247                    buffer
 4248                        .update(&mut cx, |buffer, _| {
 4249                            buffer.push_transaction(transaction, Instant::now());
 4250                        })
 4251                        .ok();
 4252                }
 4253                editor.update(&mut cx, |editor, cx| {
 4254                    editor.refresh_document_highlights(cx);
 4255                })?;
 4256            }
 4257            Ok(())
 4258        }))
 4259    }
 4260
 4261    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4262        if self.pending_rename.is_some() {
 4263            return;
 4264        }
 4265
 4266        let Some(provider) = self.completion_provider.as_ref() else {
 4267            return;
 4268        };
 4269
 4270        let position = self.selections.newest_anchor().head();
 4271        let (buffer, buffer_position) =
 4272            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4273                output
 4274            } else {
 4275                return;
 4276            };
 4277
 4278        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4279        let is_followup_invoke = {
 4280            let context_menu_state = self.context_menu.read();
 4281            matches!(
 4282                context_menu_state.deref(),
 4283                Some(ContextMenu::Completions(_))
 4284            )
 4285        };
 4286        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4287            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4288            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4289                CompletionTriggerKind::TRIGGER_CHARACTER
 4290            }
 4291
 4292            _ => CompletionTriggerKind::INVOKED,
 4293        };
 4294        let completion_context = CompletionContext {
 4295            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4296                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4297                    Some(String::from(trigger))
 4298                } else {
 4299                    None
 4300                }
 4301            }),
 4302            trigger_kind,
 4303        };
 4304        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4305        let sort_completions = provider.sort_completions();
 4306
 4307        let id = post_inc(&mut self.next_completion_id);
 4308        let task = cx.spawn(|this, mut cx| {
 4309            async move {
 4310                this.update(&mut cx, |this, _| {
 4311                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4312                })?;
 4313                let completions = completions.await.log_err();
 4314                let menu = if let Some(completions) = completions {
 4315                    let mut menu = CompletionsMenu {
 4316                        id,
 4317                        sort_completions,
 4318                        initial_position: position,
 4319                        match_candidates: completions
 4320                            .iter()
 4321                            .enumerate()
 4322                            .map(|(id, completion)| {
 4323                                StringMatchCandidate::new(
 4324                                    id,
 4325                                    completion.label.text[completion.label.filter_range.clone()]
 4326                                        .into(),
 4327                                )
 4328                            })
 4329                            .collect(),
 4330                        buffer: buffer.clone(),
 4331                        completions: Arc::new(RwLock::new(completions.into())),
 4332                        matches: Vec::new().into(),
 4333                        selected_item: 0,
 4334                        scroll_handle: UniformListScrollHandle::new(),
 4335                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4336                            DebouncedDelay::new(),
 4337                        )),
 4338                    };
 4339                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4340                        .await;
 4341
 4342                    if menu.matches.is_empty() {
 4343                        None
 4344                    } else {
 4345                        this.update(&mut cx, |editor, cx| {
 4346                            let completions = menu.completions.clone();
 4347                            let matches = menu.matches.clone();
 4348
 4349                            let delay_ms = EditorSettings::get_global(cx)
 4350                                .completion_documentation_secondary_query_debounce;
 4351                            let delay = Duration::from_millis(delay_ms);
 4352                            editor
 4353                                .completion_documentation_pre_resolve_debounce
 4354                                .fire_new(delay, cx, |editor, cx| {
 4355                                    CompletionsMenu::pre_resolve_completion_documentation(
 4356                                        buffer,
 4357                                        completions,
 4358                                        matches,
 4359                                        editor,
 4360                                        cx,
 4361                                    )
 4362                                });
 4363                        })
 4364                        .ok();
 4365                        Some(menu)
 4366                    }
 4367                } else {
 4368                    None
 4369                };
 4370
 4371                this.update(&mut cx, |this, cx| {
 4372                    let mut context_menu = this.context_menu.write();
 4373                    match context_menu.as_ref() {
 4374                        None => {}
 4375
 4376                        Some(ContextMenu::Completions(prev_menu)) => {
 4377                            if prev_menu.id > id {
 4378                                return;
 4379                            }
 4380                        }
 4381
 4382                        _ => return,
 4383                    }
 4384
 4385                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4386                        let menu = menu.unwrap();
 4387                        *context_menu = Some(ContextMenu::Completions(menu));
 4388                        drop(context_menu);
 4389                        this.discard_inline_completion(false, cx);
 4390                        cx.notify();
 4391                    } else if this.completion_tasks.len() <= 1 {
 4392                        // If there are no more completion tasks and the last menu was
 4393                        // empty, we should hide it. If it was already hidden, we should
 4394                        // also show the copilot completion when available.
 4395                        drop(context_menu);
 4396                        if this.hide_context_menu(cx).is_none() {
 4397                            this.update_visible_inline_completion(cx);
 4398                        }
 4399                    }
 4400                })?;
 4401
 4402                Ok::<_, anyhow::Error>(())
 4403            }
 4404            .log_err()
 4405        });
 4406
 4407        self.completion_tasks.push((id, task));
 4408    }
 4409
 4410    pub fn confirm_completion(
 4411        &mut self,
 4412        action: &ConfirmCompletion,
 4413        cx: &mut ViewContext<Self>,
 4414    ) -> Option<Task<Result<()>>> {
 4415        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4416    }
 4417
 4418    pub fn compose_completion(
 4419        &mut self,
 4420        action: &ComposeCompletion,
 4421        cx: &mut ViewContext<Self>,
 4422    ) -> Option<Task<Result<()>>> {
 4423        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4424    }
 4425
 4426    fn do_completion(
 4427        &mut self,
 4428        item_ix: Option<usize>,
 4429        intent: CompletionIntent,
 4430        cx: &mut ViewContext<Editor>,
 4431    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4432        use language::ToOffset as _;
 4433
 4434        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4435            menu
 4436        } else {
 4437            return None;
 4438        };
 4439
 4440        let mat = completions_menu
 4441            .matches
 4442            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4443        let buffer_handle = completions_menu.buffer;
 4444        let completions = completions_menu.completions.read();
 4445        let completion = completions.get(mat.candidate_id)?;
 4446        cx.stop_propagation();
 4447
 4448        let snippet;
 4449        let text;
 4450
 4451        if completion.is_snippet() {
 4452            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4453            text = snippet.as_ref().unwrap().text.clone();
 4454        } else {
 4455            snippet = None;
 4456            text = completion.new_text.clone();
 4457        };
 4458        let selections = self.selections.all::<usize>(cx);
 4459        let buffer = buffer_handle.read(cx);
 4460        let old_range = completion.old_range.to_offset(buffer);
 4461        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4462
 4463        let newest_selection = self.selections.newest_anchor();
 4464        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4465            return None;
 4466        }
 4467
 4468        let lookbehind = newest_selection
 4469            .start
 4470            .text_anchor
 4471            .to_offset(buffer)
 4472            .saturating_sub(old_range.start);
 4473        let lookahead = old_range
 4474            .end
 4475            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4476        let mut common_prefix_len = old_text
 4477            .bytes()
 4478            .zip(text.bytes())
 4479            .take_while(|(a, b)| a == b)
 4480            .count();
 4481
 4482        let snapshot = self.buffer.read(cx).snapshot(cx);
 4483        let mut range_to_replace: Option<Range<isize>> = None;
 4484        let mut ranges = Vec::new();
 4485        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4486        for selection in &selections {
 4487            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4488                let start = selection.start.saturating_sub(lookbehind);
 4489                let end = selection.end + lookahead;
 4490                if selection.id == newest_selection.id {
 4491                    range_to_replace = Some(
 4492                        ((start + common_prefix_len) as isize - selection.start as isize)
 4493                            ..(end as isize - selection.start as isize),
 4494                    );
 4495                }
 4496                ranges.push(start + common_prefix_len..end);
 4497            } else {
 4498                common_prefix_len = 0;
 4499                ranges.clear();
 4500                ranges.extend(selections.iter().map(|s| {
 4501                    if s.id == newest_selection.id {
 4502                        range_to_replace = Some(
 4503                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4504                                - selection.start as isize
 4505                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4506                                    - selection.start as isize,
 4507                        );
 4508                        old_range.clone()
 4509                    } else {
 4510                        s.start..s.end
 4511                    }
 4512                }));
 4513                break;
 4514            }
 4515            if !self.linked_edit_ranges.is_empty() {
 4516                let start_anchor = snapshot.anchor_before(selection.head());
 4517                let end_anchor = snapshot.anchor_after(selection.tail());
 4518                if let Some(ranges) = self
 4519                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4520                {
 4521                    for (buffer, edits) in ranges {
 4522                        linked_edits.entry(buffer.clone()).or_default().extend(
 4523                            edits
 4524                                .into_iter()
 4525                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4526                        );
 4527                    }
 4528                }
 4529            }
 4530        }
 4531        let text = &text[common_prefix_len..];
 4532
 4533        cx.emit(EditorEvent::InputHandled {
 4534            utf16_range_to_replace: range_to_replace,
 4535            text: text.into(),
 4536        });
 4537
 4538        self.transact(cx, |this, cx| {
 4539            if let Some(mut snippet) = snippet {
 4540                snippet.text = text.to_string();
 4541                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4542                    tabstop.start -= common_prefix_len as isize;
 4543                    tabstop.end -= common_prefix_len as isize;
 4544                }
 4545
 4546                this.insert_snippet(&ranges, snippet, cx).log_err();
 4547            } else {
 4548                this.buffer.update(cx, |buffer, cx| {
 4549                    buffer.edit(
 4550                        ranges.iter().map(|range| (range.clone(), text)),
 4551                        this.autoindent_mode.clone(),
 4552                        cx,
 4553                    );
 4554                });
 4555            }
 4556            for (buffer, edits) in linked_edits {
 4557                buffer.update(cx, |buffer, cx| {
 4558                    let snapshot = buffer.snapshot();
 4559                    let edits = edits
 4560                        .into_iter()
 4561                        .map(|(range, text)| {
 4562                            use text::ToPoint as TP;
 4563                            let end_point = TP::to_point(&range.end, &snapshot);
 4564                            let start_point = TP::to_point(&range.start, &snapshot);
 4565                            (start_point..end_point, text)
 4566                        })
 4567                        .sorted_by_key(|(range, _)| range.start)
 4568                        .collect::<Vec<_>>();
 4569                    buffer.edit(edits, None, cx);
 4570                })
 4571            }
 4572
 4573            this.refresh_inline_completion(true, false, cx);
 4574        });
 4575
 4576        let show_new_completions_on_confirm = completion
 4577            .confirm
 4578            .as_ref()
 4579            .map_or(false, |confirm| confirm(intent, cx));
 4580        if show_new_completions_on_confirm {
 4581            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4582        }
 4583
 4584        let provider = self.completion_provider.as_ref()?;
 4585        let apply_edits = provider.apply_additional_edits_for_completion(
 4586            buffer_handle,
 4587            completion.clone(),
 4588            true,
 4589            cx,
 4590        );
 4591
 4592        let editor_settings = EditorSettings::get_global(cx);
 4593        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4594            // After the code completion is finished, users often want to know what signatures are needed.
 4595            // so we should automatically call signature_help
 4596            self.show_signature_help(&ShowSignatureHelp, cx);
 4597        }
 4598
 4599        Some(cx.foreground_executor().spawn(async move {
 4600            apply_edits.await?;
 4601            Ok(())
 4602        }))
 4603    }
 4604
 4605    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4606        let mut context_menu = self.context_menu.write();
 4607        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4608            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4609                // Toggle if we're selecting the same one
 4610                *context_menu = None;
 4611                cx.notify();
 4612                return;
 4613            } else {
 4614                // Otherwise, clear it and start a new one
 4615                *context_menu = None;
 4616                cx.notify();
 4617            }
 4618        }
 4619        drop(context_menu);
 4620        let snapshot = self.snapshot(cx);
 4621        let deployed_from_indicator = action.deployed_from_indicator;
 4622        let mut task = self.code_actions_task.take();
 4623        let action = action.clone();
 4624        cx.spawn(|editor, mut cx| async move {
 4625            while let Some(prev_task) = task {
 4626                prev_task.await.log_err();
 4627                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4628            }
 4629
 4630            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4631                if editor.focus_handle.is_focused(cx) {
 4632                    let multibuffer_point = action
 4633                        .deployed_from_indicator
 4634                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4635                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4636                    let (buffer, buffer_row) = snapshot
 4637                        .buffer_snapshot
 4638                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4639                        .and_then(|(buffer_snapshot, range)| {
 4640                            editor
 4641                                .buffer
 4642                                .read(cx)
 4643                                .buffer(buffer_snapshot.remote_id())
 4644                                .map(|buffer| (buffer, range.start.row))
 4645                        })?;
 4646                    let (_, code_actions) = editor
 4647                        .available_code_actions
 4648                        .clone()
 4649                        .and_then(|(location, code_actions)| {
 4650                            let snapshot = location.buffer.read(cx).snapshot();
 4651                            let point_range = location.range.to_point(&snapshot);
 4652                            let point_range = point_range.start.row..=point_range.end.row;
 4653                            if point_range.contains(&buffer_row) {
 4654                                Some((location, code_actions))
 4655                            } else {
 4656                                None
 4657                            }
 4658                        })
 4659                        .unzip();
 4660                    let buffer_id = buffer.read(cx).remote_id();
 4661                    let tasks = editor
 4662                        .tasks
 4663                        .get(&(buffer_id, buffer_row))
 4664                        .map(|t| Arc::new(t.to_owned()));
 4665                    if tasks.is_none() && code_actions.is_none() {
 4666                        return None;
 4667                    }
 4668
 4669                    editor.completion_tasks.clear();
 4670                    editor.discard_inline_completion(false, cx);
 4671                    let task_context =
 4672                        tasks
 4673                            .as_ref()
 4674                            .zip(editor.project.clone())
 4675                            .map(|(tasks, project)| {
 4676                                let position = Point::new(buffer_row, tasks.column);
 4677                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4678                                let location = Location {
 4679                                    buffer: buffer.clone(),
 4680                                    range: range_start..range_start,
 4681                                };
 4682                                // Fill in the environmental variables from the tree-sitter captures
 4683                                let mut captured_task_variables = TaskVariables::default();
 4684                                for (capture_name, value) in tasks.extra_variables.clone() {
 4685                                    captured_task_variables.insert(
 4686                                        task::VariableName::Custom(capture_name.into()),
 4687                                        value.clone(),
 4688                                    );
 4689                                }
 4690                                project.update(cx, |project, cx| {
 4691                                    project.task_context_for_location(
 4692                                        captured_task_variables,
 4693                                        location,
 4694                                        cx,
 4695                                    )
 4696                                })
 4697                            });
 4698
 4699                    Some(cx.spawn(|editor, mut cx| async move {
 4700                        let task_context = match task_context {
 4701                            Some(task_context) => task_context.await,
 4702                            None => None,
 4703                        };
 4704                        let resolved_tasks =
 4705                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4706                                Arc::new(ResolvedTasks {
 4707                                    templates: tasks
 4708                                        .templates
 4709                                        .iter()
 4710                                        .filter_map(|(kind, template)| {
 4711                                            template
 4712                                                .resolve_task(&kind.to_id_base(), &task_context)
 4713                                                .map(|task| (kind.clone(), task))
 4714                                        })
 4715                                        .collect(),
 4716                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4717                                        multibuffer_point.row,
 4718                                        tasks.column,
 4719                                    )),
 4720                                })
 4721                            });
 4722                        let spawn_straight_away = resolved_tasks
 4723                            .as_ref()
 4724                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4725                            && code_actions
 4726                                .as_ref()
 4727                                .map_or(true, |actions| actions.is_empty());
 4728                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4729                            *editor.context_menu.write() =
 4730                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4731                                    buffer,
 4732                                    actions: CodeActionContents {
 4733                                        tasks: resolved_tasks,
 4734                                        actions: code_actions,
 4735                                    },
 4736                                    selected_item: Default::default(),
 4737                                    scroll_handle: UniformListScrollHandle::default(),
 4738                                    deployed_from_indicator,
 4739                                }));
 4740                            if spawn_straight_away {
 4741                                if let Some(task) = editor.confirm_code_action(
 4742                                    &ConfirmCodeAction { item_ix: Some(0) },
 4743                                    cx,
 4744                                ) {
 4745                                    cx.notify();
 4746                                    return task;
 4747                                }
 4748                            }
 4749                            cx.notify();
 4750                            Task::ready(Ok(()))
 4751                        }) {
 4752                            task.await
 4753                        } else {
 4754                            Ok(())
 4755                        }
 4756                    }))
 4757                } else {
 4758                    Some(Task::ready(Ok(())))
 4759                }
 4760            })?;
 4761            if let Some(task) = spawned_test_task {
 4762                task.await?;
 4763            }
 4764
 4765            Ok::<_, anyhow::Error>(())
 4766        })
 4767        .detach_and_log_err(cx);
 4768    }
 4769
 4770    pub fn confirm_code_action(
 4771        &mut self,
 4772        action: &ConfirmCodeAction,
 4773        cx: &mut ViewContext<Self>,
 4774    ) -> Option<Task<Result<()>>> {
 4775        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4776            menu
 4777        } else {
 4778            return None;
 4779        };
 4780        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4781        let action = actions_menu.actions.get(action_ix)?;
 4782        let title = action.label();
 4783        let buffer = actions_menu.buffer;
 4784        let workspace = self.workspace()?;
 4785
 4786        match action {
 4787            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4788                workspace.update(cx, |workspace, cx| {
 4789                    workspace::tasks::schedule_resolved_task(
 4790                        workspace,
 4791                        task_source_kind,
 4792                        resolved_task,
 4793                        false,
 4794                        cx,
 4795                    );
 4796
 4797                    Some(Task::ready(Ok(())))
 4798                })
 4799            }
 4800            CodeActionsItem::CodeAction {
 4801                excerpt_id,
 4802                action,
 4803                provider,
 4804            } => {
 4805                let apply_code_action =
 4806                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4807                let workspace = workspace.downgrade();
 4808                Some(cx.spawn(|editor, cx| async move {
 4809                    let project_transaction = apply_code_action.await?;
 4810                    Self::open_project_transaction(
 4811                        &editor,
 4812                        workspace,
 4813                        project_transaction,
 4814                        title,
 4815                        cx,
 4816                    )
 4817                    .await
 4818                }))
 4819            }
 4820        }
 4821    }
 4822
 4823    pub async fn open_project_transaction(
 4824        this: &WeakView<Editor>,
 4825        workspace: WeakView<Workspace>,
 4826        transaction: ProjectTransaction,
 4827        title: String,
 4828        mut cx: AsyncWindowContext,
 4829    ) -> Result<()> {
 4830        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4831        cx.update(|cx| {
 4832            entries.sort_unstable_by_key(|(buffer, _)| {
 4833                buffer.read(cx).file().map(|f| f.path().clone())
 4834            });
 4835        })?;
 4836
 4837        // If the project transaction's edits are all contained within this editor, then
 4838        // avoid opening a new editor to display them.
 4839
 4840        if let Some((buffer, transaction)) = entries.first() {
 4841            if entries.len() == 1 {
 4842                let excerpt = this.update(&mut cx, |editor, cx| {
 4843                    editor
 4844                        .buffer()
 4845                        .read(cx)
 4846                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4847                })?;
 4848                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4849                    if excerpted_buffer == *buffer {
 4850                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4851                            let excerpt_range = excerpt_range.to_offset(buffer);
 4852                            buffer
 4853                                .edited_ranges_for_transaction::<usize>(transaction)
 4854                                .all(|range| {
 4855                                    excerpt_range.start <= range.start
 4856                                        && excerpt_range.end >= range.end
 4857                                })
 4858                        })?;
 4859
 4860                        if all_edits_within_excerpt {
 4861                            return Ok(());
 4862                        }
 4863                    }
 4864                }
 4865            }
 4866        } else {
 4867            return Ok(());
 4868        }
 4869
 4870        let mut ranges_to_highlight = Vec::new();
 4871        let excerpt_buffer = cx.new_model(|cx| {
 4872            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4873            for (buffer_handle, transaction) in &entries {
 4874                let buffer = buffer_handle.read(cx);
 4875                ranges_to_highlight.extend(
 4876                    multibuffer.push_excerpts_with_context_lines(
 4877                        buffer_handle.clone(),
 4878                        buffer
 4879                            .edited_ranges_for_transaction::<usize>(transaction)
 4880                            .collect(),
 4881                        DEFAULT_MULTIBUFFER_CONTEXT,
 4882                        cx,
 4883                    ),
 4884                );
 4885            }
 4886            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4887            multibuffer
 4888        })?;
 4889
 4890        workspace.update(&mut cx, |workspace, cx| {
 4891            let project = workspace.project().clone();
 4892            let editor =
 4893                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4894            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4895            editor.update(cx, |editor, cx| {
 4896                editor.highlight_background::<Self>(
 4897                    &ranges_to_highlight,
 4898                    |theme| theme.editor_highlighted_line_background,
 4899                    cx,
 4900                );
 4901            });
 4902        })?;
 4903
 4904        Ok(())
 4905    }
 4906
 4907    pub fn push_code_action_provider(
 4908        &mut self,
 4909        provider: Arc<dyn CodeActionProvider>,
 4910        cx: &mut ViewContext<Self>,
 4911    ) {
 4912        self.code_action_providers.push(provider);
 4913        self.refresh_code_actions(cx);
 4914    }
 4915
 4916    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4917        let buffer = self.buffer.read(cx);
 4918        let newest_selection = self.selections.newest_anchor().clone();
 4919        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4920        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4921        if start_buffer != end_buffer {
 4922            return None;
 4923        }
 4924
 4925        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4926            cx.background_executor()
 4927                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4928                .await;
 4929
 4930            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4931                let providers = this.code_action_providers.clone();
 4932                let tasks = this
 4933                    .code_action_providers
 4934                    .iter()
 4935                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4936                    .collect::<Vec<_>>();
 4937                (providers, tasks)
 4938            })?;
 4939
 4940            let mut actions = Vec::new();
 4941            for (provider, provider_actions) in
 4942                providers.into_iter().zip(future::join_all(tasks).await)
 4943            {
 4944                if let Some(provider_actions) = provider_actions.log_err() {
 4945                    actions.extend(provider_actions.into_iter().map(|action| {
 4946                        AvailableCodeAction {
 4947                            excerpt_id: newest_selection.start.excerpt_id,
 4948                            action,
 4949                            provider: provider.clone(),
 4950                        }
 4951                    }));
 4952                }
 4953            }
 4954
 4955            this.update(&mut cx, |this, cx| {
 4956                this.available_code_actions = if actions.is_empty() {
 4957                    None
 4958                } else {
 4959                    Some((
 4960                        Location {
 4961                            buffer: start_buffer,
 4962                            range: start..end,
 4963                        },
 4964                        actions.into(),
 4965                    ))
 4966                };
 4967                cx.notify();
 4968            })
 4969        }));
 4970        None
 4971    }
 4972
 4973    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4974        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4975            self.show_git_blame_inline = false;
 4976
 4977            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4978                cx.background_executor().timer(delay).await;
 4979
 4980                this.update(&mut cx, |this, cx| {
 4981                    this.show_git_blame_inline = true;
 4982                    cx.notify();
 4983                })
 4984                .log_err();
 4985            }));
 4986        }
 4987    }
 4988
 4989    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4990        if self.pending_rename.is_some() {
 4991            return None;
 4992        }
 4993
 4994        let project = self.project.clone()?;
 4995        let buffer = self.buffer.read(cx);
 4996        let newest_selection = self.selections.newest_anchor().clone();
 4997        let cursor_position = newest_selection.head();
 4998        let (cursor_buffer, cursor_buffer_position) =
 4999            buffer.text_anchor_for_position(cursor_position, cx)?;
 5000        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5001        if cursor_buffer != tail_buffer {
 5002            return None;
 5003        }
 5004
 5005        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5006            cx.background_executor()
 5007                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5008                .await;
 5009
 5010            let highlights = if let Some(highlights) = project
 5011                .update(&mut cx, |project, cx| {
 5012                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5013                })
 5014                .log_err()
 5015            {
 5016                highlights.await.log_err()
 5017            } else {
 5018                None
 5019            };
 5020
 5021            if let Some(highlights) = highlights {
 5022                this.update(&mut cx, |this, cx| {
 5023                    if this.pending_rename.is_some() {
 5024                        return;
 5025                    }
 5026
 5027                    let buffer_id = cursor_position.buffer_id;
 5028                    let buffer = this.buffer.read(cx);
 5029                    if !buffer
 5030                        .text_anchor_for_position(cursor_position, cx)
 5031                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5032                    {
 5033                        return;
 5034                    }
 5035
 5036                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5037                    let mut write_ranges = Vec::new();
 5038                    let mut read_ranges = Vec::new();
 5039                    for highlight in highlights {
 5040                        for (excerpt_id, excerpt_range) in
 5041                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5042                        {
 5043                            let start = highlight
 5044                                .range
 5045                                .start
 5046                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5047                            let end = highlight
 5048                                .range
 5049                                .end
 5050                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5051                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5052                                continue;
 5053                            }
 5054
 5055                            let range = Anchor {
 5056                                buffer_id,
 5057                                excerpt_id,
 5058                                text_anchor: start,
 5059                            }..Anchor {
 5060                                buffer_id,
 5061                                excerpt_id,
 5062                                text_anchor: end,
 5063                            };
 5064                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5065                                write_ranges.push(range);
 5066                            } else {
 5067                                read_ranges.push(range);
 5068                            }
 5069                        }
 5070                    }
 5071
 5072                    this.highlight_background::<DocumentHighlightRead>(
 5073                        &read_ranges,
 5074                        |theme| theme.editor_document_highlight_read_background,
 5075                        cx,
 5076                    );
 5077                    this.highlight_background::<DocumentHighlightWrite>(
 5078                        &write_ranges,
 5079                        |theme| theme.editor_document_highlight_write_background,
 5080                        cx,
 5081                    );
 5082                    cx.notify();
 5083                })
 5084                .log_err();
 5085            }
 5086        }));
 5087        None
 5088    }
 5089
 5090    pub fn refresh_inline_completion(
 5091        &mut self,
 5092        debounce: bool,
 5093        user_requested: bool,
 5094        cx: &mut ViewContext<Self>,
 5095    ) -> Option<()> {
 5096        let provider = self.inline_completion_provider()?;
 5097        let cursor = self.selections.newest_anchor().head();
 5098        let (buffer, cursor_buffer_position) =
 5099            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5100
 5101        if !user_requested
 5102            && (!self.enable_inline_completions
 5103                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5104        {
 5105            self.discard_inline_completion(false, cx);
 5106            return None;
 5107        }
 5108
 5109        self.update_visible_inline_completion(cx);
 5110        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5111        Some(())
 5112    }
 5113
 5114    fn cycle_inline_completion(
 5115        &mut self,
 5116        direction: Direction,
 5117        cx: &mut ViewContext<Self>,
 5118    ) -> Option<()> {
 5119        let provider = self.inline_completion_provider()?;
 5120        let cursor = self.selections.newest_anchor().head();
 5121        let (buffer, cursor_buffer_position) =
 5122            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5123        if !self.enable_inline_completions
 5124            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5125        {
 5126            return None;
 5127        }
 5128
 5129        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5130        self.update_visible_inline_completion(cx);
 5131
 5132        Some(())
 5133    }
 5134
 5135    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5136        if !self.has_active_inline_completion(cx) {
 5137            self.refresh_inline_completion(false, true, cx);
 5138            return;
 5139        }
 5140
 5141        self.update_visible_inline_completion(cx);
 5142    }
 5143
 5144    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5145        self.show_cursor_names(cx);
 5146    }
 5147
 5148    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5149        self.show_cursor_names = true;
 5150        cx.notify();
 5151        cx.spawn(|this, mut cx| async move {
 5152            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5153            this.update(&mut cx, |this, cx| {
 5154                this.show_cursor_names = false;
 5155                cx.notify()
 5156            })
 5157            .ok()
 5158        })
 5159        .detach();
 5160    }
 5161
 5162    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5163        if self.has_active_inline_completion(cx) {
 5164            self.cycle_inline_completion(Direction::Next, cx);
 5165        } else {
 5166            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5167            if is_copilot_disabled {
 5168                cx.propagate();
 5169            }
 5170        }
 5171    }
 5172
 5173    pub fn previous_inline_completion(
 5174        &mut self,
 5175        _: &PreviousInlineCompletion,
 5176        cx: &mut ViewContext<Self>,
 5177    ) {
 5178        if self.has_active_inline_completion(cx) {
 5179            self.cycle_inline_completion(Direction::Prev, cx);
 5180        } else {
 5181            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5182            if is_copilot_disabled {
 5183                cx.propagate();
 5184            }
 5185        }
 5186    }
 5187
 5188    pub fn accept_inline_completion(
 5189        &mut self,
 5190        _: &AcceptInlineCompletion,
 5191        cx: &mut ViewContext<Self>,
 5192    ) {
 5193        let Some(completion) = self.take_active_inline_completion(cx) else {
 5194            return;
 5195        };
 5196        if let Some(provider) = self.inline_completion_provider() {
 5197            provider.accept(cx);
 5198        }
 5199
 5200        cx.emit(EditorEvent::InputHandled {
 5201            utf16_range_to_replace: None,
 5202            text: completion.text.to_string().into(),
 5203        });
 5204
 5205        if let Some(range) = completion.delete_range {
 5206            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5207        }
 5208        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5209        self.refresh_inline_completion(true, true, cx);
 5210        cx.notify();
 5211    }
 5212
 5213    pub fn accept_partial_inline_completion(
 5214        &mut self,
 5215        _: &AcceptPartialInlineCompletion,
 5216        cx: &mut ViewContext<Self>,
 5217    ) {
 5218        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5219            if let Some(completion) = self.take_active_inline_completion(cx) {
 5220                let mut partial_completion = completion
 5221                    .text
 5222                    .chars()
 5223                    .by_ref()
 5224                    .take_while(|c| c.is_alphabetic())
 5225                    .collect::<String>();
 5226                if partial_completion.is_empty() {
 5227                    partial_completion = completion
 5228                        .text
 5229                        .chars()
 5230                        .by_ref()
 5231                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5232                        .collect::<String>();
 5233                }
 5234
 5235                cx.emit(EditorEvent::InputHandled {
 5236                    utf16_range_to_replace: None,
 5237                    text: partial_completion.clone().into(),
 5238                });
 5239
 5240                if let Some(range) = completion.delete_range {
 5241                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5242                }
 5243                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5244
 5245                self.refresh_inline_completion(true, true, cx);
 5246                cx.notify();
 5247            }
 5248        }
 5249    }
 5250
 5251    fn discard_inline_completion(
 5252        &mut self,
 5253        should_report_inline_completion_event: bool,
 5254        cx: &mut ViewContext<Self>,
 5255    ) -> bool {
 5256        if let Some(provider) = self.inline_completion_provider() {
 5257            provider.discard(should_report_inline_completion_event, cx);
 5258        }
 5259
 5260        self.take_active_inline_completion(cx).is_some()
 5261    }
 5262
 5263    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5264        if let Some(completion) = self.active_inline_completion.as_ref() {
 5265            let buffer = self.buffer.read(cx).read(cx);
 5266            completion.position.is_valid(&buffer)
 5267        } else {
 5268            false
 5269        }
 5270    }
 5271
 5272    fn take_active_inline_completion(
 5273        &mut self,
 5274        cx: &mut ViewContext<Self>,
 5275    ) -> Option<CompletionState> {
 5276        let completion = self.active_inline_completion.take()?;
 5277        let render_inlay_ids = completion.render_inlay_ids.clone();
 5278        self.display_map.update(cx, |map, cx| {
 5279            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5280        });
 5281        let buffer = self.buffer.read(cx).read(cx);
 5282
 5283        if completion.position.is_valid(&buffer) {
 5284            Some(completion)
 5285        } else {
 5286            None
 5287        }
 5288    }
 5289
 5290    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5291        let selection = self.selections.newest_anchor();
 5292        let cursor = selection.head();
 5293
 5294        let excerpt_id = cursor.excerpt_id;
 5295
 5296        if self.context_menu.read().is_none()
 5297            && self.completion_tasks.is_empty()
 5298            && selection.start == selection.end
 5299        {
 5300            if let Some(provider) = self.inline_completion_provider() {
 5301                if let Some((buffer, cursor_buffer_position)) =
 5302                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5303                {
 5304                    if let Some(proposal) =
 5305                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5306                    {
 5307                        let mut to_remove = Vec::new();
 5308                        if let Some(completion) = self.active_inline_completion.take() {
 5309                            to_remove.extend(completion.render_inlay_ids.iter());
 5310                        }
 5311
 5312                        let to_add = proposal
 5313                            .inlays
 5314                            .iter()
 5315                            .filter_map(|inlay| {
 5316                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5317                                let id = post_inc(&mut self.next_inlay_id);
 5318                                match inlay {
 5319                                    InlayProposal::Hint(position, hint) => {
 5320                                        let position =
 5321                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5322                                        Some(Inlay::hint(id, position, hint))
 5323                                    }
 5324                                    InlayProposal::Suggestion(position, text) => {
 5325                                        let position =
 5326                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5327                                        Some(Inlay::suggestion(id, position, text.clone()))
 5328                                    }
 5329                                }
 5330                            })
 5331                            .collect_vec();
 5332
 5333                        self.active_inline_completion = Some(CompletionState {
 5334                            position: cursor,
 5335                            text: proposal.text,
 5336                            delete_range: proposal.delete_range.and_then(|range| {
 5337                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5338                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5339                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5340                                Some(start?..end?)
 5341                            }),
 5342                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5343                        });
 5344
 5345                        self.display_map
 5346                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5347
 5348                        cx.notify();
 5349                        return;
 5350                    }
 5351                }
 5352            }
 5353        }
 5354
 5355        self.discard_inline_completion(false, cx);
 5356    }
 5357
 5358    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5359        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5360    }
 5361
 5362    fn render_code_actions_indicator(
 5363        &self,
 5364        _style: &EditorStyle,
 5365        row: DisplayRow,
 5366        is_active: bool,
 5367        cx: &mut ViewContext<Self>,
 5368    ) -> Option<IconButton> {
 5369        if self.available_code_actions.is_some() {
 5370            Some(
 5371                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5372                    .shape(ui::IconButtonShape::Square)
 5373                    .icon_size(IconSize::XSmall)
 5374                    .icon_color(Color::Muted)
 5375                    .selected(is_active)
 5376                    .tooltip({
 5377                        let focus_handle = self.focus_handle.clone();
 5378                        move |cx| {
 5379                            Tooltip::for_action_in(
 5380                                "Toggle Code Actions",
 5381                                &ToggleCodeActions {
 5382                                    deployed_from_indicator: None,
 5383                                },
 5384                                &focus_handle,
 5385                                cx,
 5386                            )
 5387                        }
 5388                    })
 5389                    .on_click(cx.listener(move |editor, _e, cx| {
 5390                        editor.focus(cx);
 5391                        editor.toggle_code_actions(
 5392                            &ToggleCodeActions {
 5393                                deployed_from_indicator: Some(row),
 5394                            },
 5395                            cx,
 5396                        );
 5397                    })),
 5398            )
 5399        } else {
 5400            None
 5401        }
 5402    }
 5403
 5404    fn clear_tasks(&mut self) {
 5405        self.tasks.clear()
 5406    }
 5407
 5408    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5409        if self.tasks.insert(key, value).is_some() {
 5410            // This case should hopefully be rare, but just in case...
 5411            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5412        }
 5413    }
 5414
 5415    fn render_run_indicator(
 5416        &self,
 5417        _style: &EditorStyle,
 5418        is_active: bool,
 5419        row: DisplayRow,
 5420        cx: &mut ViewContext<Self>,
 5421    ) -> IconButton {
 5422        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5423            .shape(ui::IconButtonShape::Square)
 5424            .icon_size(IconSize::XSmall)
 5425            .icon_color(Color::Muted)
 5426            .selected(is_active)
 5427            .on_click(cx.listener(move |editor, _e, cx| {
 5428                editor.focus(cx);
 5429                editor.toggle_code_actions(
 5430                    &ToggleCodeActions {
 5431                        deployed_from_indicator: Some(row),
 5432                    },
 5433                    cx,
 5434                );
 5435            }))
 5436    }
 5437
 5438    pub fn context_menu_visible(&self) -> bool {
 5439        self.context_menu
 5440            .read()
 5441            .as_ref()
 5442            .map_or(false, |menu| menu.visible())
 5443    }
 5444
 5445    fn render_context_menu(
 5446        &self,
 5447        cursor_position: DisplayPoint,
 5448        style: &EditorStyle,
 5449        max_height: Pixels,
 5450        cx: &mut ViewContext<Editor>,
 5451    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5452        self.context_menu.read().as_ref().map(|menu| {
 5453            menu.render(
 5454                cursor_position,
 5455                style,
 5456                max_height,
 5457                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5458                cx,
 5459            )
 5460        })
 5461    }
 5462
 5463    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5464        cx.notify();
 5465        self.completion_tasks.clear();
 5466        let context_menu = self.context_menu.write().take();
 5467        if context_menu.is_some() {
 5468            self.update_visible_inline_completion(cx);
 5469        }
 5470        context_menu
 5471    }
 5472
 5473    pub fn insert_snippet(
 5474        &mut self,
 5475        insertion_ranges: &[Range<usize>],
 5476        snippet: Snippet,
 5477        cx: &mut ViewContext<Self>,
 5478    ) -> Result<()> {
 5479        struct Tabstop<T> {
 5480            is_end_tabstop: bool,
 5481            ranges: Vec<Range<T>>,
 5482        }
 5483
 5484        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5485            let snippet_text: Arc<str> = snippet.text.clone().into();
 5486            buffer.edit(
 5487                insertion_ranges
 5488                    .iter()
 5489                    .cloned()
 5490                    .map(|range| (range, snippet_text.clone())),
 5491                Some(AutoindentMode::EachLine),
 5492                cx,
 5493            );
 5494
 5495            let snapshot = &*buffer.read(cx);
 5496            let snippet = &snippet;
 5497            snippet
 5498                .tabstops
 5499                .iter()
 5500                .map(|tabstop| {
 5501                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5502                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5503                    });
 5504                    let mut tabstop_ranges = tabstop
 5505                        .iter()
 5506                        .flat_map(|tabstop_range| {
 5507                            let mut delta = 0_isize;
 5508                            insertion_ranges.iter().map(move |insertion_range| {
 5509                                let insertion_start = insertion_range.start as isize + delta;
 5510                                delta +=
 5511                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5512
 5513                                let start = ((insertion_start + tabstop_range.start) as usize)
 5514                                    .min(snapshot.len());
 5515                                let end = ((insertion_start + tabstop_range.end) as usize)
 5516                                    .min(snapshot.len());
 5517                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5518                            })
 5519                        })
 5520                        .collect::<Vec<_>>();
 5521                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5522
 5523                    Tabstop {
 5524                        is_end_tabstop,
 5525                        ranges: tabstop_ranges,
 5526                    }
 5527                })
 5528                .collect::<Vec<_>>()
 5529        });
 5530        if let Some(tabstop) = tabstops.first() {
 5531            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5532                s.select_ranges(tabstop.ranges.iter().cloned());
 5533            });
 5534
 5535            // If we're already at the last tabstop and it's at the end of the snippet,
 5536            // we're done, we don't need to keep the state around.
 5537            if !tabstop.is_end_tabstop {
 5538                let ranges = tabstops
 5539                    .into_iter()
 5540                    .map(|tabstop| tabstop.ranges)
 5541                    .collect::<Vec<_>>();
 5542                self.snippet_stack.push(SnippetState {
 5543                    active_index: 0,
 5544                    ranges,
 5545                });
 5546            }
 5547
 5548            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5549            if self.autoclose_regions.is_empty() {
 5550                let snapshot = self.buffer.read(cx).snapshot(cx);
 5551                for selection in &mut self.selections.all::<Point>(cx) {
 5552                    let selection_head = selection.head();
 5553                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5554                        continue;
 5555                    };
 5556
 5557                    let mut bracket_pair = None;
 5558                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5559                    let prev_chars = snapshot
 5560                        .reversed_chars_at(selection_head)
 5561                        .collect::<String>();
 5562                    for (pair, enabled) in scope.brackets() {
 5563                        if enabled
 5564                            && pair.close
 5565                            && prev_chars.starts_with(pair.start.as_str())
 5566                            && next_chars.starts_with(pair.end.as_str())
 5567                        {
 5568                            bracket_pair = Some(pair.clone());
 5569                            break;
 5570                        }
 5571                    }
 5572                    if let Some(pair) = bracket_pair {
 5573                        let start = snapshot.anchor_after(selection_head);
 5574                        let end = snapshot.anchor_after(selection_head);
 5575                        self.autoclose_regions.push(AutocloseRegion {
 5576                            selection_id: selection.id,
 5577                            range: start..end,
 5578                            pair,
 5579                        });
 5580                    }
 5581                }
 5582            }
 5583        }
 5584        Ok(())
 5585    }
 5586
 5587    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5588        self.move_to_snippet_tabstop(Bias::Right, cx)
 5589    }
 5590
 5591    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5592        self.move_to_snippet_tabstop(Bias::Left, cx)
 5593    }
 5594
 5595    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5596        if let Some(mut snippet) = self.snippet_stack.pop() {
 5597            match bias {
 5598                Bias::Left => {
 5599                    if snippet.active_index > 0 {
 5600                        snippet.active_index -= 1;
 5601                    } else {
 5602                        self.snippet_stack.push(snippet);
 5603                        return false;
 5604                    }
 5605                }
 5606                Bias::Right => {
 5607                    if snippet.active_index + 1 < snippet.ranges.len() {
 5608                        snippet.active_index += 1;
 5609                    } else {
 5610                        self.snippet_stack.push(snippet);
 5611                        return false;
 5612                    }
 5613                }
 5614            }
 5615            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5616                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5617                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5618                });
 5619                // If snippet state is not at the last tabstop, push it back on the stack
 5620                if snippet.active_index + 1 < snippet.ranges.len() {
 5621                    self.snippet_stack.push(snippet);
 5622                }
 5623                return true;
 5624            }
 5625        }
 5626
 5627        false
 5628    }
 5629
 5630    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5631        self.transact(cx, |this, cx| {
 5632            this.select_all(&SelectAll, cx);
 5633            this.insert("", cx);
 5634        });
 5635    }
 5636
 5637    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5638        self.transact(cx, |this, cx| {
 5639            this.select_autoclose_pair(cx);
 5640            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5641            if !this.linked_edit_ranges.is_empty() {
 5642                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5643                let snapshot = this.buffer.read(cx).snapshot(cx);
 5644
 5645                for selection in selections.iter() {
 5646                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5647                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5648                    if selection_start.buffer_id != selection_end.buffer_id {
 5649                        continue;
 5650                    }
 5651                    if let Some(ranges) =
 5652                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5653                    {
 5654                        for (buffer, entries) in ranges {
 5655                            linked_ranges.entry(buffer).or_default().extend(entries);
 5656                        }
 5657                    }
 5658                }
 5659            }
 5660
 5661            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5662            if !this.selections.line_mode {
 5663                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5664                for selection in &mut selections {
 5665                    if selection.is_empty() {
 5666                        let old_head = selection.head();
 5667                        let mut new_head =
 5668                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5669                                .to_point(&display_map);
 5670                        if let Some((buffer, line_buffer_range)) = display_map
 5671                            .buffer_snapshot
 5672                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5673                        {
 5674                            let indent_size =
 5675                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5676                            let indent_len = match indent_size.kind {
 5677                                IndentKind::Space => {
 5678                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5679                                }
 5680                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5681                            };
 5682                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5683                                let indent_len = indent_len.get();
 5684                                new_head = cmp::min(
 5685                                    new_head,
 5686                                    MultiBufferPoint::new(
 5687                                        old_head.row,
 5688                                        ((old_head.column - 1) / indent_len) * indent_len,
 5689                                    ),
 5690                                );
 5691                            }
 5692                        }
 5693
 5694                        selection.set_head(new_head, SelectionGoal::None);
 5695                    }
 5696                }
 5697            }
 5698
 5699            this.signature_help_state.set_backspace_pressed(true);
 5700            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5701            this.insert("", cx);
 5702            let empty_str: Arc<str> = Arc::from("");
 5703            for (buffer, edits) in linked_ranges {
 5704                let snapshot = buffer.read(cx).snapshot();
 5705                use text::ToPoint as TP;
 5706
 5707                let edits = edits
 5708                    .into_iter()
 5709                    .map(|range| {
 5710                        let end_point = TP::to_point(&range.end, &snapshot);
 5711                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5712
 5713                        if end_point == start_point {
 5714                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5715                                .saturating_sub(1);
 5716                            start_point = TP::to_point(&offset, &snapshot);
 5717                        };
 5718
 5719                        (start_point..end_point, empty_str.clone())
 5720                    })
 5721                    .sorted_by_key(|(range, _)| range.start)
 5722                    .collect::<Vec<_>>();
 5723                buffer.update(cx, |this, cx| {
 5724                    this.edit(edits, None, cx);
 5725                })
 5726            }
 5727            this.refresh_inline_completion(true, false, cx);
 5728            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5729        });
 5730    }
 5731
 5732    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5733        self.transact(cx, |this, cx| {
 5734            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5735                let line_mode = s.line_mode;
 5736                s.move_with(|map, selection| {
 5737                    if selection.is_empty() && !line_mode {
 5738                        let cursor = movement::right(map, selection.head());
 5739                        selection.end = cursor;
 5740                        selection.reversed = true;
 5741                        selection.goal = SelectionGoal::None;
 5742                    }
 5743                })
 5744            });
 5745            this.insert("", cx);
 5746            this.refresh_inline_completion(true, false, cx);
 5747        });
 5748    }
 5749
 5750    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5751        if self.move_to_prev_snippet_tabstop(cx) {
 5752            return;
 5753        }
 5754
 5755        self.outdent(&Outdent, cx);
 5756    }
 5757
 5758    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5759        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5760            return;
 5761        }
 5762
 5763        let mut selections = self.selections.all_adjusted(cx);
 5764        let buffer = self.buffer.read(cx);
 5765        let snapshot = buffer.snapshot(cx);
 5766        let rows_iter = selections.iter().map(|s| s.head().row);
 5767        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5768
 5769        let mut edits = Vec::new();
 5770        let mut prev_edited_row = 0;
 5771        let mut row_delta = 0;
 5772        for selection in &mut selections {
 5773            if selection.start.row != prev_edited_row {
 5774                row_delta = 0;
 5775            }
 5776            prev_edited_row = selection.end.row;
 5777
 5778            // If the selection is non-empty, then increase the indentation of the selected lines.
 5779            if !selection.is_empty() {
 5780                row_delta =
 5781                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5782                continue;
 5783            }
 5784
 5785            // If the selection is empty and the cursor is in the leading whitespace before the
 5786            // suggested indentation, then auto-indent the line.
 5787            let cursor = selection.head();
 5788            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5789            if let Some(suggested_indent) =
 5790                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5791            {
 5792                if cursor.column < suggested_indent.len
 5793                    && cursor.column <= current_indent.len
 5794                    && current_indent.len <= suggested_indent.len
 5795                {
 5796                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5797                    selection.end = selection.start;
 5798                    if row_delta == 0 {
 5799                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5800                            cursor.row,
 5801                            current_indent,
 5802                            suggested_indent,
 5803                        ));
 5804                        row_delta = suggested_indent.len - current_indent.len;
 5805                    }
 5806                    continue;
 5807                }
 5808            }
 5809
 5810            // Otherwise, insert a hard or soft tab.
 5811            let settings = buffer.settings_at(cursor, cx);
 5812            let tab_size = if settings.hard_tabs {
 5813                IndentSize::tab()
 5814            } else {
 5815                let tab_size = settings.tab_size.get();
 5816                let char_column = snapshot
 5817                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5818                    .flat_map(str::chars)
 5819                    .count()
 5820                    + row_delta as usize;
 5821                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5822                IndentSize::spaces(chars_to_next_tab_stop)
 5823            };
 5824            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5825            selection.end = selection.start;
 5826            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5827            row_delta += tab_size.len;
 5828        }
 5829
 5830        self.transact(cx, |this, cx| {
 5831            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5832            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5833            this.refresh_inline_completion(true, false, cx);
 5834        });
 5835    }
 5836
 5837    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5838        if self.read_only(cx) {
 5839            return;
 5840        }
 5841        let mut selections = self.selections.all::<Point>(cx);
 5842        let mut prev_edited_row = 0;
 5843        let mut row_delta = 0;
 5844        let mut edits = Vec::new();
 5845        let buffer = self.buffer.read(cx);
 5846        let snapshot = buffer.snapshot(cx);
 5847        for selection in &mut selections {
 5848            if selection.start.row != prev_edited_row {
 5849                row_delta = 0;
 5850            }
 5851            prev_edited_row = selection.end.row;
 5852
 5853            row_delta =
 5854                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5855        }
 5856
 5857        self.transact(cx, |this, cx| {
 5858            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5859            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5860        });
 5861    }
 5862
 5863    fn indent_selection(
 5864        buffer: &MultiBuffer,
 5865        snapshot: &MultiBufferSnapshot,
 5866        selection: &mut Selection<Point>,
 5867        edits: &mut Vec<(Range<Point>, String)>,
 5868        delta_for_start_row: u32,
 5869        cx: &AppContext,
 5870    ) -> u32 {
 5871        let settings = buffer.settings_at(selection.start, cx);
 5872        let tab_size = settings.tab_size.get();
 5873        let indent_kind = if settings.hard_tabs {
 5874            IndentKind::Tab
 5875        } else {
 5876            IndentKind::Space
 5877        };
 5878        let mut start_row = selection.start.row;
 5879        let mut end_row = selection.end.row + 1;
 5880
 5881        // If a selection ends at the beginning of a line, don't indent
 5882        // that last line.
 5883        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5884            end_row -= 1;
 5885        }
 5886
 5887        // Avoid re-indenting a row that has already been indented by a
 5888        // previous selection, but still update this selection's column
 5889        // to reflect that indentation.
 5890        if delta_for_start_row > 0 {
 5891            start_row += 1;
 5892            selection.start.column += delta_for_start_row;
 5893            if selection.end.row == selection.start.row {
 5894                selection.end.column += delta_for_start_row;
 5895            }
 5896        }
 5897
 5898        let mut delta_for_end_row = 0;
 5899        let has_multiple_rows = start_row + 1 != end_row;
 5900        for row in start_row..end_row {
 5901            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5902            let indent_delta = match (current_indent.kind, indent_kind) {
 5903                (IndentKind::Space, IndentKind::Space) => {
 5904                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5905                    IndentSize::spaces(columns_to_next_tab_stop)
 5906                }
 5907                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5908                (_, IndentKind::Tab) => IndentSize::tab(),
 5909            };
 5910
 5911            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5912                0
 5913            } else {
 5914                selection.start.column
 5915            };
 5916            let row_start = Point::new(row, start);
 5917            edits.push((
 5918                row_start..row_start,
 5919                indent_delta.chars().collect::<String>(),
 5920            ));
 5921
 5922            // Update this selection's endpoints to reflect the indentation.
 5923            if row == selection.start.row {
 5924                selection.start.column += indent_delta.len;
 5925            }
 5926            if row == selection.end.row {
 5927                selection.end.column += indent_delta.len;
 5928                delta_for_end_row = indent_delta.len;
 5929            }
 5930        }
 5931
 5932        if selection.start.row == selection.end.row {
 5933            delta_for_start_row + delta_for_end_row
 5934        } else {
 5935            delta_for_end_row
 5936        }
 5937    }
 5938
 5939    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5940        if self.read_only(cx) {
 5941            return;
 5942        }
 5943        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5944        let selections = self.selections.all::<Point>(cx);
 5945        let mut deletion_ranges = Vec::new();
 5946        let mut last_outdent = None;
 5947        {
 5948            let buffer = self.buffer.read(cx);
 5949            let snapshot = buffer.snapshot(cx);
 5950            for selection in &selections {
 5951                let settings = buffer.settings_at(selection.start, cx);
 5952                let tab_size = settings.tab_size.get();
 5953                let mut rows = selection.spanned_rows(false, &display_map);
 5954
 5955                // Avoid re-outdenting a row that has already been outdented by a
 5956                // previous selection.
 5957                if let Some(last_row) = last_outdent {
 5958                    if last_row == rows.start {
 5959                        rows.start = rows.start.next_row();
 5960                    }
 5961                }
 5962                let has_multiple_rows = rows.len() > 1;
 5963                for row in rows.iter_rows() {
 5964                    let indent_size = snapshot.indent_size_for_line(row);
 5965                    if indent_size.len > 0 {
 5966                        let deletion_len = match indent_size.kind {
 5967                            IndentKind::Space => {
 5968                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5969                                if columns_to_prev_tab_stop == 0 {
 5970                                    tab_size
 5971                                } else {
 5972                                    columns_to_prev_tab_stop
 5973                                }
 5974                            }
 5975                            IndentKind::Tab => 1,
 5976                        };
 5977                        let start = if has_multiple_rows
 5978                            || deletion_len > selection.start.column
 5979                            || indent_size.len < selection.start.column
 5980                        {
 5981                            0
 5982                        } else {
 5983                            selection.start.column - deletion_len
 5984                        };
 5985                        deletion_ranges.push(
 5986                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5987                        );
 5988                        last_outdent = Some(row);
 5989                    }
 5990                }
 5991            }
 5992        }
 5993
 5994        self.transact(cx, |this, cx| {
 5995            this.buffer.update(cx, |buffer, cx| {
 5996                let empty_str: Arc<str> = Arc::default();
 5997                buffer.edit(
 5998                    deletion_ranges
 5999                        .into_iter()
 6000                        .map(|range| (range, empty_str.clone())),
 6001                    None,
 6002                    cx,
 6003                );
 6004            });
 6005            let selections = this.selections.all::<usize>(cx);
 6006            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6007        });
 6008    }
 6009
 6010    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6011        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6012        let selections = self.selections.all::<Point>(cx);
 6013
 6014        let mut new_cursors = Vec::new();
 6015        let mut edit_ranges = Vec::new();
 6016        let mut selections = selections.iter().peekable();
 6017        while let Some(selection) = selections.next() {
 6018            let mut rows = selection.spanned_rows(false, &display_map);
 6019            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6020
 6021            // Accumulate contiguous regions of rows that we want to delete.
 6022            while let Some(next_selection) = selections.peek() {
 6023                let next_rows = next_selection.spanned_rows(false, &display_map);
 6024                if next_rows.start <= rows.end {
 6025                    rows.end = next_rows.end;
 6026                    selections.next().unwrap();
 6027                } else {
 6028                    break;
 6029                }
 6030            }
 6031
 6032            let buffer = &display_map.buffer_snapshot;
 6033            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6034            let edit_end;
 6035            let cursor_buffer_row;
 6036            if buffer.max_point().row >= rows.end.0 {
 6037                // If there's a line after the range, delete the \n from the end of the row range
 6038                // and position the cursor on the next line.
 6039                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6040                cursor_buffer_row = rows.end;
 6041            } else {
 6042                // If there isn't a line after the range, delete the \n from the line before the
 6043                // start of the row range and position the cursor there.
 6044                edit_start = edit_start.saturating_sub(1);
 6045                edit_end = buffer.len();
 6046                cursor_buffer_row = rows.start.previous_row();
 6047            }
 6048
 6049            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6050            *cursor.column_mut() =
 6051                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6052
 6053            new_cursors.push((
 6054                selection.id,
 6055                buffer.anchor_after(cursor.to_point(&display_map)),
 6056            ));
 6057            edit_ranges.push(edit_start..edit_end);
 6058        }
 6059
 6060        self.transact(cx, |this, cx| {
 6061            let buffer = this.buffer.update(cx, |buffer, cx| {
 6062                let empty_str: Arc<str> = Arc::default();
 6063                buffer.edit(
 6064                    edit_ranges
 6065                        .into_iter()
 6066                        .map(|range| (range, empty_str.clone())),
 6067                    None,
 6068                    cx,
 6069                );
 6070                buffer.snapshot(cx)
 6071            });
 6072            let new_selections = new_cursors
 6073                .into_iter()
 6074                .map(|(id, cursor)| {
 6075                    let cursor = cursor.to_point(&buffer);
 6076                    Selection {
 6077                        id,
 6078                        start: cursor,
 6079                        end: cursor,
 6080                        reversed: false,
 6081                        goal: SelectionGoal::None,
 6082                    }
 6083                })
 6084                .collect();
 6085
 6086            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6087                s.select(new_selections);
 6088            });
 6089        });
 6090    }
 6091
 6092    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6093        if self.read_only(cx) {
 6094            return;
 6095        }
 6096        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6097        for selection in self.selections.all::<Point>(cx) {
 6098            let start = MultiBufferRow(selection.start.row);
 6099            let end = if selection.start.row == selection.end.row {
 6100                MultiBufferRow(selection.start.row + 1)
 6101            } else {
 6102                MultiBufferRow(selection.end.row)
 6103            };
 6104
 6105            if let Some(last_row_range) = row_ranges.last_mut() {
 6106                if start <= last_row_range.end {
 6107                    last_row_range.end = end;
 6108                    continue;
 6109                }
 6110            }
 6111            row_ranges.push(start..end);
 6112        }
 6113
 6114        let snapshot = self.buffer.read(cx).snapshot(cx);
 6115        let mut cursor_positions = Vec::new();
 6116        for row_range in &row_ranges {
 6117            let anchor = snapshot.anchor_before(Point::new(
 6118                row_range.end.previous_row().0,
 6119                snapshot.line_len(row_range.end.previous_row()),
 6120            ));
 6121            cursor_positions.push(anchor..anchor);
 6122        }
 6123
 6124        self.transact(cx, |this, cx| {
 6125            for row_range in row_ranges.into_iter().rev() {
 6126                for row in row_range.iter_rows().rev() {
 6127                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6128                    let next_line_row = row.next_row();
 6129                    let indent = snapshot.indent_size_for_line(next_line_row);
 6130                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6131
 6132                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6133                        " "
 6134                    } else {
 6135                        ""
 6136                    };
 6137
 6138                    this.buffer.update(cx, |buffer, cx| {
 6139                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6140                    });
 6141                }
 6142            }
 6143
 6144            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6145                s.select_anchor_ranges(cursor_positions)
 6146            });
 6147        });
 6148    }
 6149
 6150    pub fn sort_lines_case_sensitive(
 6151        &mut self,
 6152        _: &SortLinesCaseSensitive,
 6153        cx: &mut ViewContext<Self>,
 6154    ) {
 6155        self.manipulate_lines(cx, |lines| lines.sort())
 6156    }
 6157
 6158    pub fn sort_lines_case_insensitive(
 6159        &mut self,
 6160        _: &SortLinesCaseInsensitive,
 6161        cx: &mut ViewContext<Self>,
 6162    ) {
 6163        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6164    }
 6165
 6166    pub fn unique_lines_case_insensitive(
 6167        &mut self,
 6168        _: &UniqueLinesCaseInsensitive,
 6169        cx: &mut ViewContext<Self>,
 6170    ) {
 6171        self.manipulate_lines(cx, |lines| {
 6172            let mut seen = HashSet::default();
 6173            lines.retain(|line| seen.insert(line.to_lowercase()));
 6174        })
 6175    }
 6176
 6177    pub fn unique_lines_case_sensitive(
 6178        &mut self,
 6179        _: &UniqueLinesCaseSensitive,
 6180        cx: &mut ViewContext<Self>,
 6181    ) {
 6182        self.manipulate_lines(cx, |lines| {
 6183            let mut seen = HashSet::default();
 6184            lines.retain(|line| seen.insert(*line));
 6185        })
 6186    }
 6187
 6188    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6189        let mut revert_changes = HashMap::default();
 6190        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6191        for hunk in hunks_for_rows(
 6192            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6193            &multi_buffer_snapshot,
 6194        ) {
 6195            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6196        }
 6197        if !revert_changes.is_empty() {
 6198            self.transact(cx, |editor, cx| {
 6199                editor.revert(revert_changes, cx);
 6200            });
 6201        }
 6202    }
 6203
 6204    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6205        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6206        if !revert_changes.is_empty() {
 6207            self.transact(cx, |editor, cx| {
 6208                editor.revert(revert_changes, cx);
 6209            });
 6210        }
 6211    }
 6212
 6213    fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
 6214        let snapshot = self.buffer.read(cx).snapshot(cx);
 6215        let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
 6216        self.transact(cx, |editor, cx| {
 6217            for hunk in hunks {
 6218                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
 6219                    buffer.update(cx, |buffer, cx| {
 6220                        buffer.merge_into_base(Some(hunk.buffer_range.to_offset(buffer)), cx);
 6221                    });
 6222                }
 6223            }
 6224        });
 6225    }
 6226
 6227    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6228        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6229            let project_path = buffer.read(cx).project_path(cx)?;
 6230            let project = self.project.as_ref()?.read(cx);
 6231            let entry = project.entry_for_path(&project_path, cx)?;
 6232            let abs_path = project.absolute_path(&project_path, cx)?;
 6233            let parent = if entry.is_symlink {
 6234                abs_path.canonicalize().ok()?
 6235            } else {
 6236                abs_path
 6237            }
 6238            .parent()?
 6239            .to_path_buf();
 6240            Some(parent)
 6241        }) {
 6242            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6243        }
 6244    }
 6245
 6246    fn gather_revert_changes(
 6247        &mut self,
 6248        selections: &[Selection<Anchor>],
 6249        cx: &mut ViewContext<'_, Editor>,
 6250    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6251        let mut revert_changes = HashMap::default();
 6252        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6253        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6254            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6255        }
 6256        revert_changes
 6257    }
 6258
 6259    pub fn prepare_revert_change(
 6260        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6261        multi_buffer: &Model<MultiBuffer>,
 6262        hunk: &MultiBufferDiffHunk,
 6263        cx: &AppContext,
 6264    ) -> Option<()> {
 6265        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6266        let buffer = buffer.read(cx);
 6267        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6268        let buffer_snapshot = buffer.snapshot();
 6269        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6270        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6271            probe
 6272                .0
 6273                .start
 6274                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6275                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6276        }) {
 6277            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6278            Some(())
 6279        } else {
 6280            None
 6281        }
 6282    }
 6283
 6284    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6285        self.manipulate_lines(cx, |lines| lines.reverse())
 6286    }
 6287
 6288    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6289        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6290    }
 6291
 6292    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6293    where
 6294        Fn: FnMut(&mut Vec<&str>),
 6295    {
 6296        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6297        let buffer = self.buffer.read(cx).snapshot(cx);
 6298
 6299        let mut edits = Vec::new();
 6300
 6301        let selections = self.selections.all::<Point>(cx);
 6302        let mut selections = selections.iter().peekable();
 6303        let mut contiguous_row_selections = Vec::new();
 6304        let mut new_selections = Vec::new();
 6305        let mut added_lines = 0;
 6306        let mut removed_lines = 0;
 6307
 6308        while let Some(selection) = selections.next() {
 6309            let (start_row, end_row) = consume_contiguous_rows(
 6310                &mut contiguous_row_selections,
 6311                selection,
 6312                &display_map,
 6313                &mut selections,
 6314            );
 6315
 6316            let start_point = Point::new(start_row.0, 0);
 6317            let end_point = Point::new(
 6318                end_row.previous_row().0,
 6319                buffer.line_len(end_row.previous_row()),
 6320            );
 6321            let text = buffer
 6322                .text_for_range(start_point..end_point)
 6323                .collect::<String>();
 6324
 6325            let mut lines = text.split('\n').collect_vec();
 6326
 6327            let lines_before = lines.len();
 6328            callback(&mut lines);
 6329            let lines_after = lines.len();
 6330
 6331            edits.push((start_point..end_point, lines.join("\n")));
 6332
 6333            // Selections must change based on added and removed line count
 6334            let start_row =
 6335                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6336            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6337            new_selections.push(Selection {
 6338                id: selection.id,
 6339                start: start_row,
 6340                end: end_row,
 6341                goal: SelectionGoal::None,
 6342                reversed: selection.reversed,
 6343            });
 6344
 6345            if lines_after > lines_before {
 6346                added_lines += lines_after - lines_before;
 6347            } else if lines_before > lines_after {
 6348                removed_lines += lines_before - lines_after;
 6349            }
 6350        }
 6351
 6352        self.transact(cx, |this, cx| {
 6353            let buffer = this.buffer.update(cx, |buffer, cx| {
 6354                buffer.edit(edits, None, cx);
 6355                buffer.snapshot(cx)
 6356            });
 6357
 6358            // Recalculate offsets on newly edited buffer
 6359            let new_selections = new_selections
 6360                .iter()
 6361                .map(|s| {
 6362                    let start_point = Point::new(s.start.0, 0);
 6363                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6364                    Selection {
 6365                        id: s.id,
 6366                        start: buffer.point_to_offset(start_point),
 6367                        end: buffer.point_to_offset(end_point),
 6368                        goal: s.goal,
 6369                        reversed: s.reversed,
 6370                    }
 6371                })
 6372                .collect();
 6373
 6374            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6375                s.select(new_selections);
 6376            });
 6377
 6378            this.request_autoscroll(Autoscroll::fit(), cx);
 6379        });
 6380    }
 6381
 6382    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6383        self.manipulate_text(cx, |text| text.to_uppercase())
 6384    }
 6385
 6386    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6387        self.manipulate_text(cx, |text| text.to_lowercase())
 6388    }
 6389
 6390    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6391        self.manipulate_text(cx, |text| {
 6392            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6393            // https://github.com/rutrum/convert-case/issues/16
 6394            text.split('\n')
 6395                .map(|line| line.to_case(Case::Title))
 6396                .join("\n")
 6397        })
 6398    }
 6399
 6400    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6401        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6402    }
 6403
 6404    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6405        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6406    }
 6407
 6408    pub fn convert_to_upper_camel_case(
 6409        &mut self,
 6410        _: &ConvertToUpperCamelCase,
 6411        cx: &mut ViewContext<Self>,
 6412    ) {
 6413        self.manipulate_text(cx, |text| {
 6414            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6415            // https://github.com/rutrum/convert-case/issues/16
 6416            text.split('\n')
 6417                .map(|line| line.to_case(Case::UpperCamel))
 6418                .join("\n")
 6419        })
 6420    }
 6421
 6422    pub fn convert_to_lower_camel_case(
 6423        &mut self,
 6424        _: &ConvertToLowerCamelCase,
 6425        cx: &mut ViewContext<Self>,
 6426    ) {
 6427        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6428    }
 6429
 6430    pub fn convert_to_opposite_case(
 6431        &mut self,
 6432        _: &ConvertToOppositeCase,
 6433        cx: &mut ViewContext<Self>,
 6434    ) {
 6435        self.manipulate_text(cx, |text| {
 6436            text.chars()
 6437                .fold(String::with_capacity(text.len()), |mut t, c| {
 6438                    if c.is_uppercase() {
 6439                        t.extend(c.to_lowercase());
 6440                    } else {
 6441                        t.extend(c.to_uppercase());
 6442                    }
 6443                    t
 6444                })
 6445        })
 6446    }
 6447
 6448    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6449    where
 6450        Fn: FnMut(&str) -> String,
 6451    {
 6452        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6453        let buffer = self.buffer.read(cx).snapshot(cx);
 6454
 6455        let mut new_selections = Vec::new();
 6456        let mut edits = Vec::new();
 6457        let mut selection_adjustment = 0i32;
 6458
 6459        for selection in self.selections.all::<usize>(cx) {
 6460            let selection_is_empty = selection.is_empty();
 6461
 6462            let (start, end) = if selection_is_empty {
 6463                let word_range = movement::surrounding_word(
 6464                    &display_map,
 6465                    selection.start.to_display_point(&display_map),
 6466                );
 6467                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6468                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6469                (start, end)
 6470            } else {
 6471                (selection.start, selection.end)
 6472            };
 6473
 6474            let text = buffer.text_for_range(start..end).collect::<String>();
 6475            let old_length = text.len() as i32;
 6476            let text = callback(&text);
 6477
 6478            new_selections.push(Selection {
 6479                start: (start as i32 - selection_adjustment) as usize,
 6480                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6481                goal: SelectionGoal::None,
 6482                ..selection
 6483            });
 6484
 6485            selection_adjustment += old_length - text.len() as i32;
 6486
 6487            edits.push((start..end, text));
 6488        }
 6489
 6490        self.transact(cx, |this, cx| {
 6491            this.buffer.update(cx, |buffer, cx| {
 6492                buffer.edit(edits, None, cx);
 6493            });
 6494
 6495            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6496                s.select(new_selections);
 6497            });
 6498
 6499            this.request_autoscroll(Autoscroll::fit(), cx);
 6500        });
 6501    }
 6502
 6503    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6504        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6505        let buffer = &display_map.buffer_snapshot;
 6506        let selections = self.selections.all::<Point>(cx);
 6507
 6508        let mut edits = Vec::new();
 6509        let mut selections_iter = selections.iter().peekable();
 6510        while let Some(selection) = selections_iter.next() {
 6511            // Avoid duplicating the same lines twice.
 6512            let mut rows = selection.spanned_rows(false, &display_map);
 6513
 6514            while let Some(next_selection) = selections_iter.peek() {
 6515                let next_rows = next_selection.spanned_rows(false, &display_map);
 6516                if next_rows.start < rows.end {
 6517                    rows.end = next_rows.end;
 6518                    selections_iter.next().unwrap();
 6519                } else {
 6520                    break;
 6521                }
 6522            }
 6523
 6524            // Copy the text from the selected row region and splice it either at the start
 6525            // or end of the region.
 6526            let start = Point::new(rows.start.0, 0);
 6527            let end = Point::new(
 6528                rows.end.previous_row().0,
 6529                buffer.line_len(rows.end.previous_row()),
 6530            );
 6531            let text = buffer
 6532                .text_for_range(start..end)
 6533                .chain(Some("\n"))
 6534                .collect::<String>();
 6535            let insert_location = if upwards {
 6536                Point::new(rows.end.0, 0)
 6537            } else {
 6538                start
 6539            };
 6540            edits.push((insert_location..insert_location, text));
 6541        }
 6542
 6543        self.transact(cx, |this, cx| {
 6544            this.buffer.update(cx, |buffer, cx| {
 6545                buffer.edit(edits, None, cx);
 6546            });
 6547
 6548            this.request_autoscroll(Autoscroll::fit(), cx);
 6549        });
 6550    }
 6551
 6552    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6553        self.duplicate_line(true, cx);
 6554    }
 6555
 6556    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6557        self.duplicate_line(false, cx);
 6558    }
 6559
 6560    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6561        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6562        let buffer = self.buffer.read(cx).snapshot(cx);
 6563
 6564        let mut edits = Vec::new();
 6565        let mut unfold_ranges = Vec::new();
 6566        let mut refold_ranges = Vec::new();
 6567
 6568        let selections = self.selections.all::<Point>(cx);
 6569        let mut selections = selections.iter().peekable();
 6570        let mut contiguous_row_selections = Vec::new();
 6571        let mut new_selections = Vec::new();
 6572
 6573        while let Some(selection) = selections.next() {
 6574            // Find all the selections that span a contiguous row range
 6575            let (start_row, end_row) = consume_contiguous_rows(
 6576                &mut contiguous_row_selections,
 6577                selection,
 6578                &display_map,
 6579                &mut selections,
 6580            );
 6581
 6582            // Move the text spanned by the row range to be before the line preceding the row range
 6583            if start_row.0 > 0 {
 6584                let range_to_move = Point::new(
 6585                    start_row.previous_row().0,
 6586                    buffer.line_len(start_row.previous_row()),
 6587                )
 6588                    ..Point::new(
 6589                        end_row.previous_row().0,
 6590                        buffer.line_len(end_row.previous_row()),
 6591                    );
 6592                let insertion_point = display_map
 6593                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6594                    .0;
 6595
 6596                // Don't move lines across excerpts
 6597                if buffer
 6598                    .excerpt_boundaries_in_range((
 6599                        Bound::Excluded(insertion_point),
 6600                        Bound::Included(range_to_move.end),
 6601                    ))
 6602                    .next()
 6603                    .is_none()
 6604                {
 6605                    let text = buffer
 6606                        .text_for_range(range_to_move.clone())
 6607                        .flat_map(|s| s.chars())
 6608                        .skip(1)
 6609                        .chain(['\n'])
 6610                        .collect::<String>();
 6611
 6612                    edits.push((
 6613                        buffer.anchor_after(range_to_move.start)
 6614                            ..buffer.anchor_before(range_to_move.end),
 6615                        String::new(),
 6616                    ));
 6617                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6618                    edits.push((insertion_anchor..insertion_anchor, text));
 6619
 6620                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6621
 6622                    // Move selections up
 6623                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6624                        |mut selection| {
 6625                            selection.start.row -= row_delta;
 6626                            selection.end.row -= row_delta;
 6627                            selection
 6628                        },
 6629                    ));
 6630
 6631                    // Move folds up
 6632                    unfold_ranges.push(range_to_move.clone());
 6633                    for fold in display_map.folds_in_range(
 6634                        buffer.anchor_before(range_to_move.start)
 6635                            ..buffer.anchor_after(range_to_move.end),
 6636                    ) {
 6637                        let mut start = fold.range.start.to_point(&buffer);
 6638                        let mut end = fold.range.end.to_point(&buffer);
 6639                        start.row -= row_delta;
 6640                        end.row -= row_delta;
 6641                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6642                    }
 6643                }
 6644            }
 6645
 6646            // If we didn't move line(s), preserve the existing selections
 6647            new_selections.append(&mut contiguous_row_selections);
 6648        }
 6649
 6650        self.transact(cx, |this, cx| {
 6651            this.unfold_ranges(unfold_ranges, true, true, cx);
 6652            this.buffer.update(cx, |buffer, cx| {
 6653                for (range, text) in edits {
 6654                    buffer.edit([(range, text)], None, cx);
 6655                }
 6656            });
 6657            this.fold_ranges(refold_ranges, true, cx);
 6658            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6659                s.select(new_selections);
 6660            })
 6661        });
 6662    }
 6663
 6664    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6665        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6666        let buffer = self.buffer.read(cx).snapshot(cx);
 6667
 6668        let mut edits = Vec::new();
 6669        let mut unfold_ranges = Vec::new();
 6670        let mut refold_ranges = Vec::new();
 6671
 6672        let selections = self.selections.all::<Point>(cx);
 6673        let mut selections = selections.iter().peekable();
 6674        let mut contiguous_row_selections = Vec::new();
 6675        let mut new_selections = Vec::new();
 6676
 6677        while let Some(selection) = selections.next() {
 6678            // Find all the selections that span a contiguous row range
 6679            let (start_row, end_row) = consume_contiguous_rows(
 6680                &mut contiguous_row_selections,
 6681                selection,
 6682                &display_map,
 6683                &mut selections,
 6684            );
 6685
 6686            // Move the text spanned by the row range to be after the last line of the row range
 6687            if end_row.0 <= buffer.max_point().row {
 6688                let range_to_move =
 6689                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6690                let insertion_point = display_map
 6691                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6692                    .0;
 6693
 6694                // Don't move lines across excerpt boundaries
 6695                if buffer
 6696                    .excerpt_boundaries_in_range((
 6697                        Bound::Excluded(range_to_move.start),
 6698                        Bound::Included(insertion_point),
 6699                    ))
 6700                    .next()
 6701                    .is_none()
 6702                {
 6703                    let mut text = String::from("\n");
 6704                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6705                    text.pop(); // Drop trailing newline
 6706                    edits.push((
 6707                        buffer.anchor_after(range_to_move.start)
 6708                            ..buffer.anchor_before(range_to_move.end),
 6709                        String::new(),
 6710                    ));
 6711                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6712                    edits.push((insertion_anchor..insertion_anchor, text));
 6713
 6714                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6715
 6716                    // Move selections down
 6717                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6718                        |mut selection| {
 6719                            selection.start.row += row_delta;
 6720                            selection.end.row += row_delta;
 6721                            selection
 6722                        },
 6723                    ));
 6724
 6725                    // Move folds down
 6726                    unfold_ranges.push(range_to_move.clone());
 6727                    for fold in display_map.folds_in_range(
 6728                        buffer.anchor_before(range_to_move.start)
 6729                            ..buffer.anchor_after(range_to_move.end),
 6730                    ) {
 6731                        let mut start = fold.range.start.to_point(&buffer);
 6732                        let mut end = fold.range.end.to_point(&buffer);
 6733                        start.row += row_delta;
 6734                        end.row += row_delta;
 6735                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6736                    }
 6737                }
 6738            }
 6739
 6740            // If we didn't move line(s), preserve the existing selections
 6741            new_selections.append(&mut contiguous_row_selections);
 6742        }
 6743
 6744        self.transact(cx, |this, cx| {
 6745            this.unfold_ranges(unfold_ranges, true, true, cx);
 6746            this.buffer.update(cx, |buffer, cx| {
 6747                for (range, text) in edits {
 6748                    buffer.edit([(range, text)], None, cx);
 6749                }
 6750            });
 6751            this.fold_ranges(refold_ranges, true, cx);
 6752            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6753        });
 6754    }
 6755
 6756    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6757        let text_layout_details = &self.text_layout_details(cx);
 6758        self.transact(cx, |this, cx| {
 6759            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6760                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6761                let line_mode = s.line_mode;
 6762                s.move_with(|display_map, selection| {
 6763                    if !selection.is_empty() || line_mode {
 6764                        return;
 6765                    }
 6766
 6767                    let mut head = selection.head();
 6768                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6769                    if head.column() == display_map.line_len(head.row()) {
 6770                        transpose_offset = display_map
 6771                            .buffer_snapshot
 6772                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6773                    }
 6774
 6775                    if transpose_offset == 0 {
 6776                        return;
 6777                    }
 6778
 6779                    *head.column_mut() += 1;
 6780                    head = display_map.clip_point(head, Bias::Right);
 6781                    let goal = SelectionGoal::HorizontalPosition(
 6782                        display_map
 6783                            .x_for_display_point(head, text_layout_details)
 6784                            .into(),
 6785                    );
 6786                    selection.collapse_to(head, goal);
 6787
 6788                    let transpose_start = display_map
 6789                        .buffer_snapshot
 6790                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6791                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6792                        let transpose_end = display_map
 6793                            .buffer_snapshot
 6794                            .clip_offset(transpose_offset + 1, Bias::Right);
 6795                        if let Some(ch) =
 6796                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6797                        {
 6798                            edits.push((transpose_start..transpose_offset, String::new()));
 6799                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6800                        }
 6801                    }
 6802                });
 6803                edits
 6804            });
 6805            this.buffer
 6806                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6807            let selections = this.selections.all::<usize>(cx);
 6808            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6809                s.select(selections);
 6810            });
 6811        });
 6812    }
 6813
 6814    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6815        self.rewrap_impl(true, cx)
 6816    }
 6817
 6818    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6819        let buffer = self.buffer.read(cx).snapshot(cx);
 6820        let selections = self.selections.all::<Point>(cx);
 6821        let mut selections = selections.iter().peekable();
 6822
 6823        let mut edits = Vec::new();
 6824        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6825
 6826        while let Some(selection) = selections.next() {
 6827            let mut start_row = selection.start.row;
 6828            let mut end_row = selection.end.row;
 6829
 6830            // Skip selections that overlap with a range that has already been rewrapped.
 6831            let selection_range = start_row..end_row;
 6832            if rewrapped_row_ranges
 6833                .iter()
 6834                .any(|range| range.overlaps(&selection_range))
 6835            {
 6836                continue;
 6837            }
 6838
 6839            let mut should_rewrap = !only_text;
 6840
 6841            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6842                match language_scope.language_name().0.as_ref() {
 6843                    "Markdown" | "Plain Text" => {
 6844                        should_rewrap = true;
 6845                    }
 6846                    _ => {}
 6847                }
 6848            }
 6849
 6850            // Since not all lines in the selection may be at the same indent
 6851            // level, choose the indent size that is the most common between all
 6852            // of the lines.
 6853            //
 6854            // If there is a tie, we use the deepest indent.
 6855            let (indent_size, indent_end) = {
 6856                let mut indent_size_occurrences = HashMap::default();
 6857                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6858
 6859                for row in start_row..=end_row {
 6860                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6861                    rows_by_indent_size.entry(indent).or_default().push(row);
 6862                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6863                }
 6864
 6865                let indent_size = indent_size_occurrences
 6866                    .into_iter()
 6867                    .max_by_key(|(indent, count)| (*count, indent.len))
 6868                    .map(|(indent, _)| indent)
 6869                    .unwrap_or_default();
 6870                let row = rows_by_indent_size[&indent_size][0];
 6871                let indent_end = Point::new(row, indent_size.len);
 6872
 6873                (indent_size, indent_end)
 6874            };
 6875
 6876            let mut line_prefix = indent_size.chars().collect::<String>();
 6877
 6878            if let Some(comment_prefix) =
 6879                buffer
 6880                    .language_scope_at(selection.head())
 6881                    .and_then(|language| {
 6882                        language
 6883                            .line_comment_prefixes()
 6884                            .iter()
 6885                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6886                            .cloned()
 6887                    })
 6888            {
 6889                line_prefix.push_str(&comment_prefix);
 6890                should_rewrap = true;
 6891            }
 6892
 6893            if selection.is_empty() {
 6894                'expand_upwards: while start_row > 0 {
 6895                    let prev_row = start_row - 1;
 6896                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6897                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6898                    {
 6899                        start_row = prev_row;
 6900                    } else {
 6901                        break 'expand_upwards;
 6902                    }
 6903                }
 6904
 6905                'expand_downwards: while end_row < buffer.max_point().row {
 6906                    let next_row = end_row + 1;
 6907                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6908                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6909                    {
 6910                        end_row = next_row;
 6911                    } else {
 6912                        break 'expand_downwards;
 6913                    }
 6914                }
 6915            }
 6916
 6917            if !should_rewrap {
 6918                continue;
 6919            }
 6920
 6921            let start = Point::new(start_row, 0);
 6922            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6923            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6924            let Some(lines_without_prefixes) = selection_text
 6925                .lines()
 6926                .map(|line| {
 6927                    line.strip_prefix(&line_prefix)
 6928                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6929                        .ok_or_else(|| {
 6930                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6931                        })
 6932                })
 6933                .collect::<Result<Vec<_>, _>>()
 6934                .log_err()
 6935            else {
 6936                continue;
 6937            };
 6938
 6939            let unwrapped_text = lines_without_prefixes.join(" ");
 6940            let wrap_column = buffer
 6941                .settings_at(Point::new(start_row, 0), cx)
 6942                .preferred_line_length as usize;
 6943            let mut wrapped_text = String::new();
 6944            let mut current_line = line_prefix.clone();
 6945            for word in unwrapped_text.split_whitespace() {
 6946                if current_line.len() + word.len() >= wrap_column {
 6947                    wrapped_text.push_str(&current_line);
 6948                    wrapped_text.push('\n');
 6949                    current_line.truncate(line_prefix.len());
 6950                }
 6951
 6952                if current_line.len() > line_prefix.len() {
 6953                    current_line.push(' ');
 6954                }
 6955
 6956                current_line.push_str(word);
 6957            }
 6958
 6959            if !current_line.is_empty() {
 6960                wrapped_text.push_str(&current_line);
 6961            }
 6962
 6963            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 6964            let mut offset = start.to_offset(&buffer);
 6965            let mut moved_since_edit = true;
 6966
 6967            for change in diff.iter_all_changes() {
 6968                let value = change.value();
 6969                match change.tag() {
 6970                    ChangeTag::Equal => {
 6971                        offset += value.len();
 6972                        moved_since_edit = true;
 6973                    }
 6974                    ChangeTag::Delete => {
 6975                        let start = buffer.anchor_after(offset);
 6976                        let end = buffer.anchor_before(offset + value.len());
 6977
 6978                        if moved_since_edit {
 6979                            edits.push((start..end, String::new()));
 6980                        } else {
 6981                            edits.last_mut().unwrap().0.end = end;
 6982                        }
 6983
 6984                        offset += value.len();
 6985                        moved_since_edit = false;
 6986                    }
 6987                    ChangeTag::Insert => {
 6988                        if moved_since_edit {
 6989                            let anchor = buffer.anchor_after(offset);
 6990                            edits.push((anchor..anchor, value.to_string()));
 6991                        } else {
 6992                            edits.last_mut().unwrap().1.push_str(value);
 6993                        }
 6994
 6995                        moved_since_edit = false;
 6996                    }
 6997                }
 6998            }
 6999
 7000            rewrapped_row_ranges.push(start_row..=end_row);
 7001        }
 7002
 7003        self.buffer
 7004            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7005    }
 7006
 7007    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7008        let mut text = String::new();
 7009        let buffer = self.buffer.read(cx).snapshot(cx);
 7010        let mut selections = self.selections.all::<Point>(cx);
 7011        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7012        {
 7013            let max_point = buffer.max_point();
 7014            let mut is_first = true;
 7015            for selection in &mut selections {
 7016                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7017                if is_entire_line {
 7018                    selection.start = Point::new(selection.start.row, 0);
 7019                    if !selection.is_empty() && selection.end.column == 0 {
 7020                        selection.end = cmp::min(max_point, selection.end);
 7021                    } else {
 7022                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7023                    }
 7024                    selection.goal = SelectionGoal::None;
 7025                }
 7026                if is_first {
 7027                    is_first = false;
 7028                } else {
 7029                    text += "\n";
 7030                }
 7031                let mut len = 0;
 7032                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7033                    text.push_str(chunk);
 7034                    len += chunk.len();
 7035                }
 7036                clipboard_selections.push(ClipboardSelection {
 7037                    len,
 7038                    is_entire_line,
 7039                    first_line_indent: buffer
 7040                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7041                        .len,
 7042                });
 7043            }
 7044        }
 7045
 7046        self.transact(cx, |this, cx| {
 7047            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7048                s.select(selections);
 7049            });
 7050            this.insert("", cx);
 7051            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7052                text,
 7053                clipboard_selections,
 7054            ));
 7055        });
 7056    }
 7057
 7058    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7059        let selections = self.selections.all::<Point>(cx);
 7060        let buffer = self.buffer.read(cx).read(cx);
 7061        let mut text = String::new();
 7062
 7063        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7064        {
 7065            let max_point = buffer.max_point();
 7066            let mut is_first = true;
 7067            for selection in selections.iter() {
 7068                let mut start = selection.start;
 7069                let mut end = selection.end;
 7070                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7071                if is_entire_line {
 7072                    start = Point::new(start.row, 0);
 7073                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7074                }
 7075                if is_first {
 7076                    is_first = false;
 7077                } else {
 7078                    text += "\n";
 7079                }
 7080                let mut len = 0;
 7081                for chunk in buffer.text_for_range(start..end) {
 7082                    text.push_str(chunk);
 7083                    len += chunk.len();
 7084                }
 7085                clipboard_selections.push(ClipboardSelection {
 7086                    len,
 7087                    is_entire_line,
 7088                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7089                });
 7090            }
 7091        }
 7092
 7093        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7094            text,
 7095            clipboard_selections,
 7096        ));
 7097    }
 7098
 7099    pub fn do_paste(
 7100        &mut self,
 7101        text: &String,
 7102        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7103        handle_entire_lines: bool,
 7104        cx: &mut ViewContext<Self>,
 7105    ) {
 7106        if self.read_only(cx) {
 7107            return;
 7108        }
 7109
 7110        let clipboard_text = Cow::Borrowed(text);
 7111
 7112        self.transact(cx, |this, cx| {
 7113            if let Some(mut clipboard_selections) = clipboard_selections {
 7114                let old_selections = this.selections.all::<usize>(cx);
 7115                let all_selections_were_entire_line =
 7116                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7117                let first_selection_indent_column =
 7118                    clipboard_selections.first().map(|s| s.first_line_indent);
 7119                if clipboard_selections.len() != old_selections.len() {
 7120                    clipboard_selections.drain(..);
 7121                }
 7122
 7123                this.buffer.update(cx, |buffer, cx| {
 7124                    let snapshot = buffer.read(cx);
 7125                    let mut start_offset = 0;
 7126                    let mut edits = Vec::new();
 7127                    let mut original_indent_columns = Vec::new();
 7128                    for (ix, selection) in old_selections.iter().enumerate() {
 7129                        let to_insert;
 7130                        let entire_line;
 7131                        let original_indent_column;
 7132                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7133                            let end_offset = start_offset + clipboard_selection.len;
 7134                            to_insert = &clipboard_text[start_offset..end_offset];
 7135                            entire_line = clipboard_selection.is_entire_line;
 7136                            start_offset = end_offset + 1;
 7137                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7138                        } else {
 7139                            to_insert = clipboard_text.as_str();
 7140                            entire_line = all_selections_were_entire_line;
 7141                            original_indent_column = first_selection_indent_column
 7142                        }
 7143
 7144                        // If the corresponding selection was empty when this slice of the
 7145                        // clipboard text was written, then the entire line containing the
 7146                        // selection was copied. If this selection is also currently empty,
 7147                        // then paste the line before the current line of the buffer.
 7148                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7149                            let column = selection.start.to_point(&snapshot).column as usize;
 7150                            let line_start = selection.start - column;
 7151                            line_start..line_start
 7152                        } else {
 7153                            selection.range()
 7154                        };
 7155
 7156                        edits.push((range, to_insert));
 7157                        original_indent_columns.extend(original_indent_column);
 7158                    }
 7159                    drop(snapshot);
 7160
 7161                    buffer.edit(
 7162                        edits,
 7163                        Some(AutoindentMode::Block {
 7164                            original_indent_columns,
 7165                        }),
 7166                        cx,
 7167                    );
 7168                });
 7169
 7170                let selections = this.selections.all::<usize>(cx);
 7171                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7172            } else {
 7173                this.insert(&clipboard_text, cx);
 7174            }
 7175        });
 7176    }
 7177
 7178    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7179        if let Some(item) = cx.read_from_clipboard() {
 7180            let entries = item.entries();
 7181
 7182            match entries.first() {
 7183                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7184                // of all the pasted entries.
 7185                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7186                    .do_paste(
 7187                        clipboard_string.text(),
 7188                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7189                        true,
 7190                        cx,
 7191                    ),
 7192                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7193            }
 7194        }
 7195    }
 7196
 7197    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7198        if self.read_only(cx) {
 7199            return;
 7200        }
 7201
 7202        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7203            if let Some((selections, _)) =
 7204                self.selection_history.transaction(transaction_id).cloned()
 7205            {
 7206                self.change_selections(None, cx, |s| {
 7207                    s.select_anchors(selections.to_vec());
 7208                });
 7209            }
 7210            self.request_autoscroll(Autoscroll::fit(), cx);
 7211            self.unmark_text(cx);
 7212            self.refresh_inline_completion(true, false, cx);
 7213            cx.emit(EditorEvent::Edited { transaction_id });
 7214            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7215        }
 7216    }
 7217
 7218    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7219        if self.read_only(cx) {
 7220            return;
 7221        }
 7222
 7223        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7224            if let Some((_, Some(selections))) =
 7225                self.selection_history.transaction(transaction_id).cloned()
 7226            {
 7227                self.change_selections(None, cx, |s| {
 7228                    s.select_anchors(selections.to_vec());
 7229                });
 7230            }
 7231            self.request_autoscroll(Autoscroll::fit(), cx);
 7232            self.unmark_text(cx);
 7233            self.refresh_inline_completion(true, false, cx);
 7234            cx.emit(EditorEvent::Edited { transaction_id });
 7235        }
 7236    }
 7237
 7238    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7239        self.buffer
 7240            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7241    }
 7242
 7243    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7244        self.buffer
 7245            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7246    }
 7247
 7248    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7249        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7250            let line_mode = s.line_mode;
 7251            s.move_with(|map, selection| {
 7252                let cursor = if selection.is_empty() && !line_mode {
 7253                    movement::left(map, selection.start)
 7254                } else {
 7255                    selection.start
 7256                };
 7257                selection.collapse_to(cursor, SelectionGoal::None);
 7258            });
 7259        })
 7260    }
 7261
 7262    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7263        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7264            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7265        })
 7266    }
 7267
 7268    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7269        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7270            let line_mode = s.line_mode;
 7271            s.move_with(|map, selection| {
 7272                let cursor = if selection.is_empty() && !line_mode {
 7273                    movement::right(map, selection.end)
 7274                } else {
 7275                    selection.end
 7276                };
 7277                selection.collapse_to(cursor, SelectionGoal::None)
 7278            });
 7279        })
 7280    }
 7281
 7282    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7283        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7284            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7285        })
 7286    }
 7287
 7288    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7289        if self.take_rename(true, cx).is_some() {
 7290            return;
 7291        }
 7292
 7293        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7294            cx.propagate();
 7295            return;
 7296        }
 7297
 7298        let text_layout_details = &self.text_layout_details(cx);
 7299        let selection_count = self.selections.count();
 7300        let first_selection = self.selections.first_anchor();
 7301
 7302        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7303            let line_mode = s.line_mode;
 7304            s.move_with(|map, selection| {
 7305                if !selection.is_empty() && !line_mode {
 7306                    selection.goal = SelectionGoal::None;
 7307                }
 7308                let (cursor, goal) = movement::up(
 7309                    map,
 7310                    selection.start,
 7311                    selection.goal,
 7312                    false,
 7313                    text_layout_details,
 7314                );
 7315                selection.collapse_to(cursor, goal);
 7316            });
 7317        });
 7318
 7319        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7320        {
 7321            cx.propagate();
 7322        }
 7323    }
 7324
 7325    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7326        if self.take_rename(true, cx).is_some() {
 7327            return;
 7328        }
 7329
 7330        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7331            cx.propagate();
 7332            return;
 7333        }
 7334
 7335        let text_layout_details = &self.text_layout_details(cx);
 7336
 7337        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7338            let line_mode = s.line_mode;
 7339            s.move_with(|map, selection| {
 7340                if !selection.is_empty() && !line_mode {
 7341                    selection.goal = SelectionGoal::None;
 7342                }
 7343                let (cursor, goal) = movement::up_by_rows(
 7344                    map,
 7345                    selection.start,
 7346                    action.lines,
 7347                    selection.goal,
 7348                    false,
 7349                    text_layout_details,
 7350                );
 7351                selection.collapse_to(cursor, goal);
 7352            });
 7353        })
 7354    }
 7355
 7356    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7357        if self.take_rename(true, cx).is_some() {
 7358            return;
 7359        }
 7360
 7361        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7362            cx.propagate();
 7363            return;
 7364        }
 7365
 7366        let text_layout_details = &self.text_layout_details(cx);
 7367
 7368        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7369            let line_mode = s.line_mode;
 7370            s.move_with(|map, selection| {
 7371                if !selection.is_empty() && !line_mode {
 7372                    selection.goal = SelectionGoal::None;
 7373                }
 7374                let (cursor, goal) = movement::down_by_rows(
 7375                    map,
 7376                    selection.start,
 7377                    action.lines,
 7378                    selection.goal,
 7379                    false,
 7380                    text_layout_details,
 7381                );
 7382                selection.collapse_to(cursor, goal);
 7383            });
 7384        })
 7385    }
 7386
 7387    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7388        let text_layout_details = &self.text_layout_details(cx);
 7389        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7390            s.move_heads_with(|map, head, goal| {
 7391                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7392            })
 7393        })
 7394    }
 7395
 7396    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7397        let text_layout_details = &self.text_layout_details(cx);
 7398        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7399            s.move_heads_with(|map, head, goal| {
 7400                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7401            })
 7402        })
 7403    }
 7404
 7405    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7406        let Some(row_count) = self.visible_row_count() else {
 7407            return;
 7408        };
 7409
 7410        let text_layout_details = &self.text_layout_details(cx);
 7411
 7412        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7413            s.move_heads_with(|map, head, goal| {
 7414                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7415            })
 7416        })
 7417    }
 7418
 7419    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7420        if self.take_rename(true, cx).is_some() {
 7421            return;
 7422        }
 7423
 7424        if self
 7425            .context_menu
 7426            .write()
 7427            .as_mut()
 7428            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 7429            .unwrap_or(false)
 7430        {
 7431            return;
 7432        }
 7433
 7434        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7435            cx.propagate();
 7436            return;
 7437        }
 7438
 7439        let Some(row_count) = self.visible_row_count() else {
 7440            return;
 7441        };
 7442
 7443        let autoscroll = if action.center_cursor {
 7444            Autoscroll::center()
 7445        } else {
 7446            Autoscroll::fit()
 7447        };
 7448
 7449        let text_layout_details = &self.text_layout_details(cx);
 7450
 7451        self.change_selections(Some(autoscroll), cx, |s| {
 7452            let line_mode = s.line_mode;
 7453            s.move_with(|map, selection| {
 7454                if !selection.is_empty() && !line_mode {
 7455                    selection.goal = SelectionGoal::None;
 7456                }
 7457                let (cursor, goal) = movement::up_by_rows(
 7458                    map,
 7459                    selection.end,
 7460                    row_count,
 7461                    selection.goal,
 7462                    false,
 7463                    text_layout_details,
 7464                );
 7465                selection.collapse_to(cursor, goal);
 7466            });
 7467        });
 7468    }
 7469
 7470    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7471        let text_layout_details = &self.text_layout_details(cx);
 7472        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7473            s.move_heads_with(|map, head, goal| {
 7474                movement::up(map, head, goal, false, text_layout_details)
 7475            })
 7476        })
 7477    }
 7478
 7479    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7480        self.take_rename(true, cx);
 7481
 7482        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7483            cx.propagate();
 7484            return;
 7485        }
 7486
 7487        let text_layout_details = &self.text_layout_details(cx);
 7488        let selection_count = self.selections.count();
 7489        let first_selection = self.selections.first_anchor();
 7490
 7491        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7492            let line_mode = s.line_mode;
 7493            s.move_with(|map, selection| {
 7494                if !selection.is_empty() && !line_mode {
 7495                    selection.goal = SelectionGoal::None;
 7496                }
 7497                let (cursor, goal) = movement::down(
 7498                    map,
 7499                    selection.end,
 7500                    selection.goal,
 7501                    false,
 7502                    text_layout_details,
 7503                );
 7504                selection.collapse_to(cursor, goal);
 7505            });
 7506        });
 7507
 7508        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7509        {
 7510            cx.propagate();
 7511        }
 7512    }
 7513
 7514    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7515        let Some(row_count) = self.visible_row_count() else {
 7516            return;
 7517        };
 7518
 7519        let text_layout_details = &self.text_layout_details(cx);
 7520
 7521        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7522            s.move_heads_with(|map, head, goal| {
 7523                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7524            })
 7525        })
 7526    }
 7527
 7528    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7529        if self.take_rename(true, cx).is_some() {
 7530            return;
 7531        }
 7532
 7533        if self
 7534            .context_menu
 7535            .write()
 7536            .as_mut()
 7537            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7538            .unwrap_or(false)
 7539        {
 7540            return;
 7541        }
 7542
 7543        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7544            cx.propagate();
 7545            return;
 7546        }
 7547
 7548        let Some(row_count) = self.visible_row_count() else {
 7549            return;
 7550        };
 7551
 7552        let autoscroll = if action.center_cursor {
 7553            Autoscroll::center()
 7554        } else {
 7555            Autoscroll::fit()
 7556        };
 7557
 7558        let text_layout_details = &self.text_layout_details(cx);
 7559        self.change_selections(Some(autoscroll), cx, |s| {
 7560            let line_mode = s.line_mode;
 7561            s.move_with(|map, selection| {
 7562                if !selection.is_empty() && !line_mode {
 7563                    selection.goal = SelectionGoal::None;
 7564                }
 7565                let (cursor, goal) = movement::down_by_rows(
 7566                    map,
 7567                    selection.end,
 7568                    row_count,
 7569                    selection.goal,
 7570                    false,
 7571                    text_layout_details,
 7572                );
 7573                selection.collapse_to(cursor, goal);
 7574            });
 7575        });
 7576    }
 7577
 7578    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7579        let text_layout_details = &self.text_layout_details(cx);
 7580        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7581            s.move_heads_with(|map, head, goal| {
 7582                movement::down(map, head, goal, false, text_layout_details)
 7583            })
 7584        });
 7585    }
 7586
 7587    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7588        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7589            context_menu.select_first(self.project.as_ref(), cx);
 7590        }
 7591    }
 7592
 7593    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7594        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7595            context_menu.select_prev(self.project.as_ref(), cx);
 7596        }
 7597    }
 7598
 7599    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7600        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7601            context_menu.select_next(self.project.as_ref(), cx);
 7602        }
 7603    }
 7604
 7605    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7606        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7607            context_menu.select_last(self.project.as_ref(), cx);
 7608        }
 7609    }
 7610
 7611    pub fn move_to_previous_word_start(
 7612        &mut self,
 7613        _: &MoveToPreviousWordStart,
 7614        cx: &mut ViewContext<Self>,
 7615    ) {
 7616        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7617            s.move_cursors_with(|map, head, _| {
 7618                (
 7619                    movement::previous_word_start(map, head),
 7620                    SelectionGoal::None,
 7621                )
 7622            });
 7623        })
 7624    }
 7625
 7626    pub fn move_to_previous_subword_start(
 7627        &mut self,
 7628        _: &MoveToPreviousSubwordStart,
 7629        cx: &mut ViewContext<Self>,
 7630    ) {
 7631        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7632            s.move_cursors_with(|map, head, _| {
 7633                (
 7634                    movement::previous_subword_start(map, head),
 7635                    SelectionGoal::None,
 7636                )
 7637            });
 7638        })
 7639    }
 7640
 7641    pub fn select_to_previous_word_start(
 7642        &mut self,
 7643        _: &SelectToPreviousWordStart,
 7644        cx: &mut ViewContext<Self>,
 7645    ) {
 7646        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7647            s.move_heads_with(|map, head, _| {
 7648                (
 7649                    movement::previous_word_start(map, head),
 7650                    SelectionGoal::None,
 7651                )
 7652            });
 7653        })
 7654    }
 7655
 7656    pub fn select_to_previous_subword_start(
 7657        &mut self,
 7658        _: &SelectToPreviousSubwordStart,
 7659        cx: &mut ViewContext<Self>,
 7660    ) {
 7661        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7662            s.move_heads_with(|map, head, _| {
 7663                (
 7664                    movement::previous_subword_start(map, head),
 7665                    SelectionGoal::None,
 7666                )
 7667            });
 7668        })
 7669    }
 7670
 7671    pub fn delete_to_previous_word_start(
 7672        &mut self,
 7673        action: &DeleteToPreviousWordStart,
 7674        cx: &mut ViewContext<Self>,
 7675    ) {
 7676        self.transact(cx, |this, cx| {
 7677            this.select_autoclose_pair(cx);
 7678            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7679                let line_mode = s.line_mode;
 7680                s.move_with(|map, selection| {
 7681                    if selection.is_empty() && !line_mode {
 7682                        let cursor = if action.ignore_newlines {
 7683                            movement::previous_word_start(map, selection.head())
 7684                        } else {
 7685                            movement::previous_word_start_or_newline(map, selection.head())
 7686                        };
 7687                        selection.set_head(cursor, SelectionGoal::None);
 7688                    }
 7689                });
 7690            });
 7691            this.insert("", cx);
 7692        });
 7693    }
 7694
 7695    pub fn delete_to_previous_subword_start(
 7696        &mut self,
 7697        _: &DeleteToPreviousSubwordStart,
 7698        cx: &mut ViewContext<Self>,
 7699    ) {
 7700        self.transact(cx, |this, cx| {
 7701            this.select_autoclose_pair(cx);
 7702            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7703                let line_mode = s.line_mode;
 7704                s.move_with(|map, selection| {
 7705                    if selection.is_empty() && !line_mode {
 7706                        let cursor = movement::previous_subword_start(map, selection.head());
 7707                        selection.set_head(cursor, SelectionGoal::None);
 7708                    }
 7709                });
 7710            });
 7711            this.insert("", cx);
 7712        });
 7713    }
 7714
 7715    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7716        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7717            s.move_cursors_with(|map, head, _| {
 7718                (movement::next_word_end(map, head), SelectionGoal::None)
 7719            });
 7720        })
 7721    }
 7722
 7723    pub fn move_to_next_subword_end(
 7724        &mut self,
 7725        _: &MoveToNextSubwordEnd,
 7726        cx: &mut ViewContext<Self>,
 7727    ) {
 7728        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7729            s.move_cursors_with(|map, head, _| {
 7730                (movement::next_subword_end(map, head), SelectionGoal::None)
 7731            });
 7732        })
 7733    }
 7734
 7735    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7736        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7737            s.move_heads_with(|map, head, _| {
 7738                (movement::next_word_end(map, head), SelectionGoal::None)
 7739            });
 7740        })
 7741    }
 7742
 7743    pub fn select_to_next_subword_end(
 7744        &mut self,
 7745        _: &SelectToNextSubwordEnd,
 7746        cx: &mut ViewContext<Self>,
 7747    ) {
 7748        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7749            s.move_heads_with(|map, head, _| {
 7750                (movement::next_subword_end(map, head), SelectionGoal::None)
 7751            });
 7752        })
 7753    }
 7754
 7755    pub fn delete_to_next_word_end(
 7756        &mut self,
 7757        action: &DeleteToNextWordEnd,
 7758        cx: &mut ViewContext<Self>,
 7759    ) {
 7760        self.transact(cx, |this, cx| {
 7761            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7762                let line_mode = s.line_mode;
 7763                s.move_with(|map, selection| {
 7764                    if selection.is_empty() && !line_mode {
 7765                        let cursor = if action.ignore_newlines {
 7766                            movement::next_word_end(map, selection.head())
 7767                        } else {
 7768                            movement::next_word_end_or_newline(map, selection.head())
 7769                        };
 7770                        selection.set_head(cursor, SelectionGoal::None);
 7771                    }
 7772                });
 7773            });
 7774            this.insert("", cx);
 7775        });
 7776    }
 7777
 7778    pub fn delete_to_next_subword_end(
 7779        &mut self,
 7780        _: &DeleteToNextSubwordEnd,
 7781        cx: &mut ViewContext<Self>,
 7782    ) {
 7783        self.transact(cx, |this, cx| {
 7784            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7785                s.move_with(|map, selection| {
 7786                    if selection.is_empty() {
 7787                        let cursor = movement::next_subword_end(map, selection.head());
 7788                        selection.set_head(cursor, SelectionGoal::None);
 7789                    }
 7790                });
 7791            });
 7792            this.insert("", cx);
 7793        });
 7794    }
 7795
 7796    pub fn move_to_beginning_of_line(
 7797        &mut self,
 7798        action: &MoveToBeginningOfLine,
 7799        cx: &mut ViewContext<Self>,
 7800    ) {
 7801        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7802            s.move_cursors_with(|map, head, _| {
 7803                (
 7804                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7805                    SelectionGoal::None,
 7806                )
 7807            });
 7808        })
 7809    }
 7810
 7811    pub fn select_to_beginning_of_line(
 7812        &mut self,
 7813        action: &SelectToBeginningOfLine,
 7814        cx: &mut ViewContext<Self>,
 7815    ) {
 7816        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7817            s.move_heads_with(|map, head, _| {
 7818                (
 7819                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7820                    SelectionGoal::None,
 7821                )
 7822            });
 7823        });
 7824    }
 7825
 7826    pub fn delete_to_beginning_of_line(
 7827        &mut self,
 7828        _: &DeleteToBeginningOfLine,
 7829        cx: &mut ViewContext<Self>,
 7830    ) {
 7831        self.transact(cx, |this, cx| {
 7832            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7833                s.move_with(|_, selection| {
 7834                    selection.reversed = true;
 7835                });
 7836            });
 7837
 7838            this.select_to_beginning_of_line(
 7839                &SelectToBeginningOfLine {
 7840                    stop_at_soft_wraps: false,
 7841                },
 7842                cx,
 7843            );
 7844            this.backspace(&Backspace, cx);
 7845        });
 7846    }
 7847
 7848    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7849        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7850            s.move_cursors_with(|map, head, _| {
 7851                (
 7852                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7853                    SelectionGoal::None,
 7854                )
 7855            });
 7856        })
 7857    }
 7858
 7859    pub fn select_to_end_of_line(
 7860        &mut self,
 7861        action: &SelectToEndOfLine,
 7862        cx: &mut ViewContext<Self>,
 7863    ) {
 7864        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7865            s.move_heads_with(|map, head, _| {
 7866                (
 7867                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7868                    SelectionGoal::None,
 7869                )
 7870            });
 7871        })
 7872    }
 7873
 7874    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7875        self.transact(cx, |this, cx| {
 7876            this.select_to_end_of_line(
 7877                &SelectToEndOfLine {
 7878                    stop_at_soft_wraps: false,
 7879                },
 7880                cx,
 7881            );
 7882            this.delete(&Delete, cx);
 7883        });
 7884    }
 7885
 7886    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7887        self.transact(cx, |this, cx| {
 7888            this.select_to_end_of_line(
 7889                &SelectToEndOfLine {
 7890                    stop_at_soft_wraps: false,
 7891                },
 7892                cx,
 7893            );
 7894            this.cut(&Cut, cx);
 7895        });
 7896    }
 7897
 7898    pub fn move_to_start_of_paragraph(
 7899        &mut self,
 7900        _: &MoveToStartOfParagraph,
 7901        cx: &mut ViewContext<Self>,
 7902    ) {
 7903        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7904            cx.propagate();
 7905            return;
 7906        }
 7907
 7908        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7909            s.move_with(|map, selection| {
 7910                selection.collapse_to(
 7911                    movement::start_of_paragraph(map, selection.head(), 1),
 7912                    SelectionGoal::None,
 7913                )
 7914            });
 7915        })
 7916    }
 7917
 7918    pub fn move_to_end_of_paragraph(
 7919        &mut self,
 7920        _: &MoveToEndOfParagraph,
 7921        cx: &mut ViewContext<Self>,
 7922    ) {
 7923        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7924            cx.propagate();
 7925            return;
 7926        }
 7927
 7928        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7929            s.move_with(|map, selection| {
 7930                selection.collapse_to(
 7931                    movement::end_of_paragraph(map, selection.head(), 1),
 7932                    SelectionGoal::None,
 7933                )
 7934            });
 7935        })
 7936    }
 7937
 7938    pub fn select_to_start_of_paragraph(
 7939        &mut self,
 7940        _: &SelectToStartOfParagraph,
 7941        cx: &mut ViewContext<Self>,
 7942    ) {
 7943        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7944            cx.propagate();
 7945            return;
 7946        }
 7947
 7948        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7949            s.move_heads_with(|map, head, _| {
 7950                (
 7951                    movement::start_of_paragraph(map, head, 1),
 7952                    SelectionGoal::None,
 7953                )
 7954            });
 7955        })
 7956    }
 7957
 7958    pub fn select_to_end_of_paragraph(
 7959        &mut self,
 7960        _: &SelectToEndOfParagraph,
 7961        cx: &mut ViewContext<Self>,
 7962    ) {
 7963        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7964            cx.propagate();
 7965            return;
 7966        }
 7967
 7968        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7969            s.move_heads_with(|map, head, _| {
 7970                (
 7971                    movement::end_of_paragraph(map, head, 1),
 7972                    SelectionGoal::None,
 7973                )
 7974            });
 7975        })
 7976    }
 7977
 7978    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7979        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7980            cx.propagate();
 7981            return;
 7982        }
 7983
 7984        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7985            s.select_ranges(vec![0..0]);
 7986        });
 7987    }
 7988
 7989    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7990        let mut selection = self.selections.last::<Point>(cx);
 7991        selection.set_head(Point::zero(), SelectionGoal::None);
 7992
 7993        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7994            s.select(vec![selection]);
 7995        });
 7996    }
 7997
 7998    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7999        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8000            cx.propagate();
 8001            return;
 8002        }
 8003
 8004        let cursor = self.buffer.read(cx).read(cx).len();
 8005        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8006            s.select_ranges(vec![cursor..cursor])
 8007        });
 8008    }
 8009
 8010    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8011        self.nav_history = nav_history;
 8012    }
 8013
 8014    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8015        self.nav_history.as_ref()
 8016    }
 8017
 8018    fn push_to_nav_history(
 8019        &mut self,
 8020        cursor_anchor: Anchor,
 8021        new_position: Option<Point>,
 8022        cx: &mut ViewContext<Self>,
 8023    ) {
 8024        if let Some(nav_history) = self.nav_history.as_mut() {
 8025            let buffer = self.buffer.read(cx).read(cx);
 8026            let cursor_position = cursor_anchor.to_point(&buffer);
 8027            let scroll_state = self.scroll_manager.anchor();
 8028            let scroll_top_row = scroll_state.top_row(&buffer);
 8029            drop(buffer);
 8030
 8031            if let Some(new_position) = new_position {
 8032                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8033                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8034                    return;
 8035                }
 8036            }
 8037
 8038            nav_history.push(
 8039                Some(NavigationData {
 8040                    cursor_anchor,
 8041                    cursor_position,
 8042                    scroll_anchor: scroll_state,
 8043                    scroll_top_row,
 8044                }),
 8045                cx,
 8046            );
 8047        }
 8048    }
 8049
 8050    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8051        let buffer = self.buffer.read(cx).snapshot(cx);
 8052        let mut selection = self.selections.first::<usize>(cx);
 8053        selection.set_head(buffer.len(), SelectionGoal::None);
 8054        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8055            s.select(vec![selection]);
 8056        });
 8057    }
 8058
 8059    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8060        let end = self.buffer.read(cx).read(cx).len();
 8061        self.change_selections(None, cx, |s| {
 8062            s.select_ranges(vec![0..end]);
 8063        });
 8064    }
 8065
 8066    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8067        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8068        let mut selections = self.selections.all::<Point>(cx);
 8069        let max_point = display_map.buffer_snapshot.max_point();
 8070        for selection in &mut selections {
 8071            let rows = selection.spanned_rows(true, &display_map);
 8072            selection.start = Point::new(rows.start.0, 0);
 8073            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8074            selection.reversed = false;
 8075        }
 8076        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8077            s.select(selections);
 8078        });
 8079    }
 8080
 8081    pub fn split_selection_into_lines(
 8082        &mut self,
 8083        _: &SplitSelectionIntoLines,
 8084        cx: &mut ViewContext<Self>,
 8085    ) {
 8086        let mut to_unfold = Vec::new();
 8087        let mut new_selection_ranges = Vec::new();
 8088        {
 8089            let selections = self.selections.all::<Point>(cx);
 8090            let buffer = self.buffer.read(cx).read(cx);
 8091            for selection in selections {
 8092                for row in selection.start.row..selection.end.row {
 8093                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8094                    new_selection_ranges.push(cursor..cursor);
 8095                }
 8096                new_selection_ranges.push(selection.end..selection.end);
 8097                to_unfold.push(selection.start..selection.end);
 8098            }
 8099        }
 8100        self.unfold_ranges(to_unfold, true, true, cx);
 8101        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8102            s.select_ranges(new_selection_ranges);
 8103        });
 8104    }
 8105
 8106    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8107        self.add_selection(true, cx);
 8108    }
 8109
 8110    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8111        self.add_selection(false, cx);
 8112    }
 8113
 8114    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8115        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8116        let mut selections = self.selections.all::<Point>(cx);
 8117        let text_layout_details = self.text_layout_details(cx);
 8118        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8119            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8120            let range = oldest_selection.display_range(&display_map).sorted();
 8121
 8122            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8123            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8124            let positions = start_x.min(end_x)..start_x.max(end_x);
 8125
 8126            selections.clear();
 8127            let mut stack = Vec::new();
 8128            for row in range.start.row().0..=range.end.row().0 {
 8129                if let Some(selection) = self.selections.build_columnar_selection(
 8130                    &display_map,
 8131                    DisplayRow(row),
 8132                    &positions,
 8133                    oldest_selection.reversed,
 8134                    &text_layout_details,
 8135                ) {
 8136                    stack.push(selection.id);
 8137                    selections.push(selection);
 8138                }
 8139            }
 8140
 8141            if above {
 8142                stack.reverse();
 8143            }
 8144
 8145            AddSelectionsState { above, stack }
 8146        });
 8147
 8148        let last_added_selection = *state.stack.last().unwrap();
 8149        let mut new_selections = Vec::new();
 8150        if above == state.above {
 8151            let end_row = if above {
 8152                DisplayRow(0)
 8153            } else {
 8154                display_map.max_point().row()
 8155            };
 8156
 8157            'outer: for selection in selections {
 8158                if selection.id == last_added_selection {
 8159                    let range = selection.display_range(&display_map).sorted();
 8160                    debug_assert_eq!(range.start.row(), range.end.row());
 8161                    let mut row = range.start.row();
 8162                    let positions =
 8163                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8164                            px(start)..px(end)
 8165                        } else {
 8166                            let start_x =
 8167                                display_map.x_for_display_point(range.start, &text_layout_details);
 8168                            let end_x =
 8169                                display_map.x_for_display_point(range.end, &text_layout_details);
 8170                            start_x.min(end_x)..start_x.max(end_x)
 8171                        };
 8172
 8173                    while row != end_row {
 8174                        if above {
 8175                            row.0 -= 1;
 8176                        } else {
 8177                            row.0 += 1;
 8178                        }
 8179
 8180                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8181                            &display_map,
 8182                            row,
 8183                            &positions,
 8184                            selection.reversed,
 8185                            &text_layout_details,
 8186                        ) {
 8187                            state.stack.push(new_selection.id);
 8188                            if above {
 8189                                new_selections.push(new_selection);
 8190                                new_selections.push(selection);
 8191                            } else {
 8192                                new_selections.push(selection);
 8193                                new_selections.push(new_selection);
 8194                            }
 8195
 8196                            continue 'outer;
 8197                        }
 8198                    }
 8199                }
 8200
 8201                new_selections.push(selection);
 8202            }
 8203        } else {
 8204            new_selections = selections;
 8205            new_selections.retain(|s| s.id != last_added_selection);
 8206            state.stack.pop();
 8207        }
 8208
 8209        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8210            s.select(new_selections);
 8211        });
 8212        if state.stack.len() > 1 {
 8213            self.add_selections_state = Some(state);
 8214        }
 8215    }
 8216
 8217    pub fn select_next_match_internal(
 8218        &mut self,
 8219        display_map: &DisplaySnapshot,
 8220        replace_newest: bool,
 8221        autoscroll: Option<Autoscroll>,
 8222        cx: &mut ViewContext<Self>,
 8223    ) -> Result<()> {
 8224        fn select_next_match_ranges(
 8225            this: &mut Editor,
 8226            range: Range<usize>,
 8227            replace_newest: bool,
 8228            auto_scroll: Option<Autoscroll>,
 8229            cx: &mut ViewContext<Editor>,
 8230        ) {
 8231            this.unfold_ranges([range.clone()], false, true, cx);
 8232            this.change_selections(auto_scroll, cx, |s| {
 8233                if replace_newest {
 8234                    s.delete(s.newest_anchor().id);
 8235                }
 8236                s.insert_range(range.clone());
 8237            });
 8238        }
 8239
 8240        let buffer = &display_map.buffer_snapshot;
 8241        let mut selections = self.selections.all::<usize>(cx);
 8242        if let Some(mut select_next_state) = self.select_next_state.take() {
 8243            let query = &select_next_state.query;
 8244            if !select_next_state.done {
 8245                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8246                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8247                let mut next_selected_range = None;
 8248
 8249                let bytes_after_last_selection =
 8250                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8251                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8252                let query_matches = query
 8253                    .stream_find_iter(bytes_after_last_selection)
 8254                    .map(|result| (last_selection.end, result))
 8255                    .chain(
 8256                        query
 8257                            .stream_find_iter(bytes_before_first_selection)
 8258                            .map(|result| (0, result)),
 8259                    );
 8260
 8261                for (start_offset, query_match) in query_matches {
 8262                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8263                    let offset_range =
 8264                        start_offset + query_match.start()..start_offset + query_match.end();
 8265                    let display_range = offset_range.start.to_display_point(display_map)
 8266                        ..offset_range.end.to_display_point(display_map);
 8267
 8268                    if !select_next_state.wordwise
 8269                        || (!movement::is_inside_word(display_map, display_range.start)
 8270                            && !movement::is_inside_word(display_map, display_range.end))
 8271                    {
 8272                        // TODO: This is n^2, because we might check all the selections
 8273                        if !selections
 8274                            .iter()
 8275                            .any(|selection| selection.range().overlaps(&offset_range))
 8276                        {
 8277                            next_selected_range = Some(offset_range);
 8278                            break;
 8279                        }
 8280                    }
 8281                }
 8282
 8283                if let Some(next_selected_range) = next_selected_range {
 8284                    select_next_match_ranges(
 8285                        self,
 8286                        next_selected_range,
 8287                        replace_newest,
 8288                        autoscroll,
 8289                        cx,
 8290                    );
 8291                } else {
 8292                    select_next_state.done = true;
 8293                }
 8294            }
 8295
 8296            self.select_next_state = Some(select_next_state);
 8297        } else {
 8298            let mut only_carets = true;
 8299            let mut same_text_selected = true;
 8300            let mut selected_text = None;
 8301
 8302            let mut selections_iter = selections.iter().peekable();
 8303            while let Some(selection) = selections_iter.next() {
 8304                if selection.start != selection.end {
 8305                    only_carets = false;
 8306                }
 8307
 8308                if same_text_selected {
 8309                    if selected_text.is_none() {
 8310                        selected_text =
 8311                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8312                    }
 8313
 8314                    if let Some(next_selection) = selections_iter.peek() {
 8315                        if next_selection.range().len() == selection.range().len() {
 8316                            let next_selected_text = buffer
 8317                                .text_for_range(next_selection.range())
 8318                                .collect::<String>();
 8319                            if Some(next_selected_text) != selected_text {
 8320                                same_text_selected = false;
 8321                                selected_text = None;
 8322                            }
 8323                        } else {
 8324                            same_text_selected = false;
 8325                            selected_text = None;
 8326                        }
 8327                    }
 8328                }
 8329            }
 8330
 8331            if only_carets {
 8332                for selection in &mut selections {
 8333                    let word_range = movement::surrounding_word(
 8334                        display_map,
 8335                        selection.start.to_display_point(display_map),
 8336                    );
 8337                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8338                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8339                    selection.goal = SelectionGoal::None;
 8340                    selection.reversed = false;
 8341                    select_next_match_ranges(
 8342                        self,
 8343                        selection.start..selection.end,
 8344                        replace_newest,
 8345                        autoscroll,
 8346                        cx,
 8347                    );
 8348                }
 8349
 8350                if selections.len() == 1 {
 8351                    let selection = selections
 8352                        .last()
 8353                        .expect("ensured that there's only one selection");
 8354                    let query = buffer
 8355                        .text_for_range(selection.start..selection.end)
 8356                        .collect::<String>();
 8357                    let is_empty = query.is_empty();
 8358                    let select_state = SelectNextState {
 8359                        query: AhoCorasick::new(&[query])?,
 8360                        wordwise: true,
 8361                        done: is_empty,
 8362                    };
 8363                    self.select_next_state = Some(select_state);
 8364                } else {
 8365                    self.select_next_state = None;
 8366                }
 8367            } else if let Some(selected_text) = selected_text {
 8368                self.select_next_state = Some(SelectNextState {
 8369                    query: AhoCorasick::new(&[selected_text])?,
 8370                    wordwise: false,
 8371                    done: false,
 8372                });
 8373                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8374            }
 8375        }
 8376        Ok(())
 8377    }
 8378
 8379    pub fn select_all_matches(
 8380        &mut self,
 8381        _action: &SelectAllMatches,
 8382        cx: &mut ViewContext<Self>,
 8383    ) -> Result<()> {
 8384        self.push_to_selection_history();
 8385        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8386
 8387        self.select_next_match_internal(&display_map, false, None, cx)?;
 8388        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8389            return Ok(());
 8390        };
 8391        if select_next_state.done {
 8392            return Ok(());
 8393        }
 8394
 8395        let mut new_selections = self.selections.all::<usize>(cx);
 8396
 8397        let buffer = &display_map.buffer_snapshot;
 8398        let query_matches = select_next_state
 8399            .query
 8400            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8401
 8402        for query_match in query_matches {
 8403            let query_match = query_match.unwrap(); // can only fail due to I/O
 8404            let offset_range = query_match.start()..query_match.end();
 8405            let display_range = offset_range.start.to_display_point(&display_map)
 8406                ..offset_range.end.to_display_point(&display_map);
 8407
 8408            if !select_next_state.wordwise
 8409                || (!movement::is_inside_word(&display_map, display_range.start)
 8410                    && !movement::is_inside_word(&display_map, display_range.end))
 8411            {
 8412                self.selections.change_with(cx, |selections| {
 8413                    new_selections.push(Selection {
 8414                        id: selections.new_selection_id(),
 8415                        start: offset_range.start,
 8416                        end: offset_range.end,
 8417                        reversed: false,
 8418                        goal: SelectionGoal::None,
 8419                    });
 8420                });
 8421            }
 8422        }
 8423
 8424        new_selections.sort_by_key(|selection| selection.start);
 8425        let mut ix = 0;
 8426        while ix + 1 < new_selections.len() {
 8427            let current_selection = &new_selections[ix];
 8428            let next_selection = &new_selections[ix + 1];
 8429            if current_selection.range().overlaps(&next_selection.range()) {
 8430                if current_selection.id < next_selection.id {
 8431                    new_selections.remove(ix + 1);
 8432                } else {
 8433                    new_selections.remove(ix);
 8434                }
 8435            } else {
 8436                ix += 1;
 8437            }
 8438        }
 8439
 8440        select_next_state.done = true;
 8441        self.unfold_ranges(
 8442            new_selections.iter().map(|selection| selection.range()),
 8443            false,
 8444            false,
 8445            cx,
 8446        );
 8447        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8448            selections.select(new_selections)
 8449        });
 8450
 8451        Ok(())
 8452    }
 8453
 8454    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8455        self.push_to_selection_history();
 8456        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8457        self.select_next_match_internal(
 8458            &display_map,
 8459            action.replace_newest,
 8460            Some(Autoscroll::newest()),
 8461            cx,
 8462        )?;
 8463        Ok(())
 8464    }
 8465
 8466    pub fn select_previous(
 8467        &mut self,
 8468        action: &SelectPrevious,
 8469        cx: &mut ViewContext<Self>,
 8470    ) -> Result<()> {
 8471        self.push_to_selection_history();
 8472        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8473        let buffer = &display_map.buffer_snapshot;
 8474        let mut selections = self.selections.all::<usize>(cx);
 8475        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8476            let query = &select_prev_state.query;
 8477            if !select_prev_state.done {
 8478                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8479                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8480                let mut next_selected_range = None;
 8481                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8482                let bytes_before_last_selection =
 8483                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8484                let bytes_after_first_selection =
 8485                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8486                let query_matches = query
 8487                    .stream_find_iter(bytes_before_last_selection)
 8488                    .map(|result| (last_selection.start, result))
 8489                    .chain(
 8490                        query
 8491                            .stream_find_iter(bytes_after_first_selection)
 8492                            .map(|result| (buffer.len(), result)),
 8493                    );
 8494                for (end_offset, query_match) in query_matches {
 8495                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8496                    let offset_range =
 8497                        end_offset - query_match.end()..end_offset - query_match.start();
 8498                    let display_range = offset_range.start.to_display_point(&display_map)
 8499                        ..offset_range.end.to_display_point(&display_map);
 8500
 8501                    if !select_prev_state.wordwise
 8502                        || (!movement::is_inside_word(&display_map, display_range.start)
 8503                            && !movement::is_inside_word(&display_map, display_range.end))
 8504                    {
 8505                        next_selected_range = Some(offset_range);
 8506                        break;
 8507                    }
 8508                }
 8509
 8510                if let Some(next_selected_range) = next_selected_range {
 8511                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8512                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8513                        if action.replace_newest {
 8514                            s.delete(s.newest_anchor().id);
 8515                        }
 8516                        s.insert_range(next_selected_range);
 8517                    });
 8518                } else {
 8519                    select_prev_state.done = true;
 8520                }
 8521            }
 8522
 8523            self.select_prev_state = Some(select_prev_state);
 8524        } else {
 8525            let mut only_carets = true;
 8526            let mut same_text_selected = true;
 8527            let mut selected_text = None;
 8528
 8529            let mut selections_iter = selections.iter().peekable();
 8530            while let Some(selection) = selections_iter.next() {
 8531                if selection.start != selection.end {
 8532                    only_carets = false;
 8533                }
 8534
 8535                if same_text_selected {
 8536                    if selected_text.is_none() {
 8537                        selected_text =
 8538                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8539                    }
 8540
 8541                    if let Some(next_selection) = selections_iter.peek() {
 8542                        if next_selection.range().len() == selection.range().len() {
 8543                            let next_selected_text = buffer
 8544                                .text_for_range(next_selection.range())
 8545                                .collect::<String>();
 8546                            if Some(next_selected_text) != selected_text {
 8547                                same_text_selected = false;
 8548                                selected_text = None;
 8549                            }
 8550                        } else {
 8551                            same_text_selected = false;
 8552                            selected_text = None;
 8553                        }
 8554                    }
 8555                }
 8556            }
 8557
 8558            if only_carets {
 8559                for selection in &mut selections {
 8560                    let word_range = movement::surrounding_word(
 8561                        &display_map,
 8562                        selection.start.to_display_point(&display_map),
 8563                    );
 8564                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8565                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8566                    selection.goal = SelectionGoal::None;
 8567                    selection.reversed = false;
 8568                }
 8569                if selections.len() == 1 {
 8570                    let selection = selections
 8571                        .last()
 8572                        .expect("ensured that there's only one selection");
 8573                    let query = buffer
 8574                        .text_for_range(selection.start..selection.end)
 8575                        .collect::<String>();
 8576                    let is_empty = query.is_empty();
 8577                    let select_state = SelectNextState {
 8578                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8579                        wordwise: true,
 8580                        done: is_empty,
 8581                    };
 8582                    self.select_prev_state = Some(select_state);
 8583                } else {
 8584                    self.select_prev_state = None;
 8585                }
 8586
 8587                self.unfold_ranges(
 8588                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8589                    false,
 8590                    true,
 8591                    cx,
 8592                );
 8593                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8594                    s.select(selections);
 8595                });
 8596            } else if let Some(selected_text) = selected_text {
 8597                self.select_prev_state = Some(SelectNextState {
 8598                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8599                    wordwise: false,
 8600                    done: false,
 8601                });
 8602                self.select_previous(action, cx)?;
 8603            }
 8604        }
 8605        Ok(())
 8606    }
 8607
 8608    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8609        let text_layout_details = &self.text_layout_details(cx);
 8610        self.transact(cx, |this, cx| {
 8611            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8612            let mut edits = Vec::new();
 8613            let mut selection_edit_ranges = Vec::new();
 8614            let mut last_toggled_row = None;
 8615            let snapshot = this.buffer.read(cx).read(cx);
 8616            let empty_str: Arc<str> = Arc::default();
 8617            let mut suffixes_inserted = Vec::new();
 8618
 8619            fn comment_prefix_range(
 8620                snapshot: &MultiBufferSnapshot,
 8621                row: MultiBufferRow,
 8622                comment_prefix: &str,
 8623                comment_prefix_whitespace: &str,
 8624            ) -> Range<Point> {
 8625                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8626
 8627                let mut line_bytes = snapshot
 8628                    .bytes_in_range(start..snapshot.max_point())
 8629                    .flatten()
 8630                    .copied();
 8631
 8632                // If this line currently begins with the line comment prefix, then record
 8633                // the range containing the prefix.
 8634                if line_bytes
 8635                    .by_ref()
 8636                    .take(comment_prefix.len())
 8637                    .eq(comment_prefix.bytes())
 8638                {
 8639                    // Include any whitespace that matches the comment prefix.
 8640                    let matching_whitespace_len = line_bytes
 8641                        .zip(comment_prefix_whitespace.bytes())
 8642                        .take_while(|(a, b)| a == b)
 8643                        .count() as u32;
 8644                    let end = Point::new(
 8645                        start.row,
 8646                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8647                    );
 8648                    start..end
 8649                } else {
 8650                    start..start
 8651                }
 8652            }
 8653
 8654            fn comment_suffix_range(
 8655                snapshot: &MultiBufferSnapshot,
 8656                row: MultiBufferRow,
 8657                comment_suffix: &str,
 8658                comment_suffix_has_leading_space: bool,
 8659            ) -> Range<Point> {
 8660                let end = Point::new(row.0, snapshot.line_len(row));
 8661                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8662
 8663                let mut line_end_bytes = snapshot
 8664                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8665                    .flatten()
 8666                    .copied();
 8667
 8668                let leading_space_len = if suffix_start_column > 0
 8669                    && line_end_bytes.next() == Some(b' ')
 8670                    && comment_suffix_has_leading_space
 8671                {
 8672                    1
 8673                } else {
 8674                    0
 8675                };
 8676
 8677                // If this line currently begins with the line comment prefix, then record
 8678                // the range containing the prefix.
 8679                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8680                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8681                    start..end
 8682                } else {
 8683                    end..end
 8684                }
 8685            }
 8686
 8687            // TODO: Handle selections that cross excerpts
 8688            for selection in &mut selections {
 8689                let start_column = snapshot
 8690                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8691                    .len;
 8692                let language = if let Some(language) =
 8693                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8694                {
 8695                    language
 8696                } else {
 8697                    continue;
 8698                };
 8699
 8700                selection_edit_ranges.clear();
 8701
 8702                // If multiple selections contain a given row, avoid processing that
 8703                // row more than once.
 8704                let mut start_row = MultiBufferRow(selection.start.row);
 8705                if last_toggled_row == Some(start_row) {
 8706                    start_row = start_row.next_row();
 8707                }
 8708                let end_row =
 8709                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8710                        MultiBufferRow(selection.end.row - 1)
 8711                    } else {
 8712                        MultiBufferRow(selection.end.row)
 8713                    };
 8714                last_toggled_row = Some(end_row);
 8715
 8716                if start_row > end_row {
 8717                    continue;
 8718                }
 8719
 8720                // If the language has line comments, toggle those.
 8721                let full_comment_prefixes = language.line_comment_prefixes();
 8722                if !full_comment_prefixes.is_empty() {
 8723                    let first_prefix = full_comment_prefixes
 8724                        .first()
 8725                        .expect("prefixes is non-empty");
 8726                    let prefix_trimmed_lengths = full_comment_prefixes
 8727                        .iter()
 8728                        .map(|p| p.trim_end_matches(' ').len())
 8729                        .collect::<SmallVec<[usize; 4]>>();
 8730
 8731                    let mut all_selection_lines_are_comments = true;
 8732
 8733                    for row in start_row.0..=end_row.0 {
 8734                        let row = MultiBufferRow(row);
 8735                        if start_row < end_row && snapshot.is_line_blank(row) {
 8736                            continue;
 8737                        }
 8738
 8739                        let prefix_range = full_comment_prefixes
 8740                            .iter()
 8741                            .zip(prefix_trimmed_lengths.iter().copied())
 8742                            .map(|(prefix, trimmed_prefix_len)| {
 8743                                comment_prefix_range(
 8744                                    snapshot.deref(),
 8745                                    row,
 8746                                    &prefix[..trimmed_prefix_len],
 8747                                    &prefix[trimmed_prefix_len..],
 8748                                )
 8749                            })
 8750                            .max_by_key(|range| range.end.column - range.start.column)
 8751                            .expect("prefixes is non-empty");
 8752
 8753                        if prefix_range.is_empty() {
 8754                            all_selection_lines_are_comments = false;
 8755                        }
 8756
 8757                        selection_edit_ranges.push(prefix_range);
 8758                    }
 8759
 8760                    if all_selection_lines_are_comments {
 8761                        edits.extend(
 8762                            selection_edit_ranges
 8763                                .iter()
 8764                                .cloned()
 8765                                .map(|range| (range, empty_str.clone())),
 8766                        );
 8767                    } else {
 8768                        let min_column = selection_edit_ranges
 8769                            .iter()
 8770                            .map(|range| range.start.column)
 8771                            .min()
 8772                            .unwrap_or(0);
 8773                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8774                            let position = Point::new(range.start.row, min_column);
 8775                            (position..position, first_prefix.clone())
 8776                        }));
 8777                    }
 8778                } else if let Some((full_comment_prefix, comment_suffix)) =
 8779                    language.block_comment_delimiters()
 8780                {
 8781                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8782                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8783                    let prefix_range = comment_prefix_range(
 8784                        snapshot.deref(),
 8785                        start_row,
 8786                        comment_prefix,
 8787                        comment_prefix_whitespace,
 8788                    );
 8789                    let suffix_range = comment_suffix_range(
 8790                        snapshot.deref(),
 8791                        end_row,
 8792                        comment_suffix.trim_start_matches(' '),
 8793                        comment_suffix.starts_with(' '),
 8794                    );
 8795
 8796                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8797                        edits.push((
 8798                            prefix_range.start..prefix_range.start,
 8799                            full_comment_prefix.clone(),
 8800                        ));
 8801                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8802                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8803                    } else {
 8804                        edits.push((prefix_range, empty_str.clone()));
 8805                        edits.push((suffix_range, empty_str.clone()));
 8806                    }
 8807                } else {
 8808                    continue;
 8809                }
 8810            }
 8811
 8812            drop(snapshot);
 8813            this.buffer.update(cx, |buffer, cx| {
 8814                buffer.edit(edits, None, cx);
 8815            });
 8816
 8817            // Adjust selections so that they end before any comment suffixes that
 8818            // were inserted.
 8819            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8820            let mut selections = this.selections.all::<Point>(cx);
 8821            let snapshot = this.buffer.read(cx).read(cx);
 8822            for selection in &mut selections {
 8823                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8824                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8825                        Ordering::Less => {
 8826                            suffixes_inserted.next();
 8827                            continue;
 8828                        }
 8829                        Ordering::Greater => break,
 8830                        Ordering::Equal => {
 8831                            if selection.end.column == snapshot.line_len(row) {
 8832                                if selection.is_empty() {
 8833                                    selection.start.column -= suffix_len as u32;
 8834                                }
 8835                                selection.end.column -= suffix_len as u32;
 8836                            }
 8837                            break;
 8838                        }
 8839                    }
 8840                }
 8841            }
 8842
 8843            drop(snapshot);
 8844            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8845
 8846            let selections = this.selections.all::<Point>(cx);
 8847            let selections_on_single_row = selections.windows(2).all(|selections| {
 8848                selections[0].start.row == selections[1].start.row
 8849                    && selections[0].end.row == selections[1].end.row
 8850                    && selections[0].start.row == selections[0].end.row
 8851            });
 8852            let selections_selecting = selections
 8853                .iter()
 8854                .any(|selection| selection.start != selection.end);
 8855            let advance_downwards = action.advance_downwards
 8856                && selections_on_single_row
 8857                && !selections_selecting
 8858                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8859
 8860            if advance_downwards {
 8861                let snapshot = this.buffer.read(cx).snapshot(cx);
 8862
 8863                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8864                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8865                        let mut point = display_point.to_point(display_snapshot);
 8866                        point.row += 1;
 8867                        point = snapshot.clip_point(point, Bias::Left);
 8868                        let display_point = point.to_display_point(display_snapshot);
 8869                        let goal = SelectionGoal::HorizontalPosition(
 8870                            display_snapshot
 8871                                .x_for_display_point(display_point, text_layout_details)
 8872                                .into(),
 8873                        );
 8874                        (display_point, goal)
 8875                    })
 8876                });
 8877            }
 8878        });
 8879    }
 8880
 8881    pub fn select_enclosing_symbol(
 8882        &mut self,
 8883        _: &SelectEnclosingSymbol,
 8884        cx: &mut ViewContext<Self>,
 8885    ) {
 8886        let buffer = self.buffer.read(cx).snapshot(cx);
 8887        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8888
 8889        fn update_selection(
 8890            selection: &Selection<usize>,
 8891            buffer_snap: &MultiBufferSnapshot,
 8892        ) -> Option<Selection<usize>> {
 8893            let cursor = selection.head();
 8894            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8895            for symbol in symbols.iter().rev() {
 8896                let start = symbol.range.start.to_offset(buffer_snap);
 8897                let end = symbol.range.end.to_offset(buffer_snap);
 8898                let new_range = start..end;
 8899                if start < selection.start || end > selection.end {
 8900                    return Some(Selection {
 8901                        id: selection.id,
 8902                        start: new_range.start,
 8903                        end: new_range.end,
 8904                        goal: SelectionGoal::None,
 8905                        reversed: selection.reversed,
 8906                    });
 8907                }
 8908            }
 8909            None
 8910        }
 8911
 8912        let mut selected_larger_symbol = false;
 8913        let new_selections = old_selections
 8914            .iter()
 8915            .map(|selection| match update_selection(selection, &buffer) {
 8916                Some(new_selection) => {
 8917                    if new_selection.range() != selection.range() {
 8918                        selected_larger_symbol = true;
 8919                    }
 8920                    new_selection
 8921                }
 8922                None => selection.clone(),
 8923            })
 8924            .collect::<Vec<_>>();
 8925
 8926        if selected_larger_symbol {
 8927            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8928                s.select(new_selections);
 8929            });
 8930        }
 8931    }
 8932
 8933    pub fn select_larger_syntax_node(
 8934        &mut self,
 8935        _: &SelectLargerSyntaxNode,
 8936        cx: &mut ViewContext<Self>,
 8937    ) {
 8938        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8939        let buffer = self.buffer.read(cx).snapshot(cx);
 8940        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8941
 8942        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8943        let mut selected_larger_node = false;
 8944        let new_selections = old_selections
 8945            .iter()
 8946            .map(|selection| {
 8947                let old_range = selection.start..selection.end;
 8948                let mut new_range = old_range.clone();
 8949                while let Some(containing_range) =
 8950                    buffer.range_for_syntax_ancestor(new_range.clone())
 8951                {
 8952                    new_range = containing_range;
 8953                    if !display_map.intersects_fold(new_range.start)
 8954                        && !display_map.intersects_fold(new_range.end)
 8955                    {
 8956                        break;
 8957                    }
 8958                }
 8959
 8960                selected_larger_node |= new_range != old_range;
 8961                Selection {
 8962                    id: selection.id,
 8963                    start: new_range.start,
 8964                    end: new_range.end,
 8965                    goal: SelectionGoal::None,
 8966                    reversed: selection.reversed,
 8967                }
 8968            })
 8969            .collect::<Vec<_>>();
 8970
 8971        if selected_larger_node {
 8972            stack.push(old_selections);
 8973            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8974                s.select(new_selections);
 8975            });
 8976        }
 8977        self.select_larger_syntax_node_stack = stack;
 8978    }
 8979
 8980    pub fn select_smaller_syntax_node(
 8981        &mut self,
 8982        _: &SelectSmallerSyntaxNode,
 8983        cx: &mut ViewContext<Self>,
 8984    ) {
 8985        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8986        if let Some(selections) = stack.pop() {
 8987            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8988                s.select(selections.to_vec());
 8989            });
 8990        }
 8991        self.select_larger_syntax_node_stack = stack;
 8992    }
 8993
 8994    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8995        if !EditorSettings::get_global(cx).gutter.runnables {
 8996            self.clear_tasks();
 8997            return Task::ready(());
 8998        }
 8999        let project = self.project.clone();
 9000        cx.spawn(|this, mut cx| async move {
 9001            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9002                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9003            }) else {
 9004                return;
 9005            };
 9006
 9007            let Some(project) = project else {
 9008                return;
 9009            };
 9010
 9011            let hide_runnables = project
 9012                .update(&mut cx, |project, cx| {
 9013                    // Do not display any test indicators in non-dev server remote projects.
 9014                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9015                })
 9016                .unwrap_or(true);
 9017            if hide_runnables {
 9018                return;
 9019            }
 9020            let new_rows =
 9021                cx.background_executor()
 9022                    .spawn({
 9023                        let snapshot = display_snapshot.clone();
 9024                        async move {
 9025                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9026                        }
 9027                    })
 9028                    .await;
 9029            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9030
 9031            this.update(&mut cx, |this, _| {
 9032                this.clear_tasks();
 9033                for (key, value) in rows {
 9034                    this.insert_tasks(key, value);
 9035                }
 9036            })
 9037            .ok();
 9038        })
 9039    }
 9040    fn fetch_runnable_ranges(
 9041        snapshot: &DisplaySnapshot,
 9042        range: Range<Anchor>,
 9043    ) -> Vec<language::RunnableRange> {
 9044        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9045    }
 9046
 9047    fn runnable_rows(
 9048        project: Model<Project>,
 9049        snapshot: DisplaySnapshot,
 9050        runnable_ranges: Vec<RunnableRange>,
 9051        mut cx: AsyncWindowContext,
 9052    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9053        runnable_ranges
 9054            .into_iter()
 9055            .filter_map(|mut runnable| {
 9056                let tasks = cx
 9057                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9058                    .ok()?;
 9059                if tasks.is_empty() {
 9060                    return None;
 9061                }
 9062
 9063                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9064
 9065                let row = snapshot
 9066                    .buffer_snapshot
 9067                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9068                    .1
 9069                    .start
 9070                    .row;
 9071
 9072                let context_range =
 9073                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9074                Some((
 9075                    (runnable.buffer_id, row),
 9076                    RunnableTasks {
 9077                        templates: tasks,
 9078                        offset: MultiBufferOffset(runnable.run_range.start),
 9079                        context_range,
 9080                        column: point.column,
 9081                        extra_variables: runnable.extra_captures,
 9082                    },
 9083                ))
 9084            })
 9085            .collect()
 9086    }
 9087
 9088    fn templates_with_tags(
 9089        project: &Model<Project>,
 9090        runnable: &mut Runnable,
 9091        cx: &WindowContext<'_>,
 9092    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9093        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9094            let (worktree_id, file) = project
 9095                .buffer_for_id(runnable.buffer, cx)
 9096                .and_then(|buffer| buffer.read(cx).file())
 9097                .map(|file| (file.worktree_id(cx), file.clone()))
 9098                .unzip();
 9099
 9100            (project.task_inventory().clone(), worktree_id, file)
 9101        });
 9102
 9103        let inventory = inventory.read(cx);
 9104        let tags = mem::take(&mut runnable.tags);
 9105        let mut tags: Vec<_> = tags
 9106            .into_iter()
 9107            .flat_map(|tag| {
 9108                let tag = tag.0.clone();
 9109                inventory
 9110                    .list_tasks(
 9111                        file.clone(),
 9112                        Some(runnable.language.clone()),
 9113                        worktree_id,
 9114                        cx,
 9115                    )
 9116                    .into_iter()
 9117                    .filter(move |(_, template)| {
 9118                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9119                    })
 9120            })
 9121            .sorted_by_key(|(kind, _)| kind.to_owned())
 9122            .collect();
 9123        if let Some((leading_tag_source, _)) = tags.first() {
 9124            // Strongest source wins; if we have worktree tag binding, prefer that to
 9125            // global and language bindings;
 9126            // if we have a global binding, prefer that to language binding.
 9127            let first_mismatch = tags
 9128                .iter()
 9129                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9130            if let Some(index) = first_mismatch {
 9131                tags.truncate(index);
 9132            }
 9133        }
 9134
 9135        tags
 9136    }
 9137
 9138    pub fn move_to_enclosing_bracket(
 9139        &mut self,
 9140        _: &MoveToEnclosingBracket,
 9141        cx: &mut ViewContext<Self>,
 9142    ) {
 9143        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9144            s.move_offsets_with(|snapshot, selection| {
 9145                let Some(enclosing_bracket_ranges) =
 9146                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9147                else {
 9148                    return;
 9149                };
 9150
 9151                let mut best_length = usize::MAX;
 9152                let mut best_inside = false;
 9153                let mut best_in_bracket_range = false;
 9154                let mut best_destination = None;
 9155                for (open, close) in enclosing_bracket_ranges {
 9156                    let close = close.to_inclusive();
 9157                    let length = close.end() - open.start;
 9158                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9159                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9160                        || close.contains(&selection.head());
 9161
 9162                    // If best is next to a bracket and current isn't, skip
 9163                    if !in_bracket_range && best_in_bracket_range {
 9164                        continue;
 9165                    }
 9166
 9167                    // Prefer smaller lengths unless best is inside and current isn't
 9168                    if length > best_length && (best_inside || !inside) {
 9169                        continue;
 9170                    }
 9171
 9172                    best_length = length;
 9173                    best_inside = inside;
 9174                    best_in_bracket_range = in_bracket_range;
 9175                    best_destination = Some(
 9176                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9177                            if inside {
 9178                                open.end
 9179                            } else {
 9180                                open.start
 9181                            }
 9182                        } else if inside {
 9183                            *close.start()
 9184                        } else {
 9185                            *close.end()
 9186                        },
 9187                    );
 9188                }
 9189
 9190                if let Some(destination) = best_destination {
 9191                    selection.collapse_to(destination, SelectionGoal::None);
 9192                }
 9193            })
 9194        });
 9195    }
 9196
 9197    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9198        self.end_selection(cx);
 9199        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9200        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9201            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9202            self.select_next_state = entry.select_next_state;
 9203            self.select_prev_state = entry.select_prev_state;
 9204            self.add_selections_state = entry.add_selections_state;
 9205            self.request_autoscroll(Autoscroll::newest(), cx);
 9206        }
 9207        self.selection_history.mode = SelectionHistoryMode::Normal;
 9208    }
 9209
 9210    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9211        self.end_selection(cx);
 9212        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9213        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9214            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9215            self.select_next_state = entry.select_next_state;
 9216            self.select_prev_state = entry.select_prev_state;
 9217            self.add_selections_state = entry.add_selections_state;
 9218            self.request_autoscroll(Autoscroll::newest(), cx);
 9219        }
 9220        self.selection_history.mode = SelectionHistoryMode::Normal;
 9221    }
 9222
 9223    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9224        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9225    }
 9226
 9227    pub fn expand_excerpts_down(
 9228        &mut self,
 9229        action: &ExpandExcerptsDown,
 9230        cx: &mut ViewContext<Self>,
 9231    ) {
 9232        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9233    }
 9234
 9235    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9236        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9237    }
 9238
 9239    pub fn expand_excerpts_for_direction(
 9240        &mut self,
 9241        lines: u32,
 9242        direction: ExpandExcerptDirection,
 9243        cx: &mut ViewContext<Self>,
 9244    ) {
 9245        let selections = self.selections.disjoint_anchors();
 9246
 9247        let lines = if lines == 0 {
 9248            EditorSettings::get_global(cx).expand_excerpt_lines
 9249        } else {
 9250            lines
 9251        };
 9252
 9253        self.buffer.update(cx, |buffer, cx| {
 9254            buffer.expand_excerpts(
 9255                selections
 9256                    .iter()
 9257                    .map(|selection| selection.head().excerpt_id)
 9258                    .dedup(),
 9259                lines,
 9260                direction,
 9261                cx,
 9262            )
 9263        })
 9264    }
 9265
 9266    pub fn expand_excerpt(
 9267        &mut self,
 9268        excerpt: ExcerptId,
 9269        direction: ExpandExcerptDirection,
 9270        cx: &mut ViewContext<Self>,
 9271    ) {
 9272        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9273        self.buffer.update(cx, |buffer, cx| {
 9274            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9275        })
 9276    }
 9277
 9278    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9279        self.go_to_diagnostic_impl(Direction::Next, cx)
 9280    }
 9281
 9282    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9283        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9284    }
 9285
 9286    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9287        let buffer = self.buffer.read(cx).snapshot(cx);
 9288        let selection = self.selections.newest::<usize>(cx);
 9289
 9290        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9291        if direction == Direction::Next {
 9292            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9293                let (group_id, jump_to) = popover.activation_info();
 9294                if self.activate_diagnostics(group_id, cx) {
 9295                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9296                        let mut new_selection = s.newest_anchor().clone();
 9297                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9298                        s.select_anchors(vec![new_selection.clone()]);
 9299                    });
 9300                }
 9301                return;
 9302            }
 9303        }
 9304
 9305        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9306            active_diagnostics
 9307                .primary_range
 9308                .to_offset(&buffer)
 9309                .to_inclusive()
 9310        });
 9311        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9312            if active_primary_range.contains(&selection.head()) {
 9313                *active_primary_range.start()
 9314            } else {
 9315                selection.head()
 9316            }
 9317        } else {
 9318            selection.head()
 9319        };
 9320        let snapshot = self.snapshot(cx);
 9321        loop {
 9322            let diagnostics = if direction == Direction::Prev {
 9323                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9324            } else {
 9325                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9326            }
 9327            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9328            let group = diagnostics
 9329                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9330                // be sorted in a stable way
 9331                // skip until we are at current active diagnostic, if it exists
 9332                .skip_while(|entry| {
 9333                    (match direction {
 9334                        Direction::Prev => entry.range.start >= search_start,
 9335                        Direction::Next => entry.range.start <= search_start,
 9336                    }) && self
 9337                        .active_diagnostics
 9338                        .as_ref()
 9339                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9340                })
 9341                .find_map(|entry| {
 9342                    if entry.diagnostic.is_primary
 9343                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9344                        && !entry.range.is_empty()
 9345                        // if we match with the active diagnostic, skip it
 9346                        && Some(entry.diagnostic.group_id)
 9347                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9348                    {
 9349                        Some((entry.range, entry.diagnostic.group_id))
 9350                    } else {
 9351                        None
 9352                    }
 9353                });
 9354
 9355            if let Some((primary_range, group_id)) = group {
 9356                if self.activate_diagnostics(group_id, cx) {
 9357                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9358                        s.select(vec![Selection {
 9359                            id: selection.id,
 9360                            start: primary_range.start,
 9361                            end: primary_range.start,
 9362                            reversed: false,
 9363                            goal: SelectionGoal::None,
 9364                        }]);
 9365                    });
 9366                }
 9367                break;
 9368            } else {
 9369                // Cycle around to the start of the buffer, potentially moving back to the start of
 9370                // the currently active diagnostic.
 9371                active_primary_range.take();
 9372                if direction == Direction::Prev {
 9373                    if search_start == buffer.len() {
 9374                        break;
 9375                    } else {
 9376                        search_start = buffer.len();
 9377                    }
 9378                } else if search_start == 0 {
 9379                    break;
 9380                } else {
 9381                    search_start = 0;
 9382                }
 9383            }
 9384        }
 9385    }
 9386
 9387    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9388        let snapshot = self
 9389            .display_map
 9390            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9391        let selection = self.selections.newest::<Point>(cx);
 9392        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9393    }
 9394
 9395    fn go_to_hunk_after_position(
 9396        &mut self,
 9397        snapshot: &DisplaySnapshot,
 9398        position: Point,
 9399        cx: &mut ViewContext<'_, Editor>,
 9400    ) -> Option<MultiBufferDiffHunk> {
 9401        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9402            snapshot,
 9403            position,
 9404            false,
 9405            snapshot
 9406                .buffer_snapshot
 9407                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9408            cx,
 9409        ) {
 9410            return Some(hunk);
 9411        }
 9412
 9413        let wrapped_point = Point::zero();
 9414        self.go_to_next_hunk_in_direction(
 9415            snapshot,
 9416            wrapped_point,
 9417            true,
 9418            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9419                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9420            ),
 9421            cx,
 9422        )
 9423    }
 9424
 9425    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9426        let snapshot = self
 9427            .display_map
 9428            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9429        let selection = self.selections.newest::<Point>(cx);
 9430
 9431        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9432    }
 9433
 9434    fn go_to_hunk_before_position(
 9435        &mut self,
 9436        snapshot: &DisplaySnapshot,
 9437        position: Point,
 9438        cx: &mut ViewContext<'_, Editor>,
 9439    ) -> Option<MultiBufferDiffHunk> {
 9440        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9441            snapshot,
 9442            position,
 9443            false,
 9444            snapshot
 9445                .buffer_snapshot
 9446                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9447            cx,
 9448        ) {
 9449            return Some(hunk);
 9450        }
 9451
 9452        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9453        self.go_to_next_hunk_in_direction(
 9454            snapshot,
 9455            wrapped_point,
 9456            true,
 9457            snapshot
 9458                .buffer_snapshot
 9459                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9460            cx,
 9461        )
 9462    }
 9463
 9464    fn go_to_next_hunk_in_direction(
 9465        &mut self,
 9466        snapshot: &DisplaySnapshot,
 9467        initial_point: Point,
 9468        is_wrapped: bool,
 9469        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9470        cx: &mut ViewContext<Editor>,
 9471    ) -> Option<MultiBufferDiffHunk> {
 9472        let display_point = initial_point.to_display_point(snapshot);
 9473        let mut hunks = hunks
 9474            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9475            .filter(|(display_hunk, _)| {
 9476                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9477            })
 9478            .dedup();
 9479
 9480        if let Some((display_hunk, hunk)) = hunks.next() {
 9481            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9482                let row = display_hunk.start_display_row();
 9483                let point = DisplayPoint::new(row, 0);
 9484                s.select_display_ranges([point..point]);
 9485            });
 9486
 9487            Some(hunk)
 9488        } else {
 9489            None
 9490        }
 9491    }
 9492
 9493    pub fn go_to_definition(
 9494        &mut self,
 9495        _: &GoToDefinition,
 9496        cx: &mut ViewContext<Self>,
 9497    ) -> Task<Result<Navigated>> {
 9498        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9499        cx.spawn(|editor, mut cx| async move {
 9500            if definition.await? == Navigated::Yes {
 9501                return Ok(Navigated::Yes);
 9502            }
 9503            match editor.update(&mut cx, |editor, cx| {
 9504                editor.find_all_references(&FindAllReferences, cx)
 9505            })? {
 9506                Some(references) => references.await,
 9507                None => Ok(Navigated::No),
 9508            }
 9509        })
 9510    }
 9511
 9512    pub fn go_to_declaration(
 9513        &mut self,
 9514        _: &GoToDeclaration,
 9515        cx: &mut ViewContext<Self>,
 9516    ) -> Task<Result<Navigated>> {
 9517        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9518    }
 9519
 9520    pub fn go_to_declaration_split(
 9521        &mut self,
 9522        _: &GoToDeclaration,
 9523        cx: &mut ViewContext<Self>,
 9524    ) -> Task<Result<Navigated>> {
 9525        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9526    }
 9527
 9528    pub fn go_to_implementation(
 9529        &mut self,
 9530        _: &GoToImplementation,
 9531        cx: &mut ViewContext<Self>,
 9532    ) -> Task<Result<Navigated>> {
 9533        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9534    }
 9535
 9536    pub fn go_to_implementation_split(
 9537        &mut self,
 9538        _: &GoToImplementationSplit,
 9539        cx: &mut ViewContext<Self>,
 9540    ) -> Task<Result<Navigated>> {
 9541        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9542    }
 9543
 9544    pub fn go_to_type_definition(
 9545        &mut self,
 9546        _: &GoToTypeDefinition,
 9547        cx: &mut ViewContext<Self>,
 9548    ) -> Task<Result<Navigated>> {
 9549        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9550    }
 9551
 9552    pub fn go_to_definition_split(
 9553        &mut self,
 9554        _: &GoToDefinitionSplit,
 9555        cx: &mut ViewContext<Self>,
 9556    ) -> Task<Result<Navigated>> {
 9557        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9558    }
 9559
 9560    pub fn go_to_type_definition_split(
 9561        &mut self,
 9562        _: &GoToTypeDefinitionSplit,
 9563        cx: &mut ViewContext<Self>,
 9564    ) -> Task<Result<Navigated>> {
 9565        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9566    }
 9567
 9568    fn go_to_definition_of_kind(
 9569        &mut self,
 9570        kind: GotoDefinitionKind,
 9571        split: bool,
 9572        cx: &mut ViewContext<Self>,
 9573    ) -> Task<Result<Navigated>> {
 9574        let Some(workspace) = self.workspace() else {
 9575            return Task::ready(Ok(Navigated::No));
 9576        };
 9577        let buffer = self.buffer.read(cx);
 9578        let head = self.selections.newest::<usize>(cx).head();
 9579        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9580            text_anchor
 9581        } else {
 9582            return Task::ready(Ok(Navigated::No));
 9583        };
 9584
 9585        let project = workspace.read(cx).project().clone();
 9586        let definitions = project.update(cx, |project, cx| match kind {
 9587            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 9588            GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
 9589            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 9590            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 9591        });
 9592
 9593        cx.spawn(|editor, mut cx| async move {
 9594            let definitions = definitions.await?;
 9595            let navigated = editor
 9596                .update(&mut cx, |editor, cx| {
 9597                    editor.navigate_to_hover_links(
 9598                        Some(kind),
 9599                        definitions
 9600                            .into_iter()
 9601                            .filter(|location| {
 9602                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9603                            })
 9604                            .map(HoverLink::Text)
 9605                            .collect::<Vec<_>>(),
 9606                        split,
 9607                        cx,
 9608                    )
 9609                })?
 9610                .await?;
 9611            anyhow::Ok(navigated)
 9612        })
 9613    }
 9614
 9615    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9616        let position = self.selections.newest_anchor().head();
 9617        let Some((buffer, buffer_position)) =
 9618            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9619        else {
 9620            return;
 9621        };
 9622
 9623        cx.spawn(|editor, mut cx| async move {
 9624            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9625                editor.update(&mut cx, |_, cx| {
 9626                    cx.open_url(&url);
 9627                })
 9628            } else {
 9629                Ok(())
 9630            }
 9631        })
 9632        .detach();
 9633    }
 9634
 9635    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9636        let Some(workspace) = self.workspace() else {
 9637            return;
 9638        };
 9639
 9640        let position = self.selections.newest_anchor().head();
 9641
 9642        let Some((buffer, buffer_position)) =
 9643            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9644        else {
 9645            return;
 9646        };
 9647
 9648        let Some(project) = self.project.clone() else {
 9649            return;
 9650        };
 9651
 9652        cx.spawn(|_, mut cx| async move {
 9653            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9654
 9655            if let Some((_, path)) = result {
 9656                workspace
 9657                    .update(&mut cx, |workspace, cx| {
 9658                        workspace.open_resolved_path(path, cx)
 9659                    })?
 9660                    .await?;
 9661            }
 9662            anyhow::Ok(())
 9663        })
 9664        .detach();
 9665    }
 9666
 9667    pub(crate) fn navigate_to_hover_links(
 9668        &mut self,
 9669        kind: Option<GotoDefinitionKind>,
 9670        mut definitions: Vec<HoverLink>,
 9671        split: bool,
 9672        cx: &mut ViewContext<Editor>,
 9673    ) -> Task<Result<Navigated>> {
 9674        // If there is one definition, just open it directly
 9675        if definitions.len() == 1 {
 9676            let definition = definitions.pop().unwrap();
 9677
 9678            enum TargetTaskResult {
 9679                Location(Option<Location>),
 9680                AlreadyNavigated,
 9681            }
 9682
 9683            let target_task = match definition {
 9684                HoverLink::Text(link) => {
 9685                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9686                }
 9687                HoverLink::InlayHint(lsp_location, server_id) => {
 9688                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9689                    cx.background_executor().spawn(async move {
 9690                        let location = computation.await?;
 9691                        Ok(TargetTaskResult::Location(location))
 9692                    })
 9693                }
 9694                HoverLink::Url(url) => {
 9695                    cx.open_url(&url);
 9696                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9697                }
 9698                HoverLink::File(path) => {
 9699                    if let Some(workspace) = self.workspace() {
 9700                        cx.spawn(|_, mut cx| async move {
 9701                            workspace
 9702                                .update(&mut cx, |workspace, cx| {
 9703                                    workspace.open_resolved_path(path, cx)
 9704                                })?
 9705                                .await
 9706                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9707                        })
 9708                    } else {
 9709                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9710                    }
 9711                }
 9712            };
 9713            cx.spawn(|editor, mut cx| async move {
 9714                let target = match target_task.await.context("target resolution task")? {
 9715                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9716                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9717                    TargetTaskResult::Location(Some(target)) => target,
 9718                };
 9719
 9720                editor.update(&mut cx, |editor, cx| {
 9721                    let Some(workspace) = editor.workspace() else {
 9722                        return Navigated::No;
 9723                    };
 9724                    let pane = workspace.read(cx).active_pane().clone();
 9725
 9726                    let range = target.range.to_offset(target.buffer.read(cx));
 9727                    let range = editor.range_for_match(&range);
 9728
 9729                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9730                        let buffer = target.buffer.read(cx);
 9731                        let range = check_multiline_range(buffer, range);
 9732                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9733                            s.select_ranges([range]);
 9734                        });
 9735                    } else {
 9736                        cx.window_context().defer(move |cx| {
 9737                            let target_editor: View<Self> =
 9738                                workspace.update(cx, |workspace, cx| {
 9739                                    let pane = if split {
 9740                                        workspace.adjacent_pane(cx)
 9741                                    } else {
 9742                                        workspace.active_pane().clone()
 9743                                    };
 9744
 9745                                    workspace.open_project_item(
 9746                                        pane,
 9747                                        target.buffer.clone(),
 9748                                        true,
 9749                                        true,
 9750                                        cx,
 9751                                    )
 9752                                });
 9753                            target_editor.update(cx, |target_editor, cx| {
 9754                                // When selecting a definition in a different buffer, disable the nav history
 9755                                // to avoid creating a history entry at the previous cursor location.
 9756                                pane.update(cx, |pane, _| pane.disable_history());
 9757                                let buffer = target.buffer.read(cx);
 9758                                let range = check_multiline_range(buffer, range);
 9759                                target_editor.change_selections(
 9760                                    Some(Autoscroll::focused()),
 9761                                    cx,
 9762                                    |s| {
 9763                                        s.select_ranges([range]);
 9764                                    },
 9765                                );
 9766                                pane.update(cx, |pane, _| pane.enable_history());
 9767                            });
 9768                        });
 9769                    }
 9770                    Navigated::Yes
 9771                })
 9772            })
 9773        } else if !definitions.is_empty() {
 9774            cx.spawn(|editor, mut cx| async move {
 9775                let (title, location_tasks, workspace) = editor
 9776                    .update(&mut cx, |editor, cx| {
 9777                        let tab_kind = match kind {
 9778                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9779                            _ => "Definitions",
 9780                        };
 9781                        let title = definitions
 9782                            .iter()
 9783                            .find_map(|definition| match definition {
 9784                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9785                                    let buffer = origin.buffer.read(cx);
 9786                                    format!(
 9787                                        "{} for {}",
 9788                                        tab_kind,
 9789                                        buffer
 9790                                            .text_for_range(origin.range.clone())
 9791                                            .collect::<String>()
 9792                                    )
 9793                                }),
 9794                                HoverLink::InlayHint(_, _) => None,
 9795                                HoverLink::Url(_) => None,
 9796                                HoverLink::File(_) => None,
 9797                            })
 9798                            .unwrap_or(tab_kind.to_string());
 9799                        let location_tasks = definitions
 9800                            .into_iter()
 9801                            .map(|definition| match definition {
 9802                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9803                                HoverLink::InlayHint(lsp_location, server_id) => {
 9804                                    editor.compute_target_location(lsp_location, server_id, cx)
 9805                                }
 9806                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9807                                HoverLink::File(_) => Task::ready(Ok(None)),
 9808                            })
 9809                            .collect::<Vec<_>>();
 9810                        (title, location_tasks, editor.workspace().clone())
 9811                    })
 9812                    .context("location tasks preparation")?;
 9813
 9814                let locations = future::join_all(location_tasks)
 9815                    .await
 9816                    .into_iter()
 9817                    .filter_map(|location| location.transpose())
 9818                    .collect::<Result<_>>()
 9819                    .context("location tasks")?;
 9820
 9821                let Some(workspace) = workspace else {
 9822                    return Ok(Navigated::No);
 9823                };
 9824                let opened = workspace
 9825                    .update(&mut cx, |workspace, cx| {
 9826                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9827                    })
 9828                    .ok();
 9829
 9830                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9831            })
 9832        } else {
 9833            Task::ready(Ok(Navigated::No))
 9834        }
 9835    }
 9836
 9837    fn compute_target_location(
 9838        &self,
 9839        lsp_location: lsp::Location,
 9840        server_id: LanguageServerId,
 9841        cx: &mut ViewContext<Editor>,
 9842    ) -> Task<anyhow::Result<Option<Location>>> {
 9843        let Some(project) = self.project.clone() else {
 9844            return Task::Ready(Some(Ok(None)));
 9845        };
 9846
 9847        cx.spawn(move |editor, mut cx| async move {
 9848            let location_task = editor.update(&mut cx, |editor, cx| {
 9849                project.update(cx, |project, cx| {
 9850                    let language_server_name =
 9851                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9852                            project
 9853                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9854                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9855                        });
 9856                    language_server_name.map(|language_server_name| {
 9857                        project.open_local_buffer_via_lsp(
 9858                            lsp_location.uri.clone(),
 9859                            server_id,
 9860                            language_server_name,
 9861                            cx,
 9862                        )
 9863                    })
 9864                })
 9865            })?;
 9866            let location = match location_task {
 9867                Some(task) => Some({
 9868                    let target_buffer_handle = task.await.context("open local buffer")?;
 9869                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9870                        let target_start = target_buffer
 9871                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9872                        let target_end = target_buffer
 9873                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9874                        target_buffer.anchor_after(target_start)
 9875                            ..target_buffer.anchor_before(target_end)
 9876                    })?;
 9877                    Location {
 9878                        buffer: target_buffer_handle,
 9879                        range,
 9880                    }
 9881                }),
 9882                None => None,
 9883            };
 9884            Ok(location)
 9885        })
 9886    }
 9887
 9888    pub fn find_all_references(
 9889        &mut self,
 9890        _: &FindAllReferences,
 9891        cx: &mut ViewContext<Self>,
 9892    ) -> Option<Task<Result<Navigated>>> {
 9893        let multi_buffer = self.buffer.read(cx);
 9894        let selection = self.selections.newest::<usize>(cx);
 9895        let head = selection.head();
 9896
 9897        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9898        let head_anchor = multi_buffer_snapshot.anchor_at(
 9899            head,
 9900            if head < selection.tail() {
 9901                Bias::Right
 9902            } else {
 9903                Bias::Left
 9904            },
 9905        );
 9906
 9907        match self
 9908            .find_all_references_task_sources
 9909            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9910        {
 9911            Ok(_) => {
 9912                log::info!(
 9913                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9914                );
 9915                return None;
 9916            }
 9917            Err(i) => {
 9918                self.find_all_references_task_sources.insert(i, head_anchor);
 9919            }
 9920        }
 9921
 9922        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9923        let workspace = self.workspace()?;
 9924        let project = workspace.read(cx).project().clone();
 9925        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9926        Some(cx.spawn(|editor, mut cx| async move {
 9927            let _cleanup = defer({
 9928                let mut cx = cx.clone();
 9929                move || {
 9930                    let _ = editor.update(&mut cx, |editor, _| {
 9931                        if let Ok(i) =
 9932                            editor
 9933                                .find_all_references_task_sources
 9934                                .binary_search_by(|anchor| {
 9935                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9936                                })
 9937                        {
 9938                            editor.find_all_references_task_sources.remove(i);
 9939                        }
 9940                    });
 9941                }
 9942            });
 9943
 9944            let locations = references.await?;
 9945            if locations.is_empty() {
 9946                return anyhow::Ok(Navigated::No);
 9947            }
 9948
 9949            workspace.update(&mut cx, |workspace, cx| {
 9950                let title = locations
 9951                    .first()
 9952                    .as_ref()
 9953                    .map(|location| {
 9954                        let buffer = location.buffer.read(cx);
 9955                        format!(
 9956                            "References to `{}`",
 9957                            buffer
 9958                                .text_for_range(location.range.clone())
 9959                                .collect::<String>()
 9960                        )
 9961                    })
 9962                    .unwrap();
 9963                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9964                Navigated::Yes
 9965            })
 9966        }))
 9967    }
 9968
 9969    /// Opens a multibuffer with the given project locations in it
 9970    pub fn open_locations_in_multibuffer(
 9971        workspace: &mut Workspace,
 9972        mut locations: Vec<Location>,
 9973        title: String,
 9974        split: bool,
 9975        cx: &mut ViewContext<Workspace>,
 9976    ) {
 9977        // If there are multiple definitions, open them in a multibuffer
 9978        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9979        let mut locations = locations.into_iter().peekable();
 9980        let mut ranges_to_highlight = Vec::new();
 9981        let capability = workspace.project().read(cx).capability();
 9982
 9983        let excerpt_buffer = cx.new_model(|cx| {
 9984            let mut multibuffer = MultiBuffer::new(capability);
 9985            while let Some(location) = locations.next() {
 9986                let buffer = location.buffer.read(cx);
 9987                let mut ranges_for_buffer = Vec::new();
 9988                let range = location.range.to_offset(buffer);
 9989                ranges_for_buffer.push(range.clone());
 9990
 9991                while let Some(next_location) = locations.peek() {
 9992                    if next_location.buffer == location.buffer {
 9993                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9994                        locations.next();
 9995                    } else {
 9996                        break;
 9997                    }
 9998                }
 9999
10000                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10001                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10002                    location.buffer.clone(),
10003                    ranges_for_buffer,
10004                    DEFAULT_MULTIBUFFER_CONTEXT,
10005                    cx,
10006                ))
10007            }
10008
10009            multibuffer.with_title(title)
10010        });
10011
10012        let editor = cx.new_view(|cx| {
10013            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10014        });
10015        editor.update(cx, |editor, cx| {
10016            if let Some(first_range) = ranges_to_highlight.first() {
10017                editor.change_selections(None, cx, |selections| {
10018                    selections.clear_disjoint();
10019                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10020                });
10021            }
10022            editor.highlight_background::<Self>(
10023                &ranges_to_highlight,
10024                |theme| theme.editor_highlighted_line_background,
10025                cx,
10026            );
10027        });
10028
10029        let item = Box::new(editor);
10030        let item_id = item.item_id();
10031
10032        if split {
10033            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10034        } else {
10035            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10036                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10037                    pane.close_current_preview_item(cx)
10038                } else {
10039                    None
10040                }
10041            });
10042            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10043        }
10044        workspace.active_pane().update(cx, |pane, cx| {
10045            pane.set_preview_item_id(Some(item_id), cx);
10046        });
10047    }
10048
10049    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10050        use language::ToOffset as _;
10051
10052        let project = self.project.clone()?;
10053        let selection = self.selections.newest_anchor().clone();
10054        let (cursor_buffer, cursor_buffer_position) = self
10055            .buffer
10056            .read(cx)
10057            .text_anchor_for_position(selection.head(), cx)?;
10058        let (tail_buffer, cursor_buffer_position_end) = self
10059            .buffer
10060            .read(cx)
10061            .text_anchor_for_position(selection.tail(), cx)?;
10062        if tail_buffer != cursor_buffer {
10063            return None;
10064        }
10065
10066        let snapshot = cursor_buffer.read(cx).snapshot();
10067        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10068        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10069        let prepare_rename = project.update(cx, |project, cx| {
10070            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10071        });
10072        drop(snapshot);
10073
10074        Some(cx.spawn(|this, mut cx| async move {
10075            let rename_range = if let Some(range) = prepare_rename.await? {
10076                Some(range)
10077            } else {
10078                this.update(&mut cx, |this, cx| {
10079                    let buffer = this.buffer.read(cx).snapshot(cx);
10080                    let mut buffer_highlights = this
10081                        .document_highlights_for_position(selection.head(), &buffer)
10082                        .filter(|highlight| {
10083                            highlight.start.excerpt_id == selection.head().excerpt_id
10084                                && highlight.end.excerpt_id == selection.head().excerpt_id
10085                        });
10086                    buffer_highlights
10087                        .next()
10088                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10089                })?
10090            };
10091            if let Some(rename_range) = rename_range {
10092                this.update(&mut cx, |this, cx| {
10093                    let snapshot = cursor_buffer.read(cx).snapshot();
10094                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10095                    let cursor_offset_in_rename_range =
10096                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10097                    let cursor_offset_in_rename_range_end =
10098                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10099
10100                    this.take_rename(false, cx);
10101                    let buffer = this.buffer.read(cx).read(cx);
10102                    let cursor_offset = selection.head().to_offset(&buffer);
10103                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10104                    let rename_end = rename_start + rename_buffer_range.len();
10105                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10106                    let mut old_highlight_id = None;
10107                    let old_name: Arc<str> = buffer
10108                        .chunks(rename_start..rename_end, true)
10109                        .map(|chunk| {
10110                            if old_highlight_id.is_none() {
10111                                old_highlight_id = chunk.syntax_highlight_id;
10112                            }
10113                            chunk.text
10114                        })
10115                        .collect::<String>()
10116                        .into();
10117
10118                    drop(buffer);
10119
10120                    // Position the selection in the rename editor so that it matches the current selection.
10121                    this.show_local_selections = false;
10122                    let rename_editor = cx.new_view(|cx| {
10123                        let mut editor = Editor::single_line(cx);
10124                        editor.buffer.update(cx, |buffer, cx| {
10125                            buffer.edit([(0..0, old_name.clone())], None, cx)
10126                        });
10127                        let rename_selection_range = match cursor_offset_in_rename_range
10128                            .cmp(&cursor_offset_in_rename_range_end)
10129                        {
10130                            Ordering::Equal => {
10131                                editor.select_all(&SelectAll, cx);
10132                                return editor;
10133                            }
10134                            Ordering::Less => {
10135                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10136                            }
10137                            Ordering::Greater => {
10138                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10139                            }
10140                        };
10141                        if rename_selection_range.end > old_name.len() {
10142                            editor.select_all(&SelectAll, cx);
10143                        } else {
10144                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10145                                s.select_ranges([rename_selection_range]);
10146                            });
10147                        }
10148                        editor
10149                    });
10150                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10151                        if e == &EditorEvent::Focused {
10152                            cx.emit(EditorEvent::FocusedIn)
10153                        }
10154                    })
10155                    .detach();
10156
10157                    let write_highlights =
10158                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10159                    let read_highlights =
10160                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10161                    let ranges = write_highlights
10162                        .iter()
10163                        .flat_map(|(_, ranges)| ranges.iter())
10164                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10165                        .cloned()
10166                        .collect();
10167
10168                    this.highlight_text::<Rename>(
10169                        ranges,
10170                        HighlightStyle {
10171                            fade_out: Some(0.6),
10172                            ..Default::default()
10173                        },
10174                        cx,
10175                    );
10176                    let rename_focus_handle = rename_editor.focus_handle(cx);
10177                    cx.focus(&rename_focus_handle);
10178                    let block_id = this.insert_blocks(
10179                        [BlockProperties {
10180                            style: BlockStyle::Flex,
10181                            position: range.start,
10182                            height: 1,
10183                            render: Box::new({
10184                                let rename_editor = rename_editor.clone();
10185                                move |cx: &mut BlockContext| {
10186                                    let mut text_style = cx.editor_style.text.clone();
10187                                    if let Some(highlight_style) = old_highlight_id
10188                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10189                                    {
10190                                        text_style = text_style.highlight(highlight_style);
10191                                    }
10192                                    div()
10193                                        .pl(cx.anchor_x)
10194                                        .child(EditorElement::new(
10195                                            &rename_editor,
10196                                            EditorStyle {
10197                                                background: cx.theme().system().transparent,
10198                                                local_player: cx.editor_style.local_player,
10199                                                text: text_style,
10200                                                scrollbar_width: cx.editor_style.scrollbar_width,
10201                                                syntax: cx.editor_style.syntax.clone(),
10202                                                status: cx.editor_style.status.clone(),
10203                                                inlay_hints_style: HighlightStyle {
10204                                                    font_weight: Some(FontWeight::BOLD),
10205                                                    ..make_inlay_hints_style(cx)
10206                                                },
10207                                                suggestions_style: HighlightStyle {
10208                                                    color: Some(cx.theme().status().predictive),
10209                                                    ..HighlightStyle::default()
10210                                                },
10211                                                ..EditorStyle::default()
10212                                            },
10213                                        ))
10214                                        .into_any_element()
10215                                }
10216                            }),
10217                            disposition: BlockDisposition::Below,
10218                            priority: 0,
10219                        }],
10220                        Some(Autoscroll::fit()),
10221                        cx,
10222                    )[0];
10223                    this.pending_rename = Some(RenameState {
10224                        range,
10225                        old_name,
10226                        editor: rename_editor,
10227                        block_id,
10228                    });
10229                })?;
10230            }
10231
10232            Ok(())
10233        }))
10234    }
10235
10236    pub fn confirm_rename(
10237        &mut self,
10238        _: &ConfirmRename,
10239        cx: &mut ViewContext<Self>,
10240    ) -> Option<Task<Result<()>>> {
10241        let rename = self.take_rename(false, cx)?;
10242        let workspace = self.workspace()?;
10243        let (start_buffer, start) = self
10244            .buffer
10245            .read(cx)
10246            .text_anchor_for_position(rename.range.start, cx)?;
10247        let (end_buffer, end) = self
10248            .buffer
10249            .read(cx)
10250            .text_anchor_for_position(rename.range.end, cx)?;
10251        if start_buffer != end_buffer {
10252            return None;
10253        }
10254
10255        let buffer = start_buffer;
10256        let range = start..end;
10257        let old_name = rename.old_name;
10258        let new_name = rename.editor.read(cx).text(cx);
10259
10260        let rename = workspace
10261            .read(cx)
10262            .project()
10263            .clone()
10264            .update(cx, |project, cx| {
10265                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10266            });
10267        let workspace = workspace.downgrade();
10268
10269        Some(cx.spawn(|editor, mut cx| async move {
10270            let project_transaction = rename.await?;
10271            Self::open_project_transaction(
10272                &editor,
10273                workspace,
10274                project_transaction,
10275                format!("Rename: {}{}", old_name, new_name),
10276                cx.clone(),
10277            )
10278            .await?;
10279
10280            editor.update(&mut cx, |editor, cx| {
10281                editor.refresh_document_highlights(cx);
10282            })?;
10283            Ok(())
10284        }))
10285    }
10286
10287    fn take_rename(
10288        &mut self,
10289        moving_cursor: bool,
10290        cx: &mut ViewContext<Self>,
10291    ) -> Option<RenameState> {
10292        let rename = self.pending_rename.take()?;
10293        if rename.editor.focus_handle(cx).is_focused(cx) {
10294            cx.focus(&self.focus_handle);
10295        }
10296
10297        self.remove_blocks(
10298            [rename.block_id].into_iter().collect(),
10299            Some(Autoscroll::fit()),
10300            cx,
10301        );
10302        self.clear_highlights::<Rename>(cx);
10303        self.show_local_selections = true;
10304
10305        if moving_cursor {
10306            let rename_editor = rename.editor.read(cx);
10307            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10308
10309            // Update the selection to match the position of the selection inside
10310            // the rename editor.
10311            let snapshot = self.buffer.read(cx).read(cx);
10312            let rename_range = rename.range.to_offset(&snapshot);
10313            let cursor_in_editor = snapshot
10314                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10315                .min(rename_range.end);
10316            drop(snapshot);
10317
10318            self.change_selections(None, cx, |s| {
10319                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10320            });
10321        } else {
10322            self.refresh_document_highlights(cx);
10323        }
10324
10325        Some(rename)
10326    }
10327
10328    pub fn pending_rename(&self) -> Option<&RenameState> {
10329        self.pending_rename.as_ref()
10330    }
10331
10332    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10333        let project = match &self.project {
10334            Some(project) => project.clone(),
10335            None => return None,
10336        };
10337
10338        Some(self.perform_format(project, FormatTrigger::Manual, cx))
10339    }
10340
10341    fn perform_format(
10342        &mut self,
10343        project: Model<Project>,
10344        trigger: FormatTrigger,
10345        cx: &mut ViewContext<Self>,
10346    ) -> Task<Result<()>> {
10347        let buffer = self.buffer().clone();
10348        let mut buffers = buffer.read(cx).all_buffers();
10349        if trigger == FormatTrigger::Save {
10350            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10351        }
10352
10353        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10354        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10355
10356        cx.spawn(|_, mut cx| async move {
10357            let transaction = futures::select_biased! {
10358                () = timeout => {
10359                    log::warn!("timed out waiting for formatting");
10360                    None
10361                }
10362                transaction = format.log_err().fuse() => transaction,
10363            };
10364
10365            buffer
10366                .update(&mut cx, |buffer, cx| {
10367                    if let Some(transaction) = transaction {
10368                        if !buffer.is_singleton() {
10369                            buffer.push_transaction(&transaction.0, cx);
10370                        }
10371                    }
10372
10373                    cx.notify();
10374                })
10375                .ok();
10376
10377            Ok(())
10378        })
10379    }
10380
10381    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10382        if let Some(project) = self.project.clone() {
10383            self.buffer.update(cx, |multi_buffer, cx| {
10384                project.update(cx, |project, cx| {
10385                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10386                });
10387            })
10388        }
10389    }
10390
10391    fn cancel_language_server_work(
10392        &mut self,
10393        _: &CancelLanguageServerWork,
10394        cx: &mut ViewContext<Self>,
10395    ) {
10396        if let Some(project) = self.project.clone() {
10397            self.buffer.update(cx, |multi_buffer, cx| {
10398                project.update(cx, |project, cx| {
10399                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10400                });
10401            })
10402        }
10403    }
10404
10405    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10406        cx.show_character_palette();
10407    }
10408
10409    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10410        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10411            let buffer = self.buffer.read(cx).snapshot(cx);
10412            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10413            let is_valid = buffer
10414                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10415                .any(|entry| {
10416                    entry.diagnostic.is_primary
10417                        && !entry.range.is_empty()
10418                        && entry.range.start == primary_range_start
10419                        && entry.diagnostic.message == active_diagnostics.primary_message
10420                });
10421
10422            if is_valid != active_diagnostics.is_valid {
10423                active_diagnostics.is_valid = is_valid;
10424                let mut new_styles = HashMap::default();
10425                for (block_id, diagnostic) in &active_diagnostics.blocks {
10426                    new_styles.insert(
10427                        *block_id,
10428                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10429                    );
10430                }
10431                self.display_map.update(cx, |display_map, _cx| {
10432                    display_map.replace_blocks(new_styles)
10433                });
10434            }
10435        }
10436    }
10437
10438    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10439        self.dismiss_diagnostics(cx);
10440        let snapshot = self.snapshot(cx);
10441        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10442            let buffer = self.buffer.read(cx).snapshot(cx);
10443
10444            let mut primary_range = None;
10445            let mut primary_message = None;
10446            let mut group_end = Point::zero();
10447            let diagnostic_group = buffer
10448                .diagnostic_group::<MultiBufferPoint>(group_id)
10449                .filter_map(|entry| {
10450                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10451                        && (entry.range.start.row == entry.range.end.row
10452                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10453                    {
10454                        return None;
10455                    }
10456                    if entry.range.end > group_end {
10457                        group_end = entry.range.end;
10458                    }
10459                    if entry.diagnostic.is_primary {
10460                        primary_range = Some(entry.range.clone());
10461                        primary_message = Some(entry.diagnostic.message.clone());
10462                    }
10463                    Some(entry)
10464                })
10465                .collect::<Vec<_>>();
10466            let primary_range = primary_range?;
10467            let primary_message = primary_message?;
10468            let primary_range =
10469                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10470
10471            let blocks = display_map
10472                .insert_blocks(
10473                    diagnostic_group.iter().map(|entry| {
10474                        let diagnostic = entry.diagnostic.clone();
10475                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10476                        BlockProperties {
10477                            style: BlockStyle::Fixed,
10478                            position: buffer.anchor_after(entry.range.start),
10479                            height: message_height,
10480                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10481                            disposition: BlockDisposition::Below,
10482                            priority: 0,
10483                        }
10484                    }),
10485                    cx,
10486                )
10487                .into_iter()
10488                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10489                .collect();
10490
10491            Some(ActiveDiagnosticGroup {
10492                primary_range,
10493                primary_message,
10494                group_id,
10495                blocks,
10496                is_valid: true,
10497            })
10498        });
10499        self.active_diagnostics.is_some()
10500    }
10501
10502    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10503        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10504            self.display_map.update(cx, |display_map, cx| {
10505                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10506            });
10507            cx.notify();
10508        }
10509    }
10510
10511    pub fn set_selections_from_remote(
10512        &mut self,
10513        selections: Vec<Selection<Anchor>>,
10514        pending_selection: Option<Selection<Anchor>>,
10515        cx: &mut ViewContext<Self>,
10516    ) {
10517        let old_cursor_position = self.selections.newest_anchor().head();
10518        self.selections.change_with(cx, |s| {
10519            s.select_anchors(selections);
10520            if let Some(pending_selection) = pending_selection {
10521                s.set_pending(pending_selection, SelectMode::Character);
10522            } else {
10523                s.clear_pending();
10524            }
10525        });
10526        self.selections_did_change(false, &old_cursor_position, true, cx);
10527    }
10528
10529    fn push_to_selection_history(&mut self) {
10530        self.selection_history.push(SelectionHistoryEntry {
10531            selections: self.selections.disjoint_anchors(),
10532            select_next_state: self.select_next_state.clone(),
10533            select_prev_state: self.select_prev_state.clone(),
10534            add_selections_state: self.add_selections_state.clone(),
10535        });
10536    }
10537
10538    pub fn transact(
10539        &mut self,
10540        cx: &mut ViewContext<Self>,
10541        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10542    ) -> Option<TransactionId> {
10543        self.start_transaction_at(Instant::now(), cx);
10544        update(self, cx);
10545        self.end_transaction_at(Instant::now(), cx)
10546    }
10547
10548    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10549        self.end_selection(cx);
10550        if let Some(tx_id) = self
10551            .buffer
10552            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10553        {
10554            self.selection_history
10555                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10556            cx.emit(EditorEvent::TransactionBegun {
10557                transaction_id: tx_id,
10558            })
10559        }
10560    }
10561
10562    fn end_transaction_at(
10563        &mut self,
10564        now: Instant,
10565        cx: &mut ViewContext<Self>,
10566    ) -> Option<TransactionId> {
10567        if let Some(transaction_id) = self
10568            .buffer
10569            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10570        {
10571            if let Some((_, end_selections)) =
10572                self.selection_history.transaction_mut(transaction_id)
10573            {
10574                *end_selections = Some(self.selections.disjoint_anchors());
10575            } else {
10576                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10577            }
10578
10579            cx.emit(EditorEvent::Edited { transaction_id });
10580            Some(transaction_id)
10581        } else {
10582            None
10583        }
10584    }
10585
10586    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10587        let selection = self.selections.newest::<Point>(cx);
10588
10589        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10590        let range = if selection.is_empty() {
10591            let point = selection.head().to_display_point(&display_map);
10592            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10593            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10594                .to_point(&display_map);
10595            start..end
10596        } else {
10597            selection.range()
10598        };
10599        if display_map.folds_in_range(range).next().is_some() {
10600            self.unfold_lines(&Default::default(), cx)
10601        } else {
10602            self.fold(&Default::default(), cx)
10603        }
10604    }
10605
10606    pub fn toggle_fold_recursive(
10607        &mut self,
10608        _: &actions::ToggleFoldRecursive,
10609        cx: &mut ViewContext<Self>,
10610    ) {
10611        let selection = self.selections.newest::<Point>(cx);
10612
10613        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10614        let range = if selection.is_empty() {
10615            let point = selection.head().to_display_point(&display_map);
10616            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10617            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10618                .to_point(&display_map);
10619            start..end
10620        } else {
10621            selection.range()
10622        };
10623        if display_map.folds_in_range(range).next().is_some() {
10624            self.unfold_recursive(&Default::default(), cx)
10625        } else {
10626            self.fold_recursive(&Default::default(), cx)
10627        }
10628    }
10629
10630    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10631        let mut fold_ranges = Vec::new();
10632        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10633        let selections = self.selections.all_adjusted(cx);
10634
10635        for selection in selections {
10636            let range = selection.range().sorted();
10637            let buffer_start_row = range.start.row;
10638
10639            if range.start.row != range.end.row {
10640                let mut found = false;
10641                let mut row = range.start.row;
10642                while row <= range.end.row {
10643                    if let Some((foldable_range, fold_text)) =
10644                        { display_map.foldable_range(MultiBufferRow(row)) }
10645                    {
10646                        found = true;
10647                        row = foldable_range.end.row + 1;
10648                        fold_ranges.push((foldable_range, fold_text));
10649                    } else {
10650                        row += 1
10651                    }
10652                }
10653                if found {
10654                    continue;
10655                }
10656            }
10657
10658            for row in (0..=range.start.row).rev() {
10659                if let Some((foldable_range, fold_text)) =
10660                    display_map.foldable_range(MultiBufferRow(row))
10661                {
10662                    if foldable_range.end.row >= buffer_start_row {
10663                        fold_ranges.push((foldable_range, fold_text));
10664                        if row <= range.start.row {
10665                            break;
10666                        }
10667                    }
10668                }
10669            }
10670        }
10671
10672        self.fold_ranges(fold_ranges, true, cx);
10673    }
10674
10675    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10676        let mut fold_ranges = Vec::new();
10677        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10678
10679        for row in 0..display_map.max_buffer_row().0 {
10680            if let Some((foldable_range, fold_text)) =
10681                display_map.foldable_range(MultiBufferRow(row))
10682            {
10683                fold_ranges.push((foldable_range, fold_text));
10684            }
10685        }
10686
10687        self.fold_ranges(fold_ranges, true, cx);
10688    }
10689
10690    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10691        let mut fold_ranges = Vec::new();
10692        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10693        let selections = self.selections.all_adjusted(cx);
10694
10695        for selection in selections {
10696            let range = selection.range().sorted();
10697            let buffer_start_row = range.start.row;
10698
10699            if range.start.row != range.end.row {
10700                let mut found = false;
10701                for row in range.start.row..=range.end.row {
10702                    if let Some((foldable_range, fold_text)) =
10703                        { display_map.foldable_range(MultiBufferRow(row)) }
10704                    {
10705                        found = true;
10706                        fold_ranges.push((foldable_range, fold_text));
10707                    }
10708                }
10709                if found {
10710                    continue;
10711                }
10712            }
10713
10714            for row in (0..=range.start.row).rev() {
10715                if let Some((foldable_range, fold_text)) =
10716                    display_map.foldable_range(MultiBufferRow(row))
10717                {
10718                    if foldable_range.end.row >= buffer_start_row {
10719                        fold_ranges.push((foldable_range, fold_text));
10720                    } else {
10721                        break;
10722                    }
10723                }
10724            }
10725        }
10726
10727        self.fold_ranges(fold_ranges, true, cx);
10728    }
10729
10730    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10731        let buffer_row = fold_at.buffer_row;
10732        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10733
10734        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10735            let autoscroll = self
10736                .selections
10737                .all::<Point>(cx)
10738                .iter()
10739                .any(|selection| fold_range.overlaps(&selection.range()));
10740
10741            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10742        }
10743    }
10744
10745    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10746        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10747        let buffer = &display_map.buffer_snapshot;
10748        let selections = self.selections.all::<Point>(cx);
10749        let ranges = selections
10750            .iter()
10751            .map(|s| {
10752                let range = s.display_range(&display_map).sorted();
10753                let mut start = range.start.to_point(&display_map);
10754                let mut end = range.end.to_point(&display_map);
10755                start.column = 0;
10756                end.column = buffer.line_len(MultiBufferRow(end.row));
10757                start..end
10758            })
10759            .collect::<Vec<_>>();
10760
10761        self.unfold_ranges(ranges, true, true, cx);
10762    }
10763
10764    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10765        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10766        let selections = self.selections.all::<Point>(cx);
10767        let ranges = selections
10768            .iter()
10769            .map(|s| {
10770                let mut range = s.display_range(&display_map).sorted();
10771                *range.start.column_mut() = 0;
10772                *range.end.column_mut() = display_map.line_len(range.end.row());
10773                let start = range.start.to_point(&display_map);
10774                let end = range.end.to_point(&display_map);
10775                start..end
10776            })
10777            .collect::<Vec<_>>();
10778
10779        self.unfold_ranges(ranges, true, true, cx);
10780    }
10781
10782    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10783        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10784
10785        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10786            ..Point::new(
10787                unfold_at.buffer_row.0,
10788                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10789            );
10790
10791        let autoscroll = self
10792            .selections
10793            .all::<Point>(cx)
10794            .iter()
10795            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10796
10797        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10798    }
10799
10800    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10801        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10802        self.unfold_ranges(
10803            [Point::zero()..display_map.max_point().to_point(&display_map)],
10804            true,
10805            true,
10806            cx,
10807        );
10808    }
10809
10810    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10811        let selections = self.selections.all::<Point>(cx);
10812        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10813        let line_mode = self.selections.line_mode;
10814        let ranges = selections.into_iter().map(|s| {
10815            if line_mode {
10816                let start = Point::new(s.start.row, 0);
10817                let end = Point::new(
10818                    s.end.row,
10819                    display_map
10820                        .buffer_snapshot
10821                        .line_len(MultiBufferRow(s.end.row)),
10822                );
10823                (start..end, display_map.fold_placeholder.clone())
10824            } else {
10825                (s.start..s.end, display_map.fold_placeholder.clone())
10826            }
10827        });
10828        self.fold_ranges(ranges, true, cx);
10829    }
10830
10831    pub fn fold_ranges<T: ToOffset + Clone>(
10832        &mut self,
10833        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10834        auto_scroll: bool,
10835        cx: &mut ViewContext<Self>,
10836    ) {
10837        let mut fold_ranges = Vec::new();
10838        let mut buffers_affected = HashMap::default();
10839        let multi_buffer = self.buffer().read(cx);
10840        for (fold_range, fold_text) in ranges {
10841            if let Some((_, buffer, _)) =
10842                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10843            {
10844                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10845            };
10846            fold_ranges.push((fold_range, fold_text));
10847        }
10848
10849        let mut ranges = fold_ranges.into_iter().peekable();
10850        if ranges.peek().is_some() {
10851            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10852
10853            if auto_scroll {
10854                self.request_autoscroll(Autoscroll::fit(), cx);
10855            }
10856
10857            for buffer in buffers_affected.into_values() {
10858                self.sync_expanded_diff_hunks(buffer, cx);
10859            }
10860
10861            cx.notify();
10862
10863            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10864                // Clear diagnostics block when folding a range that contains it.
10865                let snapshot = self.snapshot(cx);
10866                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10867                    drop(snapshot);
10868                    self.active_diagnostics = Some(active_diagnostics);
10869                    self.dismiss_diagnostics(cx);
10870                } else {
10871                    self.active_diagnostics = Some(active_diagnostics);
10872                }
10873            }
10874
10875            self.scrollbar_marker_state.dirty = true;
10876        }
10877    }
10878
10879    pub fn unfold_ranges<T: ToOffset + Clone>(
10880        &mut self,
10881        ranges: impl IntoIterator<Item = Range<T>>,
10882        inclusive: bool,
10883        auto_scroll: bool,
10884        cx: &mut ViewContext<Self>,
10885    ) {
10886        let mut unfold_ranges = Vec::new();
10887        let mut buffers_affected = HashMap::default();
10888        let multi_buffer = self.buffer().read(cx);
10889        for range in ranges {
10890            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10891                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10892            };
10893            unfold_ranges.push(range);
10894        }
10895
10896        let mut ranges = unfold_ranges.into_iter().peekable();
10897        if ranges.peek().is_some() {
10898            self.display_map
10899                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10900            if auto_scroll {
10901                self.request_autoscroll(Autoscroll::fit(), cx);
10902            }
10903
10904            for buffer in buffers_affected.into_values() {
10905                self.sync_expanded_diff_hunks(buffer, cx);
10906            }
10907
10908            cx.notify();
10909            self.scrollbar_marker_state.dirty = true;
10910            self.active_indent_guides_state.dirty = true;
10911        }
10912    }
10913
10914    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10915        self.display_map.read(cx).fold_placeholder.clone()
10916    }
10917
10918    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10919        if hovered != self.gutter_hovered {
10920            self.gutter_hovered = hovered;
10921            cx.notify();
10922        }
10923    }
10924
10925    pub fn insert_blocks(
10926        &mut self,
10927        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10928        autoscroll: Option<Autoscroll>,
10929        cx: &mut ViewContext<Self>,
10930    ) -> Vec<CustomBlockId> {
10931        let blocks = self
10932            .display_map
10933            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10934        if let Some(autoscroll) = autoscroll {
10935            self.request_autoscroll(autoscroll, cx);
10936        }
10937        cx.notify();
10938        blocks
10939    }
10940
10941    pub fn resize_blocks(
10942        &mut self,
10943        heights: HashMap<CustomBlockId, u32>,
10944        autoscroll: Option<Autoscroll>,
10945        cx: &mut ViewContext<Self>,
10946    ) {
10947        self.display_map
10948            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10949        if let Some(autoscroll) = autoscroll {
10950            self.request_autoscroll(autoscroll, cx);
10951        }
10952        cx.notify();
10953    }
10954
10955    pub fn replace_blocks(
10956        &mut self,
10957        renderers: HashMap<CustomBlockId, RenderBlock>,
10958        autoscroll: Option<Autoscroll>,
10959        cx: &mut ViewContext<Self>,
10960    ) {
10961        self.display_map
10962            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10963        if let Some(autoscroll) = autoscroll {
10964            self.request_autoscroll(autoscroll, cx);
10965        }
10966        cx.notify();
10967    }
10968
10969    pub fn remove_blocks(
10970        &mut self,
10971        block_ids: HashSet<CustomBlockId>,
10972        autoscroll: Option<Autoscroll>,
10973        cx: &mut ViewContext<Self>,
10974    ) {
10975        self.display_map.update(cx, |display_map, cx| {
10976            display_map.remove_blocks(block_ids, cx)
10977        });
10978        if let Some(autoscroll) = autoscroll {
10979            self.request_autoscroll(autoscroll, cx);
10980        }
10981        cx.notify();
10982    }
10983
10984    pub fn row_for_block(
10985        &self,
10986        block_id: CustomBlockId,
10987        cx: &mut ViewContext<Self>,
10988    ) -> Option<DisplayRow> {
10989        self.display_map
10990            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10991    }
10992
10993    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10994        self.focused_block = Some(focused_block);
10995    }
10996
10997    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10998        self.focused_block.take()
10999    }
11000
11001    pub fn insert_creases(
11002        &mut self,
11003        creases: impl IntoIterator<Item = Crease>,
11004        cx: &mut ViewContext<Self>,
11005    ) -> Vec<CreaseId> {
11006        self.display_map
11007            .update(cx, |map, cx| map.insert_creases(creases, cx))
11008    }
11009
11010    pub fn remove_creases(
11011        &mut self,
11012        ids: impl IntoIterator<Item = CreaseId>,
11013        cx: &mut ViewContext<Self>,
11014    ) {
11015        self.display_map
11016            .update(cx, |map, cx| map.remove_creases(ids, cx));
11017    }
11018
11019    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11020        self.display_map
11021            .update(cx, |map, cx| map.snapshot(cx))
11022            .longest_row()
11023    }
11024
11025    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11026        self.display_map
11027            .update(cx, |map, cx| map.snapshot(cx))
11028            .max_point()
11029    }
11030
11031    pub fn text(&self, cx: &AppContext) -> String {
11032        self.buffer.read(cx).read(cx).text()
11033    }
11034
11035    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11036        let text = self.text(cx);
11037        let text = text.trim();
11038
11039        if text.is_empty() {
11040            return None;
11041        }
11042
11043        Some(text.to_string())
11044    }
11045
11046    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11047        self.transact(cx, |this, cx| {
11048            this.buffer
11049                .read(cx)
11050                .as_singleton()
11051                .expect("you can only call set_text on editors for singleton buffers")
11052                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11053        });
11054    }
11055
11056    pub fn display_text(&self, cx: &mut AppContext) -> String {
11057        self.display_map
11058            .update(cx, |map, cx| map.snapshot(cx))
11059            .text()
11060    }
11061
11062    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11063        let mut wrap_guides = smallvec::smallvec![];
11064
11065        if self.show_wrap_guides == Some(false) {
11066            return wrap_guides;
11067        }
11068
11069        let settings = self.buffer.read(cx).settings_at(0, cx);
11070        if settings.show_wrap_guides {
11071            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11072                wrap_guides.push((soft_wrap as usize, true));
11073            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11074                wrap_guides.push((soft_wrap as usize, true));
11075            }
11076            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11077        }
11078
11079        wrap_guides
11080    }
11081
11082    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11083        let settings = self.buffer.read(cx).settings_at(0, cx);
11084        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11085        match mode {
11086            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11087                SoftWrap::None
11088            }
11089            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11090            language_settings::SoftWrap::PreferredLineLength => {
11091                SoftWrap::Column(settings.preferred_line_length)
11092            }
11093            language_settings::SoftWrap::Bounded => {
11094                SoftWrap::Bounded(settings.preferred_line_length)
11095            }
11096        }
11097    }
11098
11099    pub fn set_soft_wrap_mode(
11100        &mut self,
11101        mode: language_settings::SoftWrap,
11102        cx: &mut ViewContext<Self>,
11103    ) {
11104        self.soft_wrap_mode_override = Some(mode);
11105        cx.notify();
11106    }
11107
11108    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11109        let rem_size = cx.rem_size();
11110        self.display_map.update(cx, |map, cx| {
11111            map.set_font(
11112                style.text.font(),
11113                style.text.font_size.to_pixels(rem_size),
11114                cx,
11115            )
11116        });
11117        self.style = Some(style);
11118    }
11119
11120    pub fn style(&self) -> Option<&EditorStyle> {
11121        self.style.as_ref()
11122    }
11123
11124    // Called by the element. This method is not designed to be called outside of the editor
11125    // element's layout code because it does not notify when rewrapping is computed synchronously.
11126    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11127        self.display_map
11128            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11129    }
11130
11131    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11132        if self.soft_wrap_mode_override.is_some() {
11133            self.soft_wrap_mode_override.take();
11134        } else {
11135            let soft_wrap = match self.soft_wrap_mode(cx) {
11136                SoftWrap::GitDiff => return,
11137                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11138                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11139                    language_settings::SoftWrap::None
11140                }
11141            };
11142            self.soft_wrap_mode_override = Some(soft_wrap);
11143        }
11144        cx.notify();
11145    }
11146
11147    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11148        let Some(workspace) = self.workspace() else {
11149            return;
11150        };
11151        let fs = workspace.read(cx).app_state().fs.clone();
11152        let current_show = TabBarSettings::get_global(cx).show;
11153        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11154            setting.show = Some(!current_show);
11155        });
11156    }
11157
11158    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11159        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11160            self.buffer
11161                .read(cx)
11162                .settings_at(0, cx)
11163                .indent_guides
11164                .enabled
11165        });
11166        self.show_indent_guides = Some(!currently_enabled);
11167        cx.notify();
11168    }
11169
11170    fn should_show_indent_guides(&self) -> Option<bool> {
11171        self.show_indent_guides
11172    }
11173
11174    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11175        let mut editor_settings = EditorSettings::get_global(cx).clone();
11176        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11177        EditorSettings::override_global(editor_settings, cx);
11178    }
11179
11180    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11181        self.use_relative_line_numbers
11182            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11183    }
11184
11185    pub fn toggle_relative_line_numbers(
11186        &mut self,
11187        _: &ToggleRelativeLineNumbers,
11188        cx: &mut ViewContext<Self>,
11189    ) {
11190        let is_relative = self.should_use_relative_line_numbers(cx);
11191        self.set_relative_line_number(Some(!is_relative), cx)
11192    }
11193
11194    pub fn set_relative_line_number(
11195        &mut self,
11196        is_relative: Option<bool>,
11197        cx: &mut ViewContext<Self>,
11198    ) {
11199        self.use_relative_line_numbers = is_relative;
11200        cx.notify();
11201    }
11202
11203    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11204        self.show_gutter = show_gutter;
11205        cx.notify();
11206    }
11207
11208    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11209        self.show_line_numbers = Some(show_line_numbers);
11210        cx.notify();
11211    }
11212
11213    pub fn set_show_git_diff_gutter(
11214        &mut self,
11215        show_git_diff_gutter: bool,
11216        cx: &mut ViewContext<Self>,
11217    ) {
11218        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11219        cx.notify();
11220    }
11221
11222    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11223        self.show_code_actions = Some(show_code_actions);
11224        cx.notify();
11225    }
11226
11227    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11228        self.show_runnables = Some(show_runnables);
11229        cx.notify();
11230    }
11231
11232    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11233        if self.display_map.read(cx).masked != masked {
11234            self.display_map.update(cx, |map, _| map.masked = masked);
11235        }
11236        cx.notify()
11237    }
11238
11239    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11240        self.show_wrap_guides = Some(show_wrap_guides);
11241        cx.notify();
11242    }
11243
11244    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11245        self.show_indent_guides = Some(show_indent_guides);
11246        cx.notify();
11247    }
11248
11249    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11250        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11251            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11252                if let Some(dir) = file.abs_path(cx).parent() {
11253                    return Some(dir.to_owned());
11254                }
11255            }
11256
11257            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11258                return Some(project_path.path.to_path_buf());
11259            }
11260        }
11261
11262        None
11263    }
11264
11265    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11266        self.active_excerpt(cx)?
11267            .1
11268            .read(cx)
11269            .file()
11270            .and_then(|f| f.as_local())
11271    }
11272
11273    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11274        if let Some(target) = self.target_file(cx) {
11275            cx.reveal_path(&target.abs_path(cx));
11276        }
11277    }
11278
11279    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11280        if let Some(file) = self.target_file(cx) {
11281            if let Some(path) = file.abs_path(cx).to_str() {
11282                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11283            }
11284        }
11285    }
11286
11287    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11288        if let Some(file) = self.target_file(cx) {
11289            if let Some(path) = file.path().to_str() {
11290                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11291            }
11292        }
11293    }
11294
11295    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11296        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11297
11298        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11299            self.start_git_blame(true, cx);
11300        }
11301
11302        cx.notify();
11303    }
11304
11305    pub fn toggle_git_blame_inline(
11306        &mut self,
11307        _: &ToggleGitBlameInline,
11308        cx: &mut ViewContext<Self>,
11309    ) {
11310        self.toggle_git_blame_inline_internal(true, cx);
11311        cx.notify();
11312    }
11313
11314    pub fn git_blame_inline_enabled(&self) -> bool {
11315        self.git_blame_inline_enabled
11316    }
11317
11318    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11319        self.show_selection_menu = self
11320            .show_selection_menu
11321            .map(|show_selections_menu| !show_selections_menu)
11322            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11323
11324        cx.notify();
11325    }
11326
11327    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11328        self.show_selection_menu
11329            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11330    }
11331
11332    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11333        if let Some(project) = self.project.as_ref() {
11334            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11335                return;
11336            };
11337
11338            if buffer.read(cx).file().is_none() {
11339                return;
11340            }
11341
11342            let focused = self.focus_handle(cx).contains_focused(cx);
11343
11344            let project = project.clone();
11345            let blame =
11346                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11347            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11348            self.blame = Some(blame);
11349        }
11350    }
11351
11352    fn toggle_git_blame_inline_internal(
11353        &mut self,
11354        user_triggered: bool,
11355        cx: &mut ViewContext<Self>,
11356    ) {
11357        if self.git_blame_inline_enabled {
11358            self.git_blame_inline_enabled = false;
11359            self.show_git_blame_inline = false;
11360            self.show_git_blame_inline_delay_task.take();
11361        } else {
11362            self.git_blame_inline_enabled = true;
11363            self.start_git_blame_inline(user_triggered, cx);
11364        }
11365
11366        cx.notify();
11367    }
11368
11369    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11370        self.start_git_blame(user_triggered, cx);
11371
11372        if ProjectSettings::get_global(cx)
11373            .git
11374            .inline_blame_delay()
11375            .is_some()
11376        {
11377            self.start_inline_blame_timer(cx);
11378        } else {
11379            self.show_git_blame_inline = true
11380        }
11381    }
11382
11383    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11384        self.blame.as_ref()
11385    }
11386
11387    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11388        self.show_git_blame_gutter && self.has_blame_entries(cx)
11389    }
11390
11391    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11392        self.show_git_blame_inline
11393            && self.focus_handle.is_focused(cx)
11394            && !self.newest_selection_head_on_empty_line(cx)
11395            && self.has_blame_entries(cx)
11396    }
11397
11398    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11399        self.blame()
11400            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11401    }
11402
11403    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11404        let cursor_anchor = self.selections.newest_anchor().head();
11405
11406        let snapshot = self.buffer.read(cx).snapshot(cx);
11407        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11408
11409        snapshot.line_len(buffer_row) == 0
11410    }
11411
11412    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11413        let (path, selection, repo) = maybe!({
11414            let project_handle = self.project.as_ref()?.clone();
11415            let project = project_handle.read(cx);
11416
11417            let selection = self.selections.newest::<Point>(cx);
11418            let selection_range = selection.range();
11419
11420            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11421                (buffer, selection_range.start.row..selection_range.end.row)
11422            } else {
11423                let buffer_ranges = self
11424                    .buffer()
11425                    .read(cx)
11426                    .range_to_buffer_ranges(selection_range, cx);
11427
11428                let (buffer, range, _) = if selection.reversed {
11429                    buffer_ranges.first()
11430                } else {
11431                    buffer_ranges.last()
11432                }?;
11433
11434                let snapshot = buffer.read(cx).snapshot();
11435                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11436                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11437                (buffer.clone(), selection)
11438            };
11439
11440            let path = buffer
11441                .read(cx)
11442                .file()?
11443                .as_local()?
11444                .path()
11445                .to_str()?
11446                .to_string();
11447            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11448            Some((path, selection, repo))
11449        })
11450        .ok_or_else(|| anyhow!("unable to open git repository"))?;
11451
11452        const REMOTE_NAME: &str = "origin";
11453        let origin_url = repo
11454            .remote_url(REMOTE_NAME)
11455            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11456        let sha = repo
11457            .head_sha()
11458            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11459
11460        let (provider, remote) =
11461            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11462                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11463
11464        Ok(provider.build_permalink(
11465            remote,
11466            BuildPermalinkParams {
11467                sha: &sha,
11468                path: &path,
11469                selection: Some(selection),
11470            },
11471        ))
11472    }
11473
11474    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11475        let permalink = self.get_permalink_to_line(cx);
11476
11477        match permalink {
11478            Ok(permalink) => {
11479                cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11480            }
11481            Err(err) => {
11482                let message = format!("Failed to copy permalink: {err}");
11483
11484                Err::<(), anyhow::Error>(err).log_err();
11485
11486                if let Some(workspace) = self.workspace() {
11487                    workspace.update(cx, |workspace, cx| {
11488                        struct CopyPermalinkToLine;
11489
11490                        workspace.show_toast(
11491                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11492                            cx,
11493                        )
11494                    })
11495                }
11496            }
11497        }
11498    }
11499
11500    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11501        if let Some(file) = self.target_file(cx) {
11502            if let Some(path) = file.path().to_str() {
11503                let selection = self.selections.newest::<Point>(cx).start.row + 1;
11504                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11505            }
11506        }
11507    }
11508
11509    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11510        let permalink = self.get_permalink_to_line(cx);
11511
11512        match permalink {
11513            Ok(permalink) => {
11514                cx.open_url(permalink.as_ref());
11515            }
11516            Err(err) => {
11517                let message = format!("Failed to open permalink: {err}");
11518
11519                Err::<(), anyhow::Error>(err).log_err();
11520
11521                if let Some(workspace) = self.workspace() {
11522                    workspace.update(cx, |workspace, cx| {
11523                        struct OpenPermalinkToLine;
11524
11525                        workspace.show_toast(
11526                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11527                            cx,
11528                        )
11529                    })
11530                }
11531            }
11532        }
11533    }
11534
11535    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11536    /// last highlight added will be used.
11537    ///
11538    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11539    pub fn highlight_rows<T: 'static>(
11540        &mut self,
11541        range: Range<Anchor>,
11542        color: Hsla,
11543        should_autoscroll: bool,
11544        cx: &mut ViewContext<Self>,
11545    ) {
11546        let snapshot = self.buffer().read(cx).snapshot(cx);
11547        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11548        let ix = row_highlights.binary_search_by(|highlight| {
11549            Ordering::Equal
11550                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11551                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11552        });
11553
11554        if let Err(mut ix) = ix {
11555            let index = post_inc(&mut self.highlight_order);
11556
11557            // If this range intersects with the preceding highlight, then merge it with
11558            // the preceding highlight. Otherwise insert a new highlight.
11559            let mut merged = false;
11560            if ix > 0 {
11561                let prev_highlight = &mut row_highlights[ix - 1];
11562                if prev_highlight
11563                    .range
11564                    .end
11565                    .cmp(&range.start, &snapshot)
11566                    .is_ge()
11567                {
11568                    ix -= 1;
11569                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11570                        prev_highlight.range.end = range.end;
11571                    }
11572                    merged = true;
11573                    prev_highlight.index = index;
11574                    prev_highlight.color = color;
11575                    prev_highlight.should_autoscroll = should_autoscroll;
11576                }
11577            }
11578
11579            if !merged {
11580                row_highlights.insert(
11581                    ix,
11582                    RowHighlight {
11583                        range: range.clone(),
11584                        index,
11585                        color,
11586                        should_autoscroll,
11587                    },
11588                );
11589            }
11590
11591            // If any of the following highlights intersect with this one, merge them.
11592            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11593                let highlight = &row_highlights[ix];
11594                if next_highlight
11595                    .range
11596                    .start
11597                    .cmp(&highlight.range.end, &snapshot)
11598                    .is_le()
11599                {
11600                    if next_highlight
11601                        .range
11602                        .end
11603                        .cmp(&highlight.range.end, &snapshot)
11604                        .is_gt()
11605                    {
11606                        row_highlights[ix].range.end = next_highlight.range.end;
11607                    }
11608                    row_highlights.remove(ix + 1);
11609                } else {
11610                    break;
11611                }
11612            }
11613        }
11614    }
11615
11616    /// Remove any highlighted row ranges of the given type that intersect the
11617    /// given ranges.
11618    pub fn remove_highlighted_rows<T: 'static>(
11619        &mut self,
11620        ranges_to_remove: Vec<Range<Anchor>>,
11621        cx: &mut ViewContext<Self>,
11622    ) {
11623        let snapshot = self.buffer().read(cx).snapshot(cx);
11624        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11625        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11626        row_highlights.retain(|highlight| {
11627            while let Some(range_to_remove) = ranges_to_remove.peek() {
11628                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11629                    Ordering::Less | Ordering::Equal => {
11630                        ranges_to_remove.next();
11631                    }
11632                    Ordering::Greater => {
11633                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11634                            Ordering::Less | Ordering::Equal => {
11635                                return false;
11636                            }
11637                            Ordering::Greater => break,
11638                        }
11639                    }
11640                }
11641            }
11642
11643            true
11644        })
11645    }
11646
11647    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11648    pub fn clear_row_highlights<T: 'static>(&mut self) {
11649        self.highlighted_rows.remove(&TypeId::of::<T>());
11650    }
11651
11652    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11653    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11654        self.highlighted_rows
11655            .get(&TypeId::of::<T>())
11656            .map_or(&[] as &[_], |vec| vec.as_slice())
11657            .iter()
11658            .map(|highlight| (highlight.range.clone(), highlight.color))
11659    }
11660
11661    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11662    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11663    /// Allows to ignore certain kinds of highlights.
11664    pub fn highlighted_display_rows(
11665        &mut self,
11666        cx: &mut WindowContext,
11667    ) -> BTreeMap<DisplayRow, Hsla> {
11668        let snapshot = self.snapshot(cx);
11669        let mut used_highlight_orders = HashMap::default();
11670        self.highlighted_rows
11671            .iter()
11672            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11673            .fold(
11674                BTreeMap::<DisplayRow, Hsla>::new(),
11675                |mut unique_rows, highlight| {
11676                    let start = highlight.range.start.to_display_point(&snapshot);
11677                    let end = highlight.range.end.to_display_point(&snapshot);
11678                    let start_row = start.row().0;
11679                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11680                        && end.column() == 0
11681                    {
11682                        end.row().0.saturating_sub(1)
11683                    } else {
11684                        end.row().0
11685                    };
11686                    for row in start_row..=end_row {
11687                        let used_index =
11688                            used_highlight_orders.entry(row).or_insert(highlight.index);
11689                        if highlight.index >= *used_index {
11690                            *used_index = highlight.index;
11691                            unique_rows.insert(DisplayRow(row), highlight.color);
11692                        }
11693                    }
11694                    unique_rows
11695                },
11696            )
11697    }
11698
11699    pub fn highlighted_display_row_for_autoscroll(
11700        &self,
11701        snapshot: &DisplaySnapshot,
11702    ) -> Option<DisplayRow> {
11703        self.highlighted_rows
11704            .values()
11705            .flat_map(|highlighted_rows| highlighted_rows.iter())
11706            .filter_map(|highlight| {
11707                if highlight.should_autoscroll {
11708                    Some(highlight.range.start.to_display_point(snapshot).row())
11709                } else {
11710                    None
11711                }
11712            })
11713            .min()
11714    }
11715
11716    pub fn set_search_within_ranges(
11717        &mut self,
11718        ranges: &[Range<Anchor>],
11719        cx: &mut ViewContext<Self>,
11720    ) {
11721        self.highlight_background::<SearchWithinRange>(
11722            ranges,
11723            |colors| colors.editor_document_highlight_read_background,
11724            cx,
11725        )
11726    }
11727
11728    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11729        self.breadcrumb_header = Some(new_header);
11730    }
11731
11732    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11733        self.clear_background_highlights::<SearchWithinRange>(cx);
11734    }
11735
11736    pub fn highlight_background<T: 'static>(
11737        &mut self,
11738        ranges: &[Range<Anchor>],
11739        color_fetcher: fn(&ThemeColors) -> Hsla,
11740        cx: &mut ViewContext<Self>,
11741    ) {
11742        self.background_highlights
11743            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11744        self.scrollbar_marker_state.dirty = true;
11745        cx.notify();
11746    }
11747
11748    pub fn clear_background_highlights<T: 'static>(
11749        &mut self,
11750        cx: &mut ViewContext<Self>,
11751    ) -> Option<BackgroundHighlight> {
11752        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11753        if !text_highlights.1.is_empty() {
11754            self.scrollbar_marker_state.dirty = true;
11755            cx.notify();
11756        }
11757        Some(text_highlights)
11758    }
11759
11760    pub fn highlight_gutter<T: 'static>(
11761        &mut self,
11762        ranges: &[Range<Anchor>],
11763        color_fetcher: fn(&AppContext) -> Hsla,
11764        cx: &mut ViewContext<Self>,
11765    ) {
11766        self.gutter_highlights
11767            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11768        cx.notify();
11769    }
11770
11771    pub fn clear_gutter_highlights<T: 'static>(
11772        &mut self,
11773        cx: &mut ViewContext<Self>,
11774    ) -> Option<GutterHighlight> {
11775        cx.notify();
11776        self.gutter_highlights.remove(&TypeId::of::<T>())
11777    }
11778
11779    #[cfg(feature = "test-support")]
11780    pub fn all_text_background_highlights(
11781        &mut self,
11782        cx: &mut ViewContext<Self>,
11783    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11784        let snapshot = self.snapshot(cx);
11785        let buffer = &snapshot.buffer_snapshot;
11786        let start = buffer.anchor_before(0);
11787        let end = buffer.anchor_after(buffer.len());
11788        let theme = cx.theme().colors();
11789        self.background_highlights_in_range(start..end, &snapshot, theme)
11790    }
11791
11792    #[cfg(feature = "test-support")]
11793    pub fn search_background_highlights(
11794        &mut self,
11795        cx: &mut ViewContext<Self>,
11796    ) -> Vec<Range<Point>> {
11797        let snapshot = self.buffer().read(cx).snapshot(cx);
11798
11799        let highlights = self
11800            .background_highlights
11801            .get(&TypeId::of::<items::BufferSearchHighlights>());
11802
11803        if let Some((_color, ranges)) = highlights {
11804            ranges
11805                .iter()
11806                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11807                .collect_vec()
11808        } else {
11809            vec![]
11810        }
11811    }
11812
11813    fn document_highlights_for_position<'a>(
11814        &'a self,
11815        position: Anchor,
11816        buffer: &'a MultiBufferSnapshot,
11817    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11818        let read_highlights = self
11819            .background_highlights
11820            .get(&TypeId::of::<DocumentHighlightRead>())
11821            .map(|h| &h.1);
11822        let write_highlights = self
11823            .background_highlights
11824            .get(&TypeId::of::<DocumentHighlightWrite>())
11825            .map(|h| &h.1);
11826        let left_position = position.bias_left(buffer);
11827        let right_position = position.bias_right(buffer);
11828        read_highlights
11829            .into_iter()
11830            .chain(write_highlights)
11831            .flat_map(move |ranges| {
11832                let start_ix = match ranges.binary_search_by(|probe| {
11833                    let cmp = probe.end.cmp(&left_position, buffer);
11834                    if cmp.is_ge() {
11835                        Ordering::Greater
11836                    } else {
11837                        Ordering::Less
11838                    }
11839                }) {
11840                    Ok(i) | Err(i) => i,
11841                };
11842
11843                ranges[start_ix..]
11844                    .iter()
11845                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11846            })
11847    }
11848
11849    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11850        self.background_highlights
11851            .get(&TypeId::of::<T>())
11852            .map_or(false, |(_, highlights)| !highlights.is_empty())
11853    }
11854
11855    pub fn background_highlights_in_range(
11856        &self,
11857        search_range: Range<Anchor>,
11858        display_snapshot: &DisplaySnapshot,
11859        theme: &ThemeColors,
11860    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11861        let mut results = Vec::new();
11862        for (color_fetcher, ranges) in self.background_highlights.values() {
11863            let color = color_fetcher(theme);
11864            let start_ix = match ranges.binary_search_by(|probe| {
11865                let cmp = probe
11866                    .end
11867                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11868                if cmp.is_gt() {
11869                    Ordering::Greater
11870                } else {
11871                    Ordering::Less
11872                }
11873            }) {
11874                Ok(i) | Err(i) => i,
11875            };
11876            for range in &ranges[start_ix..] {
11877                if range
11878                    .start
11879                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11880                    .is_ge()
11881                {
11882                    break;
11883                }
11884
11885                let start = range.start.to_display_point(display_snapshot);
11886                let end = range.end.to_display_point(display_snapshot);
11887                results.push((start..end, color))
11888            }
11889        }
11890        results
11891    }
11892
11893    pub fn background_highlight_row_ranges<T: 'static>(
11894        &self,
11895        search_range: Range<Anchor>,
11896        display_snapshot: &DisplaySnapshot,
11897        count: usize,
11898    ) -> Vec<RangeInclusive<DisplayPoint>> {
11899        let mut results = Vec::new();
11900        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11901            return vec![];
11902        };
11903
11904        let start_ix = match ranges.binary_search_by(|probe| {
11905            let cmp = probe
11906                .end
11907                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11908            if cmp.is_gt() {
11909                Ordering::Greater
11910            } else {
11911                Ordering::Less
11912            }
11913        }) {
11914            Ok(i) | Err(i) => i,
11915        };
11916        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11917            if let (Some(start_display), Some(end_display)) = (start, end) {
11918                results.push(
11919                    start_display.to_display_point(display_snapshot)
11920                        ..=end_display.to_display_point(display_snapshot),
11921                );
11922            }
11923        };
11924        let mut start_row: Option<Point> = None;
11925        let mut end_row: Option<Point> = None;
11926        if ranges.len() > count {
11927            return Vec::new();
11928        }
11929        for range in &ranges[start_ix..] {
11930            if range
11931                .start
11932                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11933                .is_ge()
11934            {
11935                break;
11936            }
11937            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11938            if let Some(current_row) = &end_row {
11939                if end.row == current_row.row {
11940                    continue;
11941                }
11942            }
11943            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11944            if start_row.is_none() {
11945                assert_eq!(end_row, None);
11946                start_row = Some(start);
11947                end_row = Some(end);
11948                continue;
11949            }
11950            if let Some(current_end) = end_row.as_mut() {
11951                if start.row > current_end.row + 1 {
11952                    push_region(start_row, end_row);
11953                    start_row = Some(start);
11954                    end_row = Some(end);
11955                } else {
11956                    // Merge two hunks.
11957                    *current_end = end;
11958                }
11959            } else {
11960                unreachable!();
11961            }
11962        }
11963        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11964        push_region(start_row, end_row);
11965        results
11966    }
11967
11968    pub fn gutter_highlights_in_range(
11969        &self,
11970        search_range: Range<Anchor>,
11971        display_snapshot: &DisplaySnapshot,
11972        cx: &AppContext,
11973    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11974        let mut results = Vec::new();
11975        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11976            let color = color_fetcher(cx);
11977            let start_ix = match ranges.binary_search_by(|probe| {
11978                let cmp = probe
11979                    .end
11980                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11981                if cmp.is_gt() {
11982                    Ordering::Greater
11983                } else {
11984                    Ordering::Less
11985                }
11986            }) {
11987                Ok(i) | Err(i) => i,
11988            };
11989            for range in &ranges[start_ix..] {
11990                if range
11991                    .start
11992                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11993                    .is_ge()
11994                {
11995                    break;
11996                }
11997
11998                let start = range.start.to_display_point(display_snapshot);
11999                let end = range.end.to_display_point(display_snapshot);
12000                results.push((start..end, color))
12001            }
12002        }
12003        results
12004    }
12005
12006    /// Get the text ranges corresponding to the redaction query
12007    pub fn redacted_ranges(
12008        &self,
12009        search_range: Range<Anchor>,
12010        display_snapshot: &DisplaySnapshot,
12011        cx: &WindowContext,
12012    ) -> Vec<Range<DisplayPoint>> {
12013        display_snapshot
12014            .buffer_snapshot
12015            .redacted_ranges(search_range, |file| {
12016                if let Some(file) = file {
12017                    file.is_private()
12018                        && EditorSettings::get(
12019                            Some(SettingsLocation {
12020                                worktree_id: file.worktree_id(cx),
12021                                path: file.path().as_ref(),
12022                            }),
12023                            cx,
12024                        )
12025                        .redact_private_values
12026                } else {
12027                    false
12028                }
12029            })
12030            .map(|range| {
12031                range.start.to_display_point(display_snapshot)
12032                    ..range.end.to_display_point(display_snapshot)
12033            })
12034            .collect()
12035    }
12036
12037    pub fn highlight_text<T: 'static>(
12038        &mut self,
12039        ranges: Vec<Range<Anchor>>,
12040        style: HighlightStyle,
12041        cx: &mut ViewContext<Self>,
12042    ) {
12043        self.display_map.update(cx, |map, _| {
12044            map.highlight_text(TypeId::of::<T>(), ranges, style)
12045        });
12046        cx.notify();
12047    }
12048
12049    pub(crate) fn highlight_inlays<T: 'static>(
12050        &mut self,
12051        highlights: Vec<InlayHighlight>,
12052        style: HighlightStyle,
12053        cx: &mut ViewContext<Self>,
12054    ) {
12055        self.display_map.update(cx, |map, _| {
12056            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12057        });
12058        cx.notify();
12059    }
12060
12061    pub fn text_highlights<'a, T: 'static>(
12062        &'a self,
12063        cx: &'a AppContext,
12064    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12065        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12066    }
12067
12068    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12069        let cleared = self
12070            .display_map
12071            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12072        if cleared {
12073            cx.notify();
12074        }
12075    }
12076
12077    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12078        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12079            && self.focus_handle.is_focused(cx)
12080    }
12081
12082    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12083        self.show_cursor_when_unfocused = is_enabled;
12084        cx.notify();
12085    }
12086
12087    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12088        cx.notify();
12089    }
12090
12091    fn on_buffer_event(
12092        &mut self,
12093        multibuffer: Model<MultiBuffer>,
12094        event: &multi_buffer::Event,
12095        cx: &mut ViewContext<Self>,
12096    ) {
12097        match event {
12098            multi_buffer::Event::Edited {
12099                singleton_buffer_edited,
12100            } => {
12101                self.scrollbar_marker_state.dirty = true;
12102                self.active_indent_guides_state.dirty = true;
12103                self.refresh_active_diagnostics(cx);
12104                self.refresh_code_actions(cx);
12105                if self.has_active_inline_completion(cx) {
12106                    self.update_visible_inline_completion(cx);
12107                }
12108                cx.emit(EditorEvent::BufferEdited);
12109                cx.emit(SearchEvent::MatchesInvalidated);
12110                if *singleton_buffer_edited {
12111                    if let Some(project) = &self.project {
12112                        let project = project.read(cx);
12113                        #[allow(clippy::mutable_key_type)]
12114                        let languages_affected = multibuffer
12115                            .read(cx)
12116                            .all_buffers()
12117                            .into_iter()
12118                            .filter_map(|buffer| {
12119                                let buffer = buffer.read(cx);
12120                                let language = buffer.language()?;
12121                                if project.is_local()
12122                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12123                                {
12124                                    None
12125                                } else {
12126                                    Some(language)
12127                                }
12128                            })
12129                            .cloned()
12130                            .collect::<HashSet<_>>();
12131                        if !languages_affected.is_empty() {
12132                            self.refresh_inlay_hints(
12133                                InlayHintRefreshReason::BufferEdited(languages_affected),
12134                                cx,
12135                            );
12136                        }
12137                    }
12138                }
12139
12140                let Some(project) = &self.project else { return };
12141                let telemetry = project.read(cx).client().telemetry().clone();
12142                refresh_linked_ranges(self, cx);
12143                telemetry.log_edit_event("editor");
12144            }
12145            multi_buffer::Event::ExcerptsAdded {
12146                buffer,
12147                predecessor,
12148                excerpts,
12149            } => {
12150                self.tasks_update_task = Some(self.refresh_runnables(cx));
12151                cx.emit(EditorEvent::ExcerptsAdded {
12152                    buffer: buffer.clone(),
12153                    predecessor: *predecessor,
12154                    excerpts: excerpts.clone(),
12155                });
12156                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12157            }
12158            multi_buffer::Event::ExcerptsRemoved { ids } => {
12159                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12160                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12161            }
12162            multi_buffer::Event::ExcerptsEdited { ids } => {
12163                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12164            }
12165            multi_buffer::Event::ExcerptsExpanded { ids } => {
12166                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12167            }
12168            multi_buffer::Event::Reparsed(buffer_id) => {
12169                self.tasks_update_task = Some(self.refresh_runnables(cx));
12170
12171                cx.emit(EditorEvent::Reparsed(*buffer_id));
12172            }
12173            multi_buffer::Event::LanguageChanged(buffer_id) => {
12174                linked_editing_ranges::refresh_linked_ranges(self, cx);
12175                cx.emit(EditorEvent::Reparsed(*buffer_id));
12176                cx.notify();
12177            }
12178            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12179            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12180            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12181                cx.emit(EditorEvent::TitleChanged)
12182            }
12183            multi_buffer::Event::DiffBaseChanged => {
12184                self.scrollbar_marker_state.dirty = true;
12185                cx.emit(EditorEvent::DiffBaseChanged);
12186                cx.notify();
12187            }
12188            multi_buffer::Event::DiffUpdated { buffer } => {
12189                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12190                cx.notify();
12191            }
12192            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12193            multi_buffer::Event::DiagnosticsUpdated => {
12194                self.refresh_active_diagnostics(cx);
12195                self.scrollbar_marker_state.dirty = true;
12196                cx.notify();
12197            }
12198            _ => {}
12199        };
12200    }
12201
12202    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12203        cx.notify();
12204    }
12205
12206    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12207        self.tasks_update_task = Some(self.refresh_runnables(cx));
12208        self.refresh_inline_completion(true, false, cx);
12209        self.refresh_inlay_hints(
12210            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12211                self.selections.newest_anchor().head(),
12212                &self.buffer.read(cx).snapshot(cx),
12213                cx,
12214            )),
12215            cx,
12216        );
12217
12218        let old_cursor_shape = self.cursor_shape;
12219
12220        {
12221            let editor_settings = EditorSettings::get_global(cx);
12222            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12223            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12224            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12225        }
12226
12227        if old_cursor_shape != self.cursor_shape {
12228            cx.emit(EditorEvent::CursorShapeChanged);
12229        }
12230
12231        let project_settings = ProjectSettings::get_global(cx);
12232        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12233
12234        if self.mode == EditorMode::Full {
12235            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12236            if self.git_blame_inline_enabled != inline_blame_enabled {
12237                self.toggle_git_blame_inline_internal(false, cx);
12238            }
12239        }
12240
12241        cx.notify();
12242    }
12243
12244    pub fn set_searchable(&mut self, searchable: bool) {
12245        self.searchable = searchable;
12246    }
12247
12248    pub fn searchable(&self) -> bool {
12249        self.searchable
12250    }
12251
12252    fn open_proposed_changes_editor(
12253        &mut self,
12254        _: &OpenProposedChangesEditor,
12255        cx: &mut ViewContext<Self>,
12256    ) {
12257        let Some(workspace) = self.workspace() else {
12258            cx.propagate();
12259            return;
12260        };
12261
12262        let buffer = self.buffer.read(cx);
12263        let mut new_selections_by_buffer = HashMap::default();
12264        for selection in self.selections.all::<usize>(cx) {
12265            for (buffer, range, _) in
12266                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12267            {
12268                let mut range = range.to_point(buffer.read(cx));
12269                range.start.column = 0;
12270                range.end.column = buffer.read(cx).line_len(range.end.row);
12271                new_selections_by_buffer
12272                    .entry(buffer)
12273                    .or_insert(Vec::new())
12274                    .push(range)
12275            }
12276        }
12277
12278        let proposed_changes_buffers = new_selections_by_buffer
12279            .into_iter()
12280            .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12281            .collect::<Vec<_>>();
12282        let proposed_changes_editor = cx.new_view(|cx| {
12283            ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12284        });
12285
12286        cx.window_context().defer(move |cx| {
12287            workspace.update(cx, |workspace, cx| {
12288                workspace.active_pane().update(cx, |pane, cx| {
12289                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12290                });
12291            });
12292        });
12293    }
12294
12295    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12296        self.open_excerpts_common(true, cx)
12297    }
12298
12299    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12300        self.open_excerpts_common(false, cx)
12301    }
12302
12303    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12304        let buffer = self.buffer.read(cx);
12305        if buffer.is_singleton() {
12306            cx.propagate();
12307            return;
12308        }
12309
12310        let Some(workspace) = self.workspace() else {
12311            cx.propagate();
12312            return;
12313        };
12314
12315        let mut new_selections_by_buffer = HashMap::default();
12316        for selection in self.selections.all::<usize>(cx) {
12317            for (buffer, mut range, _) in
12318                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12319            {
12320                if selection.reversed {
12321                    mem::swap(&mut range.start, &mut range.end);
12322                }
12323                new_selections_by_buffer
12324                    .entry(buffer)
12325                    .or_insert(Vec::new())
12326                    .push(range)
12327            }
12328        }
12329
12330        // We defer the pane interaction because we ourselves are a workspace item
12331        // and activating a new item causes the pane to call a method on us reentrantly,
12332        // which panics if we're on the stack.
12333        cx.window_context().defer(move |cx| {
12334            workspace.update(cx, |workspace, cx| {
12335                let pane = if split {
12336                    workspace.adjacent_pane(cx)
12337                } else {
12338                    workspace.active_pane().clone()
12339                };
12340
12341                for (buffer, ranges) in new_selections_by_buffer {
12342                    let editor =
12343                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12344                    editor.update(cx, |editor, cx| {
12345                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12346                            s.select_ranges(ranges);
12347                        });
12348                    });
12349                }
12350            })
12351        });
12352    }
12353
12354    fn jump(
12355        &mut self,
12356        path: ProjectPath,
12357        position: Point,
12358        anchor: language::Anchor,
12359        offset_from_top: u32,
12360        cx: &mut ViewContext<Self>,
12361    ) {
12362        let workspace = self.workspace();
12363        cx.spawn(|_, mut cx| async move {
12364            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12365            let editor = workspace.update(&mut cx, |workspace, cx| {
12366                // Reset the preview item id before opening the new item
12367                workspace.active_pane().update(cx, |pane, cx| {
12368                    pane.set_preview_item_id(None, cx);
12369                });
12370                workspace.open_path_preview(path, None, true, true, cx)
12371            })?;
12372            let editor = editor
12373                .await?
12374                .downcast::<Editor>()
12375                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12376                .downgrade();
12377            editor.update(&mut cx, |editor, cx| {
12378                let buffer = editor
12379                    .buffer()
12380                    .read(cx)
12381                    .as_singleton()
12382                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12383                let buffer = buffer.read(cx);
12384                let cursor = if buffer.can_resolve(&anchor) {
12385                    language::ToPoint::to_point(&anchor, buffer)
12386                } else {
12387                    buffer.clip_point(position, Bias::Left)
12388                };
12389
12390                let nav_history = editor.nav_history.take();
12391                editor.change_selections(
12392                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12393                    cx,
12394                    |s| {
12395                        s.select_ranges([cursor..cursor]);
12396                    },
12397                );
12398                editor.nav_history = nav_history;
12399
12400                anyhow::Ok(())
12401            })??;
12402
12403            anyhow::Ok(())
12404        })
12405        .detach_and_log_err(cx);
12406    }
12407
12408    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12409        let snapshot = self.buffer.read(cx).read(cx);
12410        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12411        Some(
12412            ranges
12413                .iter()
12414                .map(move |range| {
12415                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12416                })
12417                .collect(),
12418        )
12419    }
12420
12421    fn selection_replacement_ranges(
12422        &self,
12423        range: Range<OffsetUtf16>,
12424        cx: &AppContext,
12425    ) -> Vec<Range<OffsetUtf16>> {
12426        let selections = self.selections.all::<OffsetUtf16>(cx);
12427        let newest_selection = selections
12428            .iter()
12429            .max_by_key(|selection| selection.id)
12430            .unwrap();
12431        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12432        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12433        let snapshot = self.buffer.read(cx).read(cx);
12434        selections
12435            .into_iter()
12436            .map(|mut selection| {
12437                selection.start.0 =
12438                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12439                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12440                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12441                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12442            })
12443            .collect()
12444    }
12445
12446    fn report_editor_event(
12447        &self,
12448        operation: &'static str,
12449        file_extension: Option<String>,
12450        cx: &AppContext,
12451    ) {
12452        if cfg!(any(test, feature = "test-support")) {
12453            return;
12454        }
12455
12456        let Some(project) = &self.project else { return };
12457
12458        // If None, we are in a file without an extension
12459        let file = self
12460            .buffer
12461            .read(cx)
12462            .as_singleton()
12463            .and_then(|b| b.read(cx).file());
12464        let file_extension = file_extension.or(file
12465            .as_ref()
12466            .and_then(|file| Path::new(file.file_name(cx)).extension())
12467            .and_then(|e| e.to_str())
12468            .map(|a| a.to_string()));
12469
12470        let vim_mode = cx
12471            .global::<SettingsStore>()
12472            .raw_user_settings()
12473            .get("vim_mode")
12474            == Some(&serde_json::Value::Bool(true));
12475
12476        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12477            == language::language_settings::InlineCompletionProvider::Copilot;
12478        let copilot_enabled_for_language = self
12479            .buffer
12480            .read(cx)
12481            .settings_at(0, cx)
12482            .show_inline_completions;
12483
12484        let telemetry = project.read(cx).client().telemetry().clone();
12485        telemetry.report_editor_event(
12486            file_extension,
12487            vim_mode,
12488            operation,
12489            copilot_enabled,
12490            copilot_enabled_for_language,
12491        )
12492    }
12493
12494    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12495    /// with each line being an array of {text, highlight} objects.
12496    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12497        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12498            return;
12499        };
12500
12501        #[derive(Serialize)]
12502        struct Chunk<'a> {
12503            text: String,
12504            highlight: Option<&'a str>,
12505        }
12506
12507        let snapshot = buffer.read(cx).snapshot();
12508        let range = self
12509            .selected_text_range(false, cx)
12510            .and_then(|selection| {
12511                if selection.range.is_empty() {
12512                    None
12513                } else {
12514                    Some(selection.range)
12515                }
12516            })
12517            .unwrap_or_else(|| 0..snapshot.len());
12518
12519        let chunks = snapshot.chunks(range, true);
12520        let mut lines = Vec::new();
12521        let mut line: VecDeque<Chunk> = VecDeque::new();
12522
12523        let Some(style) = self.style.as_ref() else {
12524            return;
12525        };
12526
12527        for chunk in chunks {
12528            let highlight = chunk
12529                .syntax_highlight_id
12530                .and_then(|id| id.name(&style.syntax));
12531            let mut chunk_lines = chunk.text.split('\n').peekable();
12532            while let Some(text) = chunk_lines.next() {
12533                let mut merged_with_last_token = false;
12534                if let Some(last_token) = line.back_mut() {
12535                    if last_token.highlight == highlight {
12536                        last_token.text.push_str(text);
12537                        merged_with_last_token = true;
12538                    }
12539                }
12540
12541                if !merged_with_last_token {
12542                    line.push_back(Chunk {
12543                        text: text.into(),
12544                        highlight,
12545                    });
12546                }
12547
12548                if chunk_lines.peek().is_some() {
12549                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12550                        line.pop_front();
12551                    }
12552                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12553                        line.pop_back();
12554                    }
12555
12556                    lines.push(mem::take(&mut line));
12557                }
12558            }
12559        }
12560
12561        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12562            return;
12563        };
12564        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12565    }
12566
12567    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12568        &self.inlay_hint_cache
12569    }
12570
12571    pub fn replay_insert_event(
12572        &mut self,
12573        text: &str,
12574        relative_utf16_range: Option<Range<isize>>,
12575        cx: &mut ViewContext<Self>,
12576    ) {
12577        if !self.input_enabled {
12578            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12579            return;
12580        }
12581        if let Some(relative_utf16_range) = relative_utf16_range {
12582            let selections = self.selections.all::<OffsetUtf16>(cx);
12583            self.change_selections(None, cx, |s| {
12584                let new_ranges = selections.into_iter().map(|range| {
12585                    let start = OffsetUtf16(
12586                        range
12587                            .head()
12588                            .0
12589                            .saturating_add_signed(relative_utf16_range.start),
12590                    );
12591                    let end = OffsetUtf16(
12592                        range
12593                            .head()
12594                            .0
12595                            .saturating_add_signed(relative_utf16_range.end),
12596                    );
12597                    start..end
12598                });
12599                s.select_ranges(new_ranges);
12600            });
12601        }
12602
12603        self.handle_input(text, cx);
12604    }
12605
12606    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12607        let Some(project) = self.project.as_ref() else {
12608            return false;
12609        };
12610        let project = project.read(cx);
12611
12612        let mut supports = false;
12613        self.buffer().read(cx).for_each_buffer(|buffer| {
12614            if !supports {
12615                supports = project
12616                    .language_servers_for_buffer(buffer.read(cx), cx)
12617                    .any(
12618                        |(_, server)| match server.capabilities().inlay_hint_provider {
12619                            Some(lsp::OneOf::Left(enabled)) => enabled,
12620                            Some(lsp::OneOf::Right(_)) => true,
12621                            None => false,
12622                        },
12623                    )
12624            }
12625        });
12626        supports
12627    }
12628
12629    pub fn focus(&self, cx: &mut WindowContext) {
12630        cx.focus(&self.focus_handle)
12631    }
12632
12633    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12634        self.focus_handle.is_focused(cx)
12635    }
12636
12637    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12638        cx.emit(EditorEvent::Focused);
12639
12640        if let Some(descendant) = self
12641            .last_focused_descendant
12642            .take()
12643            .and_then(|descendant| descendant.upgrade())
12644        {
12645            cx.focus(&descendant);
12646        } else {
12647            if let Some(blame) = self.blame.as_ref() {
12648                blame.update(cx, GitBlame::focus)
12649            }
12650
12651            self.blink_manager.update(cx, BlinkManager::enable);
12652            self.show_cursor_names(cx);
12653            self.buffer.update(cx, |buffer, cx| {
12654                buffer.finalize_last_transaction(cx);
12655                if self.leader_peer_id.is_none() {
12656                    buffer.set_active_selections(
12657                        &self.selections.disjoint_anchors(),
12658                        self.selections.line_mode,
12659                        self.cursor_shape,
12660                        cx,
12661                    );
12662                }
12663            });
12664        }
12665    }
12666
12667    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12668        cx.emit(EditorEvent::FocusedIn)
12669    }
12670
12671    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12672        if event.blurred != self.focus_handle {
12673            self.last_focused_descendant = Some(event.blurred);
12674        }
12675    }
12676
12677    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12678        self.blink_manager.update(cx, BlinkManager::disable);
12679        self.buffer
12680            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12681
12682        if let Some(blame) = self.blame.as_ref() {
12683            blame.update(cx, GitBlame::blur)
12684        }
12685        if !self.hover_state.focused(cx) {
12686            hide_hover(self, cx);
12687        }
12688
12689        self.hide_context_menu(cx);
12690        cx.emit(EditorEvent::Blurred);
12691        cx.notify();
12692    }
12693
12694    pub fn register_action<A: Action>(
12695        &mut self,
12696        listener: impl Fn(&A, &mut WindowContext) + 'static,
12697    ) -> Subscription {
12698        let id = self.next_editor_action_id.post_inc();
12699        let listener = Arc::new(listener);
12700        self.editor_actions.borrow_mut().insert(
12701            id,
12702            Box::new(move |cx| {
12703                let cx = cx.window_context();
12704                let listener = listener.clone();
12705                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12706                    let action = action.downcast_ref().unwrap();
12707                    if phase == DispatchPhase::Bubble {
12708                        listener(action, cx)
12709                    }
12710                })
12711            }),
12712        );
12713
12714        let editor_actions = self.editor_actions.clone();
12715        Subscription::new(move || {
12716            editor_actions.borrow_mut().remove(&id);
12717        })
12718    }
12719
12720    pub fn file_header_size(&self) -> u32 {
12721        self.file_header_size
12722    }
12723
12724    pub fn revert(
12725        &mut self,
12726        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12727        cx: &mut ViewContext<Self>,
12728    ) {
12729        self.buffer().update(cx, |multi_buffer, cx| {
12730            for (buffer_id, changes) in revert_changes {
12731                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12732                    buffer.update(cx, |buffer, cx| {
12733                        buffer.edit(
12734                            changes.into_iter().map(|(range, text)| {
12735                                (range, text.to_string().map(Arc::<str>::from))
12736                            }),
12737                            None,
12738                            cx,
12739                        );
12740                    });
12741                }
12742            }
12743        });
12744        self.change_selections(None, cx, |selections| selections.refresh());
12745    }
12746
12747    pub fn to_pixel_point(
12748        &mut self,
12749        source: multi_buffer::Anchor,
12750        editor_snapshot: &EditorSnapshot,
12751        cx: &mut ViewContext<Self>,
12752    ) -> Option<gpui::Point<Pixels>> {
12753        let source_point = source.to_display_point(editor_snapshot);
12754        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12755    }
12756
12757    pub fn display_to_pixel_point(
12758        &mut self,
12759        source: DisplayPoint,
12760        editor_snapshot: &EditorSnapshot,
12761        cx: &mut ViewContext<Self>,
12762    ) -> Option<gpui::Point<Pixels>> {
12763        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12764        let text_layout_details = self.text_layout_details(cx);
12765        let scroll_top = text_layout_details
12766            .scroll_anchor
12767            .scroll_position(editor_snapshot)
12768            .y;
12769
12770        if source.row().as_f32() < scroll_top.floor() {
12771            return None;
12772        }
12773        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12774        let source_y = line_height * (source.row().as_f32() - scroll_top);
12775        Some(gpui::Point::new(source_x, source_y))
12776    }
12777
12778    pub fn has_active_completions_menu(&self) -> bool {
12779        self.context_menu.read().as_ref().map_or(false, |menu| {
12780            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12781        })
12782    }
12783
12784    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12785        self.addons
12786            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12787    }
12788
12789    pub fn unregister_addon<T: Addon>(&mut self) {
12790        self.addons.remove(&std::any::TypeId::of::<T>());
12791    }
12792
12793    pub fn addon<T: Addon>(&self) -> Option<&T> {
12794        let type_id = std::any::TypeId::of::<T>();
12795        self.addons
12796            .get(&type_id)
12797            .and_then(|item| item.to_any().downcast_ref::<T>())
12798    }
12799}
12800
12801fn hunks_for_selections(
12802    multi_buffer_snapshot: &MultiBufferSnapshot,
12803    selections: &[Selection<Anchor>],
12804) -> Vec<MultiBufferDiffHunk> {
12805    let buffer_rows_for_selections = selections.iter().map(|selection| {
12806        let head = selection.head();
12807        let tail = selection.tail();
12808        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12809        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12810        if start > end {
12811            end..start
12812        } else {
12813            start..end
12814        }
12815    });
12816
12817    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12818}
12819
12820pub fn hunks_for_rows(
12821    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12822    multi_buffer_snapshot: &MultiBufferSnapshot,
12823) -> Vec<MultiBufferDiffHunk> {
12824    let mut hunks = Vec::new();
12825    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12826        HashMap::default();
12827    for selected_multi_buffer_rows in rows {
12828        let query_rows =
12829            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12830        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12831            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12832            // when the caret is just above or just below the deleted hunk.
12833            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12834            let related_to_selection = if allow_adjacent {
12835                hunk.row_range.overlaps(&query_rows)
12836                    || hunk.row_range.start == query_rows.end
12837                    || hunk.row_range.end == query_rows.start
12838            } else {
12839                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12840                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12841                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12842                    || selected_multi_buffer_rows.end == hunk.row_range.start
12843            };
12844            if related_to_selection {
12845                if !processed_buffer_rows
12846                    .entry(hunk.buffer_id)
12847                    .or_default()
12848                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12849                {
12850                    continue;
12851                }
12852                hunks.push(hunk);
12853            }
12854        }
12855    }
12856
12857    hunks
12858}
12859
12860pub trait CollaborationHub {
12861    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12862    fn user_participant_indices<'a>(
12863        &self,
12864        cx: &'a AppContext,
12865    ) -> &'a HashMap<u64, ParticipantIndex>;
12866    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12867}
12868
12869impl CollaborationHub for Model<Project> {
12870    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12871        self.read(cx).collaborators()
12872    }
12873
12874    fn user_participant_indices<'a>(
12875        &self,
12876        cx: &'a AppContext,
12877    ) -> &'a HashMap<u64, ParticipantIndex> {
12878        self.read(cx).user_store().read(cx).participant_indices()
12879    }
12880
12881    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12882        let this = self.read(cx);
12883        let user_ids = this.collaborators().values().map(|c| c.user_id);
12884        this.user_store().read_with(cx, |user_store, cx| {
12885            user_store.participant_names(user_ids, cx)
12886        })
12887    }
12888}
12889
12890pub trait CompletionProvider {
12891    fn completions(
12892        &self,
12893        buffer: &Model<Buffer>,
12894        buffer_position: text::Anchor,
12895        trigger: CompletionContext,
12896        cx: &mut ViewContext<Editor>,
12897    ) -> Task<Result<Vec<Completion>>>;
12898
12899    fn resolve_completions(
12900        &self,
12901        buffer: Model<Buffer>,
12902        completion_indices: Vec<usize>,
12903        completions: Arc<RwLock<Box<[Completion]>>>,
12904        cx: &mut ViewContext<Editor>,
12905    ) -> Task<Result<bool>>;
12906
12907    fn apply_additional_edits_for_completion(
12908        &self,
12909        buffer: Model<Buffer>,
12910        completion: Completion,
12911        push_to_history: bool,
12912        cx: &mut ViewContext<Editor>,
12913    ) -> Task<Result<Option<language::Transaction>>>;
12914
12915    fn is_completion_trigger(
12916        &self,
12917        buffer: &Model<Buffer>,
12918        position: language::Anchor,
12919        text: &str,
12920        trigger_in_words: bool,
12921        cx: &mut ViewContext<Editor>,
12922    ) -> bool;
12923
12924    fn sort_completions(&self) -> bool {
12925        true
12926    }
12927}
12928
12929pub trait CodeActionProvider {
12930    fn code_actions(
12931        &self,
12932        buffer: &Model<Buffer>,
12933        range: Range<text::Anchor>,
12934        cx: &mut WindowContext,
12935    ) -> Task<Result<Vec<CodeAction>>>;
12936
12937    fn apply_code_action(
12938        &self,
12939        buffer_handle: Model<Buffer>,
12940        action: CodeAction,
12941        excerpt_id: ExcerptId,
12942        push_to_history: bool,
12943        cx: &mut WindowContext,
12944    ) -> Task<Result<ProjectTransaction>>;
12945}
12946
12947impl CodeActionProvider for Model<Project> {
12948    fn code_actions(
12949        &self,
12950        buffer: &Model<Buffer>,
12951        range: Range<text::Anchor>,
12952        cx: &mut WindowContext,
12953    ) -> Task<Result<Vec<CodeAction>>> {
12954        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12955    }
12956
12957    fn apply_code_action(
12958        &self,
12959        buffer_handle: Model<Buffer>,
12960        action: CodeAction,
12961        _excerpt_id: ExcerptId,
12962        push_to_history: bool,
12963        cx: &mut WindowContext,
12964    ) -> Task<Result<ProjectTransaction>> {
12965        self.update(cx, |project, cx| {
12966            project.apply_code_action(buffer_handle, action, push_to_history, cx)
12967        })
12968    }
12969}
12970
12971fn snippet_completions(
12972    project: &Project,
12973    buffer: &Model<Buffer>,
12974    buffer_position: text::Anchor,
12975    cx: &mut AppContext,
12976) -> Vec<Completion> {
12977    let language = buffer.read(cx).language_at(buffer_position);
12978    let language_name = language.as_ref().map(|language| language.lsp_id());
12979    let snippet_store = project.snippets().read(cx);
12980    let snippets = snippet_store.snippets_for(language_name, cx);
12981
12982    if snippets.is_empty() {
12983        return vec![];
12984    }
12985    let snapshot = buffer.read(cx).text_snapshot();
12986    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12987
12988    let mut lines = chunks.lines();
12989    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12990        return vec![];
12991    };
12992
12993    let scope = language.map(|language| language.default_scope());
12994    let classifier = CharClassifier::new(scope).for_completion(true);
12995    let mut last_word = line_at
12996        .chars()
12997        .rev()
12998        .take_while(|c| classifier.is_word(*c))
12999        .collect::<String>();
13000    last_word = last_word.chars().rev().collect();
13001    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13002    let to_lsp = |point: &text::Anchor| {
13003        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13004        point_to_lsp(end)
13005    };
13006    let lsp_end = to_lsp(&buffer_position);
13007    snippets
13008        .into_iter()
13009        .filter_map(|snippet| {
13010            let matching_prefix = snippet
13011                .prefix
13012                .iter()
13013                .find(|prefix| prefix.starts_with(&last_word))?;
13014            let start = as_offset - last_word.len();
13015            let start = snapshot.anchor_before(start);
13016            let range = start..buffer_position;
13017            let lsp_start = to_lsp(&start);
13018            let lsp_range = lsp::Range {
13019                start: lsp_start,
13020                end: lsp_end,
13021            };
13022            Some(Completion {
13023                old_range: range,
13024                new_text: snippet.body.clone(),
13025                label: CodeLabel {
13026                    text: matching_prefix.clone(),
13027                    runs: vec![],
13028                    filter_range: 0..matching_prefix.len(),
13029                },
13030                server_id: LanguageServerId(usize::MAX),
13031                documentation: snippet.description.clone().map(Documentation::SingleLine),
13032                lsp_completion: lsp::CompletionItem {
13033                    label: snippet.prefix.first().unwrap().clone(),
13034                    kind: Some(CompletionItemKind::SNIPPET),
13035                    label_details: snippet.description.as_ref().map(|description| {
13036                        lsp::CompletionItemLabelDetails {
13037                            detail: Some(description.clone()),
13038                            description: None,
13039                        }
13040                    }),
13041                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13042                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13043                        lsp::InsertReplaceEdit {
13044                            new_text: snippet.body.clone(),
13045                            insert: lsp_range,
13046                            replace: lsp_range,
13047                        },
13048                    )),
13049                    filter_text: Some(snippet.body.clone()),
13050                    sort_text: Some(char::MAX.to_string()),
13051                    ..Default::default()
13052                },
13053                confirm: None,
13054            })
13055        })
13056        .collect()
13057}
13058
13059impl CompletionProvider for Model<Project> {
13060    fn completions(
13061        &self,
13062        buffer: &Model<Buffer>,
13063        buffer_position: text::Anchor,
13064        options: CompletionContext,
13065        cx: &mut ViewContext<Editor>,
13066    ) -> Task<Result<Vec<Completion>>> {
13067        self.update(cx, |project, cx| {
13068            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13069            let project_completions = project.completions(buffer, buffer_position, options, cx);
13070            cx.background_executor().spawn(async move {
13071                let mut completions = project_completions.await?;
13072                //let snippets = snippets.into_iter().;
13073                completions.extend(snippets);
13074                Ok(completions)
13075            })
13076        })
13077    }
13078
13079    fn resolve_completions(
13080        &self,
13081        buffer: Model<Buffer>,
13082        completion_indices: Vec<usize>,
13083        completions: Arc<RwLock<Box<[Completion]>>>,
13084        cx: &mut ViewContext<Editor>,
13085    ) -> Task<Result<bool>> {
13086        self.update(cx, |project, cx| {
13087            project.resolve_completions(buffer, completion_indices, completions, cx)
13088        })
13089    }
13090
13091    fn apply_additional_edits_for_completion(
13092        &self,
13093        buffer: Model<Buffer>,
13094        completion: Completion,
13095        push_to_history: bool,
13096        cx: &mut ViewContext<Editor>,
13097    ) -> Task<Result<Option<language::Transaction>>> {
13098        self.update(cx, |project, cx| {
13099            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13100        })
13101    }
13102
13103    fn is_completion_trigger(
13104        &self,
13105        buffer: &Model<Buffer>,
13106        position: language::Anchor,
13107        text: &str,
13108        trigger_in_words: bool,
13109        cx: &mut ViewContext<Editor>,
13110    ) -> bool {
13111        if !EditorSettings::get_global(cx).show_completions_on_input {
13112            return false;
13113        }
13114
13115        let mut chars = text.chars();
13116        let char = if let Some(char) = chars.next() {
13117            char
13118        } else {
13119            return false;
13120        };
13121        if chars.next().is_some() {
13122            return false;
13123        }
13124
13125        let buffer = buffer.read(cx);
13126        let classifier = buffer
13127            .snapshot()
13128            .char_classifier_at(position)
13129            .for_completion(true);
13130        if trigger_in_words && classifier.is_word(char) {
13131            return true;
13132        }
13133
13134        buffer
13135            .completion_triggers()
13136            .iter()
13137            .any(|string| string == text)
13138    }
13139}
13140
13141fn inlay_hint_settings(
13142    location: Anchor,
13143    snapshot: &MultiBufferSnapshot,
13144    cx: &mut ViewContext<'_, Editor>,
13145) -> InlayHintSettings {
13146    let file = snapshot.file_at(location);
13147    let language = snapshot.language_at(location);
13148    let settings = all_language_settings(file, cx);
13149    settings
13150        .language(language.map(|l| l.name()).as_ref())
13151        .inlay_hints
13152}
13153
13154fn consume_contiguous_rows(
13155    contiguous_row_selections: &mut Vec<Selection<Point>>,
13156    selection: &Selection<Point>,
13157    display_map: &DisplaySnapshot,
13158    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13159) -> (MultiBufferRow, MultiBufferRow) {
13160    contiguous_row_selections.push(selection.clone());
13161    let start_row = MultiBufferRow(selection.start.row);
13162    let mut end_row = ending_row(selection, display_map);
13163
13164    while let Some(next_selection) = selections.peek() {
13165        if next_selection.start.row <= end_row.0 {
13166            end_row = ending_row(next_selection, display_map);
13167            contiguous_row_selections.push(selections.next().unwrap().clone());
13168        } else {
13169            break;
13170        }
13171    }
13172    (start_row, end_row)
13173}
13174
13175fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13176    if next_selection.end.column > 0 || next_selection.is_empty() {
13177        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13178    } else {
13179        MultiBufferRow(next_selection.end.row)
13180    }
13181}
13182
13183impl EditorSnapshot {
13184    pub fn remote_selections_in_range<'a>(
13185        &'a self,
13186        range: &'a Range<Anchor>,
13187        collaboration_hub: &dyn CollaborationHub,
13188        cx: &'a AppContext,
13189    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13190        let participant_names = collaboration_hub.user_names(cx);
13191        let participant_indices = collaboration_hub.user_participant_indices(cx);
13192        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13193        let collaborators_by_replica_id = collaborators_by_peer_id
13194            .iter()
13195            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13196            .collect::<HashMap<_, _>>();
13197        self.buffer_snapshot
13198            .selections_in_range(range, false)
13199            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13200                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13201                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13202                let user_name = participant_names.get(&collaborator.user_id).cloned();
13203                Some(RemoteSelection {
13204                    replica_id,
13205                    selection,
13206                    cursor_shape,
13207                    line_mode,
13208                    participant_index,
13209                    peer_id: collaborator.peer_id,
13210                    user_name,
13211                })
13212            })
13213    }
13214
13215    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13216        self.display_snapshot.buffer_snapshot.language_at(position)
13217    }
13218
13219    pub fn is_focused(&self) -> bool {
13220        self.is_focused
13221    }
13222
13223    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13224        self.placeholder_text.as_ref()
13225    }
13226
13227    pub fn scroll_position(&self) -> gpui::Point<f32> {
13228        self.scroll_anchor.scroll_position(&self.display_snapshot)
13229    }
13230
13231    fn gutter_dimensions(
13232        &self,
13233        font_id: FontId,
13234        font_size: Pixels,
13235        em_width: Pixels,
13236        em_advance: Pixels,
13237        max_line_number_width: Pixels,
13238        cx: &AppContext,
13239    ) -> GutterDimensions {
13240        if !self.show_gutter {
13241            return GutterDimensions::default();
13242        }
13243        let descent = cx.text_system().descent(font_id, font_size);
13244
13245        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13246            matches!(
13247                ProjectSettings::get_global(cx).git.git_gutter,
13248                Some(GitGutterSetting::TrackedFiles)
13249            )
13250        });
13251        let gutter_settings = EditorSettings::get_global(cx).gutter;
13252        let show_line_numbers = self
13253            .show_line_numbers
13254            .unwrap_or(gutter_settings.line_numbers);
13255        let line_gutter_width = if show_line_numbers {
13256            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13257            let min_width_for_number_on_gutter = em_advance * 4.0;
13258            max_line_number_width.max(min_width_for_number_on_gutter)
13259        } else {
13260            0.0.into()
13261        };
13262
13263        let show_code_actions = self
13264            .show_code_actions
13265            .unwrap_or(gutter_settings.code_actions);
13266
13267        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13268
13269        let git_blame_entries_width =
13270            self.git_blame_gutter_max_author_length
13271                .map(|max_author_length| {
13272                    // Length of the author name, but also space for the commit hash,
13273                    // the spacing and the timestamp.
13274                    let max_char_count = max_author_length
13275                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13276                        + 7 // length of commit sha
13277                        + 14 // length of max relative timestamp ("60 minutes ago")
13278                        + 4; // gaps and margins
13279
13280                    em_advance * max_char_count
13281                });
13282
13283        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13284        left_padding += if show_code_actions || show_runnables {
13285            em_width * 3.0
13286        } else if show_git_gutter && show_line_numbers {
13287            em_width * 2.0
13288        } else if show_git_gutter || show_line_numbers {
13289            em_width
13290        } else {
13291            px(0.)
13292        };
13293
13294        let right_padding = if gutter_settings.folds && show_line_numbers {
13295            em_width * 4.0
13296        } else if gutter_settings.folds {
13297            em_width * 3.0
13298        } else if show_line_numbers {
13299            em_width
13300        } else {
13301            px(0.)
13302        };
13303
13304        GutterDimensions {
13305            left_padding,
13306            right_padding,
13307            width: line_gutter_width + left_padding + right_padding,
13308            margin: -descent,
13309            git_blame_entries_width,
13310        }
13311    }
13312
13313    pub fn render_fold_toggle(
13314        &self,
13315        buffer_row: MultiBufferRow,
13316        row_contains_cursor: bool,
13317        editor: View<Editor>,
13318        cx: &mut WindowContext,
13319    ) -> Option<AnyElement> {
13320        let folded = self.is_line_folded(buffer_row);
13321
13322        if let Some(crease) = self
13323            .crease_snapshot
13324            .query_row(buffer_row, &self.buffer_snapshot)
13325        {
13326            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13327                if folded {
13328                    editor.update(cx, |editor, cx| {
13329                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13330                    });
13331                } else {
13332                    editor.update(cx, |editor, cx| {
13333                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13334                    });
13335                }
13336            });
13337
13338            Some((crease.render_toggle)(
13339                buffer_row,
13340                folded,
13341                toggle_callback,
13342                cx,
13343            ))
13344        } else if folded
13345            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13346        {
13347            Some(
13348                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13349                    .selected(folded)
13350                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13351                        if folded {
13352                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13353                        } else {
13354                            this.fold_at(&FoldAt { buffer_row }, cx);
13355                        }
13356                    }))
13357                    .into_any_element(),
13358            )
13359        } else {
13360            None
13361        }
13362    }
13363
13364    pub fn render_crease_trailer(
13365        &self,
13366        buffer_row: MultiBufferRow,
13367        cx: &mut WindowContext,
13368    ) -> Option<AnyElement> {
13369        let folded = self.is_line_folded(buffer_row);
13370        let crease = self
13371            .crease_snapshot
13372            .query_row(buffer_row, &self.buffer_snapshot)?;
13373        Some((crease.render_trailer)(buffer_row, folded, cx))
13374    }
13375}
13376
13377impl Deref for EditorSnapshot {
13378    type Target = DisplaySnapshot;
13379
13380    fn deref(&self) -> &Self::Target {
13381        &self.display_snapshot
13382    }
13383}
13384
13385#[derive(Clone, Debug, PartialEq, Eq)]
13386pub enum EditorEvent {
13387    InputIgnored {
13388        text: Arc<str>,
13389    },
13390    InputHandled {
13391        utf16_range_to_replace: Option<Range<isize>>,
13392        text: Arc<str>,
13393    },
13394    ExcerptsAdded {
13395        buffer: Model<Buffer>,
13396        predecessor: ExcerptId,
13397        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13398    },
13399    ExcerptsRemoved {
13400        ids: Vec<ExcerptId>,
13401    },
13402    ExcerptsEdited {
13403        ids: Vec<ExcerptId>,
13404    },
13405    ExcerptsExpanded {
13406        ids: Vec<ExcerptId>,
13407    },
13408    BufferEdited,
13409    Edited {
13410        transaction_id: clock::Lamport,
13411    },
13412    Reparsed(BufferId),
13413    Focused,
13414    FocusedIn,
13415    Blurred,
13416    DirtyChanged,
13417    Saved,
13418    TitleChanged,
13419    DiffBaseChanged,
13420    SelectionsChanged {
13421        local: bool,
13422    },
13423    ScrollPositionChanged {
13424        local: bool,
13425        autoscroll: bool,
13426    },
13427    Closed,
13428    TransactionUndone {
13429        transaction_id: clock::Lamport,
13430    },
13431    TransactionBegun {
13432        transaction_id: clock::Lamport,
13433    },
13434    CursorShapeChanged,
13435}
13436
13437impl EventEmitter<EditorEvent> for Editor {}
13438
13439impl FocusableView for Editor {
13440    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13441        self.focus_handle.clone()
13442    }
13443}
13444
13445impl Render for Editor {
13446    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13447        let settings = ThemeSettings::get_global(cx);
13448
13449        let text_style = match self.mode {
13450            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13451                color: cx.theme().colors().editor_foreground,
13452                font_family: settings.ui_font.family.clone(),
13453                font_features: settings.ui_font.features.clone(),
13454                font_fallbacks: settings.ui_font.fallbacks.clone(),
13455                font_size: rems(0.875).into(),
13456                font_weight: settings.ui_font.weight,
13457                line_height: relative(settings.buffer_line_height.value()),
13458                ..Default::default()
13459            },
13460            EditorMode::Full => TextStyle {
13461                color: cx.theme().colors().editor_foreground,
13462                font_family: settings.buffer_font.family.clone(),
13463                font_features: settings.buffer_font.features.clone(),
13464                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13465                font_size: settings.buffer_font_size(cx).into(),
13466                font_weight: settings.buffer_font.weight,
13467                line_height: relative(settings.buffer_line_height.value()),
13468                ..Default::default()
13469            },
13470        };
13471
13472        let background = match self.mode {
13473            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13474            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13475            EditorMode::Full => cx.theme().colors().editor_background,
13476        };
13477
13478        EditorElement::new(
13479            cx.view(),
13480            EditorStyle {
13481                background,
13482                local_player: cx.theme().players().local(),
13483                text: text_style,
13484                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13485                syntax: cx.theme().syntax().clone(),
13486                status: cx.theme().status().clone(),
13487                inlay_hints_style: make_inlay_hints_style(cx),
13488                suggestions_style: HighlightStyle {
13489                    color: Some(cx.theme().status().predictive),
13490                    ..HighlightStyle::default()
13491                },
13492                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13493            },
13494        )
13495    }
13496}
13497
13498impl ViewInputHandler for Editor {
13499    fn text_for_range(
13500        &mut self,
13501        range_utf16: Range<usize>,
13502        cx: &mut ViewContext<Self>,
13503    ) -> Option<String> {
13504        Some(
13505            self.buffer
13506                .read(cx)
13507                .read(cx)
13508                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13509                .collect(),
13510        )
13511    }
13512
13513    fn selected_text_range(
13514        &mut self,
13515        ignore_disabled_input: bool,
13516        cx: &mut ViewContext<Self>,
13517    ) -> Option<UTF16Selection> {
13518        // Prevent the IME menu from appearing when holding down an alphabetic key
13519        // while input is disabled.
13520        if !ignore_disabled_input && !self.input_enabled {
13521            return None;
13522        }
13523
13524        let selection = self.selections.newest::<OffsetUtf16>(cx);
13525        let range = selection.range();
13526
13527        Some(UTF16Selection {
13528            range: range.start.0..range.end.0,
13529            reversed: selection.reversed,
13530        })
13531    }
13532
13533    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13534        let snapshot = self.buffer.read(cx).read(cx);
13535        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13536        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13537    }
13538
13539    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13540        self.clear_highlights::<InputComposition>(cx);
13541        self.ime_transaction.take();
13542    }
13543
13544    fn replace_text_in_range(
13545        &mut self,
13546        range_utf16: Option<Range<usize>>,
13547        text: &str,
13548        cx: &mut ViewContext<Self>,
13549    ) {
13550        if !self.input_enabled {
13551            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13552            return;
13553        }
13554
13555        self.transact(cx, |this, cx| {
13556            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13557                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13558                Some(this.selection_replacement_ranges(range_utf16, cx))
13559            } else {
13560                this.marked_text_ranges(cx)
13561            };
13562
13563            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13564                let newest_selection_id = this.selections.newest_anchor().id;
13565                this.selections
13566                    .all::<OffsetUtf16>(cx)
13567                    .iter()
13568                    .zip(ranges_to_replace.iter())
13569                    .find_map(|(selection, range)| {
13570                        if selection.id == newest_selection_id {
13571                            Some(
13572                                (range.start.0 as isize - selection.head().0 as isize)
13573                                    ..(range.end.0 as isize - selection.head().0 as isize),
13574                            )
13575                        } else {
13576                            None
13577                        }
13578                    })
13579            });
13580
13581            cx.emit(EditorEvent::InputHandled {
13582                utf16_range_to_replace: range_to_replace,
13583                text: text.into(),
13584            });
13585
13586            if let Some(new_selected_ranges) = new_selected_ranges {
13587                this.change_selections(None, cx, |selections| {
13588                    selections.select_ranges(new_selected_ranges)
13589                });
13590                this.backspace(&Default::default(), cx);
13591            }
13592
13593            this.handle_input(text, cx);
13594        });
13595
13596        if let Some(transaction) = self.ime_transaction {
13597            self.buffer.update(cx, |buffer, cx| {
13598                buffer.group_until_transaction(transaction, cx);
13599            });
13600        }
13601
13602        self.unmark_text(cx);
13603    }
13604
13605    fn replace_and_mark_text_in_range(
13606        &mut self,
13607        range_utf16: Option<Range<usize>>,
13608        text: &str,
13609        new_selected_range_utf16: Option<Range<usize>>,
13610        cx: &mut ViewContext<Self>,
13611    ) {
13612        if !self.input_enabled {
13613            return;
13614        }
13615
13616        let transaction = self.transact(cx, |this, cx| {
13617            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13618                let snapshot = this.buffer.read(cx).read(cx);
13619                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13620                    for marked_range in &mut marked_ranges {
13621                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13622                        marked_range.start.0 += relative_range_utf16.start;
13623                        marked_range.start =
13624                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13625                        marked_range.end =
13626                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13627                    }
13628                }
13629                Some(marked_ranges)
13630            } else if let Some(range_utf16) = range_utf16 {
13631                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13632                Some(this.selection_replacement_ranges(range_utf16, cx))
13633            } else {
13634                None
13635            };
13636
13637            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13638                let newest_selection_id = this.selections.newest_anchor().id;
13639                this.selections
13640                    .all::<OffsetUtf16>(cx)
13641                    .iter()
13642                    .zip(ranges_to_replace.iter())
13643                    .find_map(|(selection, range)| {
13644                        if selection.id == newest_selection_id {
13645                            Some(
13646                                (range.start.0 as isize - selection.head().0 as isize)
13647                                    ..(range.end.0 as isize - selection.head().0 as isize),
13648                            )
13649                        } else {
13650                            None
13651                        }
13652                    })
13653            });
13654
13655            cx.emit(EditorEvent::InputHandled {
13656                utf16_range_to_replace: range_to_replace,
13657                text: text.into(),
13658            });
13659
13660            if let Some(ranges) = ranges_to_replace {
13661                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13662            }
13663
13664            let marked_ranges = {
13665                let snapshot = this.buffer.read(cx).read(cx);
13666                this.selections
13667                    .disjoint_anchors()
13668                    .iter()
13669                    .map(|selection| {
13670                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13671                    })
13672                    .collect::<Vec<_>>()
13673            };
13674
13675            if text.is_empty() {
13676                this.unmark_text(cx);
13677            } else {
13678                this.highlight_text::<InputComposition>(
13679                    marked_ranges.clone(),
13680                    HighlightStyle {
13681                        underline: Some(UnderlineStyle {
13682                            thickness: px(1.),
13683                            color: None,
13684                            wavy: false,
13685                        }),
13686                        ..Default::default()
13687                    },
13688                    cx,
13689                );
13690            }
13691
13692            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13693            let use_autoclose = this.use_autoclose;
13694            let use_auto_surround = this.use_auto_surround;
13695            this.set_use_autoclose(false);
13696            this.set_use_auto_surround(false);
13697            this.handle_input(text, cx);
13698            this.set_use_autoclose(use_autoclose);
13699            this.set_use_auto_surround(use_auto_surround);
13700
13701            if let Some(new_selected_range) = new_selected_range_utf16 {
13702                let snapshot = this.buffer.read(cx).read(cx);
13703                let new_selected_ranges = marked_ranges
13704                    .into_iter()
13705                    .map(|marked_range| {
13706                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13707                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13708                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13709                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13710                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13711                    })
13712                    .collect::<Vec<_>>();
13713
13714                drop(snapshot);
13715                this.change_selections(None, cx, |selections| {
13716                    selections.select_ranges(new_selected_ranges)
13717                });
13718            }
13719        });
13720
13721        self.ime_transaction = self.ime_transaction.or(transaction);
13722        if let Some(transaction) = self.ime_transaction {
13723            self.buffer.update(cx, |buffer, cx| {
13724                buffer.group_until_transaction(transaction, cx);
13725            });
13726        }
13727
13728        if self.text_highlights::<InputComposition>(cx).is_none() {
13729            self.ime_transaction.take();
13730        }
13731    }
13732
13733    fn bounds_for_range(
13734        &mut self,
13735        range_utf16: Range<usize>,
13736        element_bounds: gpui::Bounds<Pixels>,
13737        cx: &mut ViewContext<Self>,
13738    ) -> Option<gpui::Bounds<Pixels>> {
13739        let text_layout_details = self.text_layout_details(cx);
13740        let style = &text_layout_details.editor_style;
13741        let font_id = cx.text_system().resolve_font(&style.text.font());
13742        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13743        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13744
13745        let em_width = cx
13746            .text_system()
13747            .typographic_bounds(font_id, font_size, 'm')
13748            .unwrap()
13749            .size
13750            .width;
13751
13752        let snapshot = self.snapshot(cx);
13753        let scroll_position = snapshot.scroll_position();
13754        let scroll_left = scroll_position.x * em_width;
13755
13756        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13757        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13758            + self.gutter_dimensions.width;
13759        let y = line_height * (start.row().as_f32() - scroll_position.y);
13760
13761        Some(Bounds {
13762            origin: element_bounds.origin + point(x, y),
13763            size: size(em_width, line_height),
13764        })
13765    }
13766}
13767
13768trait SelectionExt {
13769    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13770    fn spanned_rows(
13771        &self,
13772        include_end_if_at_line_start: bool,
13773        map: &DisplaySnapshot,
13774    ) -> Range<MultiBufferRow>;
13775}
13776
13777impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13778    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13779        let start = self
13780            .start
13781            .to_point(&map.buffer_snapshot)
13782            .to_display_point(map);
13783        let end = self
13784            .end
13785            .to_point(&map.buffer_snapshot)
13786            .to_display_point(map);
13787        if self.reversed {
13788            end..start
13789        } else {
13790            start..end
13791        }
13792    }
13793
13794    fn spanned_rows(
13795        &self,
13796        include_end_if_at_line_start: bool,
13797        map: &DisplaySnapshot,
13798    ) -> Range<MultiBufferRow> {
13799        let start = self.start.to_point(&map.buffer_snapshot);
13800        let mut end = self.end.to_point(&map.buffer_snapshot);
13801        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13802            end.row -= 1;
13803        }
13804
13805        let buffer_start = map.prev_line_boundary(start).0;
13806        let buffer_end = map.next_line_boundary(end).0;
13807        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13808    }
13809}
13810
13811impl<T: InvalidationRegion> InvalidationStack<T> {
13812    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13813    where
13814        S: Clone + ToOffset,
13815    {
13816        while let Some(region) = self.last() {
13817            let all_selections_inside_invalidation_ranges =
13818                if selections.len() == region.ranges().len() {
13819                    selections
13820                        .iter()
13821                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13822                        .all(|(selection, invalidation_range)| {
13823                            let head = selection.head().to_offset(buffer);
13824                            invalidation_range.start <= head && invalidation_range.end >= head
13825                        })
13826                } else {
13827                    false
13828                };
13829
13830            if all_selections_inside_invalidation_ranges {
13831                break;
13832            } else {
13833                self.pop();
13834            }
13835        }
13836    }
13837}
13838
13839impl<T> Default for InvalidationStack<T> {
13840    fn default() -> Self {
13841        Self(Default::default())
13842    }
13843}
13844
13845impl<T> Deref for InvalidationStack<T> {
13846    type Target = Vec<T>;
13847
13848    fn deref(&self) -> &Self::Target {
13849        &self.0
13850    }
13851}
13852
13853impl<T> DerefMut for InvalidationStack<T> {
13854    fn deref_mut(&mut self) -> &mut Self::Target {
13855        &mut self.0
13856    }
13857}
13858
13859impl InvalidationRegion for SnippetState {
13860    fn ranges(&self) -> &[Range<Anchor>] {
13861        &self.ranges[self.active_index]
13862    }
13863}
13864
13865pub fn diagnostic_block_renderer(
13866    diagnostic: Diagnostic,
13867    max_message_rows: Option<u8>,
13868    allow_closing: bool,
13869    _is_valid: bool,
13870) -> RenderBlock {
13871    let (text_without_backticks, code_ranges) =
13872        highlight_diagnostic_message(&diagnostic, max_message_rows);
13873
13874    Box::new(move |cx: &mut BlockContext| {
13875        let group_id: SharedString = cx.block_id.to_string().into();
13876
13877        let mut text_style = cx.text_style().clone();
13878        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13879        let theme_settings = ThemeSettings::get_global(cx);
13880        text_style.font_family = theme_settings.buffer_font.family.clone();
13881        text_style.font_style = theme_settings.buffer_font.style;
13882        text_style.font_features = theme_settings.buffer_font.features.clone();
13883        text_style.font_weight = theme_settings.buffer_font.weight;
13884
13885        let multi_line_diagnostic = diagnostic.message.contains('\n');
13886
13887        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13888            if multi_line_diagnostic {
13889                v_flex()
13890            } else {
13891                h_flex()
13892            }
13893            .when(allow_closing, |div| {
13894                div.children(diagnostic.is_primary.then(|| {
13895                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13896                        .icon_color(Color::Muted)
13897                        .size(ButtonSize::Compact)
13898                        .style(ButtonStyle::Transparent)
13899                        .visible_on_hover(group_id.clone())
13900                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13901                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13902                }))
13903            })
13904            .child(
13905                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13906                    .icon_color(Color::Muted)
13907                    .size(ButtonSize::Compact)
13908                    .style(ButtonStyle::Transparent)
13909                    .visible_on_hover(group_id.clone())
13910                    .on_click({
13911                        let message = diagnostic.message.clone();
13912                        move |_click, cx| {
13913                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13914                        }
13915                    })
13916                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13917            )
13918        };
13919
13920        let icon_size = buttons(&diagnostic, cx.block_id)
13921            .into_any_element()
13922            .layout_as_root(AvailableSpace::min_size(), cx);
13923
13924        h_flex()
13925            .id(cx.block_id)
13926            .group(group_id.clone())
13927            .relative()
13928            .size_full()
13929            .pl(cx.gutter_dimensions.width)
13930            .w(cx.max_width + cx.gutter_dimensions.width)
13931            .child(
13932                div()
13933                    .flex()
13934                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13935                    .flex_shrink(),
13936            )
13937            .child(buttons(&diagnostic, cx.block_id))
13938            .child(div().flex().flex_shrink_0().child(
13939                StyledText::new(text_without_backticks.clone()).with_highlights(
13940                    &text_style,
13941                    code_ranges.iter().map(|range| {
13942                        (
13943                            range.clone(),
13944                            HighlightStyle {
13945                                font_weight: Some(FontWeight::BOLD),
13946                                ..Default::default()
13947                            },
13948                        )
13949                    }),
13950                ),
13951            ))
13952            .into_any_element()
13953    })
13954}
13955
13956pub fn highlight_diagnostic_message(
13957    diagnostic: &Diagnostic,
13958    mut max_message_rows: Option<u8>,
13959) -> (SharedString, Vec<Range<usize>>) {
13960    let mut text_without_backticks = String::new();
13961    let mut code_ranges = Vec::new();
13962
13963    if let Some(source) = &diagnostic.source {
13964        text_without_backticks.push_str(source);
13965        code_ranges.push(0..source.len());
13966        text_without_backticks.push_str(": ");
13967    }
13968
13969    let mut prev_offset = 0;
13970    let mut in_code_block = false;
13971    let has_row_limit = max_message_rows.is_some();
13972    let mut newline_indices = diagnostic
13973        .message
13974        .match_indices('\n')
13975        .filter(|_| has_row_limit)
13976        .map(|(ix, _)| ix)
13977        .fuse()
13978        .peekable();
13979
13980    for (quote_ix, _) in diagnostic
13981        .message
13982        .match_indices('`')
13983        .chain([(diagnostic.message.len(), "")])
13984    {
13985        let mut first_newline_ix = None;
13986        let mut last_newline_ix = None;
13987        while let Some(newline_ix) = newline_indices.peek() {
13988            if *newline_ix < quote_ix {
13989                if first_newline_ix.is_none() {
13990                    first_newline_ix = Some(*newline_ix);
13991                }
13992                last_newline_ix = Some(*newline_ix);
13993
13994                if let Some(rows_left) = &mut max_message_rows {
13995                    if *rows_left == 0 {
13996                        break;
13997                    } else {
13998                        *rows_left -= 1;
13999                    }
14000                }
14001                let _ = newline_indices.next();
14002            } else {
14003                break;
14004            }
14005        }
14006        let prev_len = text_without_backticks.len();
14007        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14008        text_without_backticks.push_str(new_text);
14009        if in_code_block {
14010            code_ranges.push(prev_len..text_without_backticks.len());
14011        }
14012        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14013        in_code_block = !in_code_block;
14014        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14015            text_without_backticks.push_str("...");
14016            break;
14017        }
14018    }
14019
14020    (text_without_backticks.into(), code_ranges)
14021}
14022
14023fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14024    match severity {
14025        DiagnosticSeverity::ERROR => colors.error,
14026        DiagnosticSeverity::WARNING => colors.warning,
14027        DiagnosticSeverity::INFORMATION => colors.info,
14028        DiagnosticSeverity::HINT => colors.info,
14029        _ => colors.ignored,
14030    }
14031}
14032
14033pub fn styled_runs_for_code_label<'a>(
14034    label: &'a CodeLabel,
14035    syntax_theme: &'a theme::SyntaxTheme,
14036) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14037    let fade_out = HighlightStyle {
14038        fade_out: Some(0.35),
14039        ..Default::default()
14040    };
14041
14042    let mut prev_end = label.filter_range.end;
14043    label
14044        .runs
14045        .iter()
14046        .enumerate()
14047        .flat_map(move |(ix, (range, highlight_id))| {
14048            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14049                style
14050            } else {
14051                return Default::default();
14052            };
14053            let mut muted_style = style;
14054            muted_style.highlight(fade_out);
14055
14056            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14057            if range.start >= label.filter_range.end {
14058                if range.start > prev_end {
14059                    runs.push((prev_end..range.start, fade_out));
14060                }
14061                runs.push((range.clone(), muted_style));
14062            } else if range.end <= label.filter_range.end {
14063                runs.push((range.clone(), style));
14064            } else {
14065                runs.push((range.start..label.filter_range.end, style));
14066                runs.push((label.filter_range.end..range.end, muted_style));
14067            }
14068            prev_end = cmp::max(prev_end, range.end);
14069
14070            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14071                runs.push((prev_end..label.text.len(), fade_out));
14072            }
14073
14074            runs
14075        })
14076}
14077
14078pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14079    let mut prev_index = 0;
14080    let mut prev_codepoint: Option<char> = None;
14081    text.char_indices()
14082        .chain([(text.len(), '\0')])
14083        .filter_map(move |(index, codepoint)| {
14084            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14085            let is_boundary = index == text.len()
14086                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14087                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14088            if is_boundary {
14089                let chunk = &text[prev_index..index];
14090                prev_index = index;
14091                Some(chunk)
14092            } else {
14093                None
14094            }
14095        })
14096}
14097
14098pub trait RangeToAnchorExt: Sized {
14099    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14100
14101    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14102        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14103        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14104    }
14105}
14106
14107impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14108    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14109        let start_offset = self.start.to_offset(snapshot);
14110        let end_offset = self.end.to_offset(snapshot);
14111        if start_offset == end_offset {
14112            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14113        } else {
14114            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14115        }
14116    }
14117}
14118
14119pub trait RowExt {
14120    fn as_f32(&self) -> f32;
14121
14122    fn next_row(&self) -> Self;
14123
14124    fn previous_row(&self) -> Self;
14125
14126    fn minus(&self, other: Self) -> u32;
14127}
14128
14129impl RowExt for DisplayRow {
14130    fn as_f32(&self) -> f32 {
14131        self.0 as f32
14132    }
14133
14134    fn next_row(&self) -> Self {
14135        Self(self.0 + 1)
14136    }
14137
14138    fn previous_row(&self) -> Self {
14139        Self(self.0.saturating_sub(1))
14140    }
14141
14142    fn minus(&self, other: Self) -> u32 {
14143        self.0 - other.0
14144    }
14145}
14146
14147impl RowExt for MultiBufferRow {
14148    fn as_f32(&self) -> f32 {
14149        self.0 as f32
14150    }
14151
14152    fn next_row(&self) -> Self {
14153        Self(self.0 + 1)
14154    }
14155
14156    fn previous_row(&self) -> Self {
14157        Self(self.0.saturating_sub(1))
14158    }
14159
14160    fn minus(&self, other: Self) -> u32 {
14161        self.0 - other.0
14162    }
14163}
14164
14165trait RowRangeExt {
14166    type Row;
14167
14168    fn len(&self) -> usize;
14169
14170    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14171}
14172
14173impl RowRangeExt for Range<MultiBufferRow> {
14174    type Row = MultiBufferRow;
14175
14176    fn len(&self) -> usize {
14177        (self.end.0 - self.start.0) as usize
14178    }
14179
14180    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14181        (self.start.0..self.end.0).map(MultiBufferRow)
14182    }
14183}
14184
14185impl RowRangeExt for Range<DisplayRow> {
14186    type Row = DisplayRow;
14187
14188    fn len(&self) -> usize {
14189        (self.end.0 - self.start.0) as usize
14190    }
14191
14192    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14193        (self.start.0..self.end.0).map(DisplayRow)
14194    }
14195}
14196
14197fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14198    if hunk.diff_base_byte_range.is_empty() {
14199        DiffHunkStatus::Added
14200    } else if hunk.row_range.is_empty() {
14201        DiffHunkStatus::Removed
14202    } else {
14203        DiffHunkStatus::Modified
14204    }
14205}
14206
14207/// If select range has more than one line, we
14208/// just point the cursor to range.start.
14209fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14210    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14211        range
14212    } else {
14213        range.start..range.start
14214    }
14215}