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        let mut ranges_by_buffer = HashMap::default();
 6217        self.transact(cx, |editor, cx| {
 6218            for hunk in hunks {
 6219                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
 6220                    ranges_by_buffer
 6221                        .entry(buffer.clone())
 6222                        .or_insert_with(Vec::new)
 6223                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
 6224                }
 6225            }
 6226
 6227            for (buffer, ranges) in ranges_by_buffer {
 6228                buffer.update(cx, |buffer, cx| {
 6229                    buffer.merge_into_base(ranges, cx);
 6230                });
 6231            }
 6232        });
 6233    }
 6234
 6235    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6236        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6237            let project_path = buffer.read(cx).project_path(cx)?;
 6238            let project = self.project.as_ref()?.read(cx);
 6239            let entry = project.entry_for_path(&project_path, cx)?;
 6240            let abs_path = project.absolute_path(&project_path, cx)?;
 6241            let parent = if entry.is_symlink {
 6242                abs_path.canonicalize().ok()?
 6243            } else {
 6244                abs_path
 6245            }
 6246            .parent()?
 6247            .to_path_buf();
 6248            Some(parent)
 6249        }) {
 6250            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6251        }
 6252    }
 6253
 6254    fn gather_revert_changes(
 6255        &mut self,
 6256        selections: &[Selection<Anchor>],
 6257        cx: &mut ViewContext<'_, Editor>,
 6258    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6259        let mut revert_changes = HashMap::default();
 6260        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6261        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6262            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6263        }
 6264        revert_changes
 6265    }
 6266
 6267    pub fn prepare_revert_change(
 6268        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6269        multi_buffer: &Model<MultiBuffer>,
 6270        hunk: &MultiBufferDiffHunk,
 6271        cx: &AppContext,
 6272    ) -> Option<()> {
 6273        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6274        let buffer = buffer.read(cx);
 6275        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6276        let buffer_snapshot = buffer.snapshot();
 6277        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6278        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6279            probe
 6280                .0
 6281                .start
 6282                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6283                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6284        }) {
 6285            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6286            Some(())
 6287        } else {
 6288            None
 6289        }
 6290    }
 6291
 6292    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6293        self.manipulate_lines(cx, |lines| lines.reverse())
 6294    }
 6295
 6296    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6297        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6298    }
 6299
 6300    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6301    where
 6302        Fn: FnMut(&mut Vec<&str>),
 6303    {
 6304        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6305        let buffer = self.buffer.read(cx).snapshot(cx);
 6306
 6307        let mut edits = Vec::new();
 6308
 6309        let selections = self.selections.all::<Point>(cx);
 6310        let mut selections = selections.iter().peekable();
 6311        let mut contiguous_row_selections = Vec::new();
 6312        let mut new_selections = Vec::new();
 6313        let mut added_lines = 0;
 6314        let mut removed_lines = 0;
 6315
 6316        while let Some(selection) = selections.next() {
 6317            let (start_row, end_row) = consume_contiguous_rows(
 6318                &mut contiguous_row_selections,
 6319                selection,
 6320                &display_map,
 6321                &mut selections,
 6322            );
 6323
 6324            let start_point = Point::new(start_row.0, 0);
 6325            let end_point = Point::new(
 6326                end_row.previous_row().0,
 6327                buffer.line_len(end_row.previous_row()),
 6328            );
 6329            let text = buffer
 6330                .text_for_range(start_point..end_point)
 6331                .collect::<String>();
 6332
 6333            let mut lines = text.split('\n').collect_vec();
 6334
 6335            let lines_before = lines.len();
 6336            callback(&mut lines);
 6337            let lines_after = lines.len();
 6338
 6339            edits.push((start_point..end_point, lines.join("\n")));
 6340
 6341            // Selections must change based on added and removed line count
 6342            let start_row =
 6343                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6344            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6345            new_selections.push(Selection {
 6346                id: selection.id,
 6347                start: start_row,
 6348                end: end_row,
 6349                goal: SelectionGoal::None,
 6350                reversed: selection.reversed,
 6351            });
 6352
 6353            if lines_after > lines_before {
 6354                added_lines += lines_after - lines_before;
 6355            } else if lines_before > lines_after {
 6356                removed_lines += lines_before - lines_after;
 6357            }
 6358        }
 6359
 6360        self.transact(cx, |this, cx| {
 6361            let buffer = this.buffer.update(cx, |buffer, cx| {
 6362                buffer.edit(edits, None, cx);
 6363                buffer.snapshot(cx)
 6364            });
 6365
 6366            // Recalculate offsets on newly edited buffer
 6367            let new_selections = new_selections
 6368                .iter()
 6369                .map(|s| {
 6370                    let start_point = Point::new(s.start.0, 0);
 6371                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6372                    Selection {
 6373                        id: s.id,
 6374                        start: buffer.point_to_offset(start_point),
 6375                        end: buffer.point_to_offset(end_point),
 6376                        goal: s.goal,
 6377                        reversed: s.reversed,
 6378                    }
 6379                })
 6380                .collect();
 6381
 6382            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6383                s.select(new_selections);
 6384            });
 6385
 6386            this.request_autoscroll(Autoscroll::fit(), cx);
 6387        });
 6388    }
 6389
 6390    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6391        self.manipulate_text(cx, |text| text.to_uppercase())
 6392    }
 6393
 6394    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6395        self.manipulate_text(cx, |text| text.to_lowercase())
 6396    }
 6397
 6398    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6399        self.manipulate_text(cx, |text| {
 6400            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6401            // https://github.com/rutrum/convert-case/issues/16
 6402            text.split('\n')
 6403                .map(|line| line.to_case(Case::Title))
 6404                .join("\n")
 6405        })
 6406    }
 6407
 6408    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6409        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6410    }
 6411
 6412    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6413        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6414    }
 6415
 6416    pub fn convert_to_upper_camel_case(
 6417        &mut self,
 6418        _: &ConvertToUpperCamelCase,
 6419        cx: &mut ViewContext<Self>,
 6420    ) {
 6421        self.manipulate_text(cx, |text| {
 6422            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6423            // https://github.com/rutrum/convert-case/issues/16
 6424            text.split('\n')
 6425                .map(|line| line.to_case(Case::UpperCamel))
 6426                .join("\n")
 6427        })
 6428    }
 6429
 6430    pub fn convert_to_lower_camel_case(
 6431        &mut self,
 6432        _: &ConvertToLowerCamelCase,
 6433        cx: &mut ViewContext<Self>,
 6434    ) {
 6435        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6436    }
 6437
 6438    pub fn convert_to_opposite_case(
 6439        &mut self,
 6440        _: &ConvertToOppositeCase,
 6441        cx: &mut ViewContext<Self>,
 6442    ) {
 6443        self.manipulate_text(cx, |text| {
 6444            text.chars()
 6445                .fold(String::with_capacity(text.len()), |mut t, c| {
 6446                    if c.is_uppercase() {
 6447                        t.extend(c.to_lowercase());
 6448                    } else {
 6449                        t.extend(c.to_uppercase());
 6450                    }
 6451                    t
 6452                })
 6453        })
 6454    }
 6455
 6456    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6457    where
 6458        Fn: FnMut(&str) -> String,
 6459    {
 6460        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6461        let buffer = self.buffer.read(cx).snapshot(cx);
 6462
 6463        let mut new_selections = Vec::new();
 6464        let mut edits = Vec::new();
 6465        let mut selection_adjustment = 0i32;
 6466
 6467        for selection in self.selections.all::<usize>(cx) {
 6468            let selection_is_empty = selection.is_empty();
 6469
 6470            let (start, end) = if selection_is_empty {
 6471                let word_range = movement::surrounding_word(
 6472                    &display_map,
 6473                    selection.start.to_display_point(&display_map),
 6474                );
 6475                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6476                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6477                (start, end)
 6478            } else {
 6479                (selection.start, selection.end)
 6480            };
 6481
 6482            let text = buffer.text_for_range(start..end).collect::<String>();
 6483            let old_length = text.len() as i32;
 6484            let text = callback(&text);
 6485
 6486            new_selections.push(Selection {
 6487                start: (start as i32 - selection_adjustment) as usize,
 6488                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6489                goal: SelectionGoal::None,
 6490                ..selection
 6491            });
 6492
 6493            selection_adjustment += old_length - text.len() as i32;
 6494
 6495            edits.push((start..end, text));
 6496        }
 6497
 6498        self.transact(cx, |this, cx| {
 6499            this.buffer.update(cx, |buffer, cx| {
 6500                buffer.edit(edits, None, cx);
 6501            });
 6502
 6503            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6504                s.select(new_selections);
 6505            });
 6506
 6507            this.request_autoscroll(Autoscroll::fit(), cx);
 6508        });
 6509    }
 6510
 6511    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6512        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6513        let buffer = &display_map.buffer_snapshot;
 6514        let selections = self.selections.all::<Point>(cx);
 6515
 6516        let mut edits = Vec::new();
 6517        let mut selections_iter = selections.iter().peekable();
 6518        while let Some(selection) = selections_iter.next() {
 6519            // Avoid duplicating the same lines twice.
 6520            let mut rows = selection.spanned_rows(false, &display_map);
 6521
 6522            while let Some(next_selection) = selections_iter.peek() {
 6523                let next_rows = next_selection.spanned_rows(false, &display_map);
 6524                if next_rows.start < rows.end {
 6525                    rows.end = next_rows.end;
 6526                    selections_iter.next().unwrap();
 6527                } else {
 6528                    break;
 6529                }
 6530            }
 6531
 6532            // Copy the text from the selected row region and splice it either at the start
 6533            // or end of the region.
 6534            let start = Point::new(rows.start.0, 0);
 6535            let end = Point::new(
 6536                rows.end.previous_row().0,
 6537                buffer.line_len(rows.end.previous_row()),
 6538            );
 6539            let text = buffer
 6540                .text_for_range(start..end)
 6541                .chain(Some("\n"))
 6542                .collect::<String>();
 6543            let insert_location = if upwards {
 6544                Point::new(rows.end.0, 0)
 6545            } else {
 6546                start
 6547            };
 6548            edits.push((insert_location..insert_location, text));
 6549        }
 6550
 6551        self.transact(cx, |this, cx| {
 6552            this.buffer.update(cx, |buffer, cx| {
 6553                buffer.edit(edits, None, cx);
 6554            });
 6555
 6556            this.request_autoscroll(Autoscroll::fit(), cx);
 6557        });
 6558    }
 6559
 6560    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6561        self.duplicate_line(true, cx);
 6562    }
 6563
 6564    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6565        self.duplicate_line(false, cx);
 6566    }
 6567
 6568    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6569        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6570        let buffer = self.buffer.read(cx).snapshot(cx);
 6571
 6572        let mut edits = Vec::new();
 6573        let mut unfold_ranges = Vec::new();
 6574        let mut refold_ranges = Vec::new();
 6575
 6576        let selections = self.selections.all::<Point>(cx);
 6577        let mut selections = selections.iter().peekable();
 6578        let mut contiguous_row_selections = Vec::new();
 6579        let mut new_selections = Vec::new();
 6580
 6581        while let Some(selection) = selections.next() {
 6582            // Find all the selections that span a contiguous row range
 6583            let (start_row, end_row) = consume_contiguous_rows(
 6584                &mut contiguous_row_selections,
 6585                selection,
 6586                &display_map,
 6587                &mut selections,
 6588            );
 6589
 6590            // Move the text spanned by the row range to be before the line preceding the row range
 6591            if start_row.0 > 0 {
 6592                let range_to_move = Point::new(
 6593                    start_row.previous_row().0,
 6594                    buffer.line_len(start_row.previous_row()),
 6595                )
 6596                    ..Point::new(
 6597                        end_row.previous_row().0,
 6598                        buffer.line_len(end_row.previous_row()),
 6599                    );
 6600                let insertion_point = display_map
 6601                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6602                    .0;
 6603
 6604                // Don't move lines across excerpts
 6605                if buffer
 6606                    .excerpt_boundaries_in_range((
 6607                        Bound::Excluded(insertion_point),
 6608                        Bound::Included(range_to_move.end),
 6609                    ))
 6610                    .next()
 6611                    .is_none()
 6612                {
 6613                    let text = buffer
 6614                        .text_for_range(range_to_move.clone())
 6615                        .flat_map(|s| s.chars())
 6616                        .skip(1)
 6617                        .chain(['\n'])
 6618                        .collect::<String>();
 6619
 6620                    edits.push((
 6621                        buffer.anchor_after(range_to_move.start)
 6622                            ..buffer.anchor_before(range_to_move.end),
 6623                        String::new(),
 6624                    ));
 6625                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6626                    edits.push((insertion_anchor..insertion_anchor, text));
 6627
 6628                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6629
 6630                    // Move selections up
 6631                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6632                        |mut selection| {
 6633                            selection.start.row -= row_delta;
 6634                            selection.end.row -= row_delta;
 6635                            selection
 6636                        },
 6637                    ));
 6638
 6639                    // Move folds up
 6640                    unfold_ranges.push(range_to_move.clone());
 6641                    for fold in display_map.folds_in_range(
 6642                        buffer.anchor_before(range_to_move.start)
 6643                            ..buffer.anchor_after(range_to_move.end),
 6644                    ) {
 6645                        let mut start = fold.range.start.to_point(&buffer);
 6646                        let mut end = fold.range.end.to_point(&buffer);
 6647                        start.row -= row_delta;
 6648                        end.row -= row_delta;
 6649                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6650                    }
 6651                }
 6652            }
 6653
 6654            // If we didn't move line(s), preserve the existing selections
 6655            new_selections.append(&mut contiguous_row_selections);
 6656        }
 6657
 6658        self.transact(cx, |this, cx| {
 6659            this.unfold_ranges(unfold_ranges, true, true, cx);
 6660            this.buffer.update(cx, |buffer, cx| {
 6661                for (range, text) in edits {
 6662                    buffer.edit([(range, text)], None, cx);
 6663                }
 6664            });
 6665            this.fold_ranges(refold_ranges, true, cx);
 6666            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6667                s.select(new_selections);
 6668            })
 6669        });
 6670    }
 6671
 6672    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6673        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6674        let buffer = self.buffer.read(cx).snapshot(cx);
 6675
 6676        let mut edits = Vec::new();
 6677        let mut unfold_ranges = Vec::new();
 6678        let mut refold_ranges = Vec::new();
 6679
 6680        let selections = self.selections.all::<Point>(cx);
 6681        let mut selections = selections.iter().peekable();
 6682        let mut contiguous_row_selections = Vec::new();
 6683        let mut new_selections = Vec::new();
 6684
 6685        while let Some(selection) = selections.next() {
 6686            // Find all the selections that span a contiguous row range
 6687            let (start_row, end_row) = consume_contiguous_rows(
 6688                &mut contiguous_row_selections,
 6689                selection,
 6690                &display_map,
 6691                &mut selections,
 6692            );
 6693
 6694            // Move the text spanned by the row range to be after the last line of the row range
 6695            if end_row.0 <= buffer.max_point().row {
 6696                let range_to_move =
 6697                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6698                let insertion_point = display_map
 6699                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6700                    .0;
 6701
 6702                // Don't move lines across excerpt boundaries
 6703                if buffer
 6704                    .excerpt_boundaries_in_range((
 6705                        Bound::Excluded(range_to_move.start),
 6706                        Bound::Included(insertion_point),
 6707                    ))
 6708                    .next()
 6709                    .is_none()
 6710                {
 6711                    let mut text = String::from("\n");
 6712                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6713                    text.pop(); // Drop trailing newline
 6714                    edits.push((
 6715                        buffer.anchor_after(range_to_move.start)
 6716                            ..buffer.anchor_before(range_to_move.end),
 6717                        String::new(),
 6718                    ));
 6719                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6720                    edits.push((insertion_anchor..insertion_anchor, text));
 6721
 6722                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6723
 6724                    // Move selections down
 6725                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6726                        |mut selection| {
 6727                            selection.start.row += row_delta;
 6728                            selection.end.row += row_delta;
 6729                            selection
 6730                        },
 6731                    ));
 6732
 6733                    // Move folds down
 6734                    unfold_ranges.push(range_to_move.clone());
 6735                    for fold in display_map.folds_in_range(
 6736                        buffer.anchor_before(range_to_move.start)
 6737                            ..buffer.anchor_after(range_to_move.end),
 6738                    ) {
 6739                        let mut start = fold.range.start.to_point(&buffer);
 6740                        let mut end = fold.range.end.to_point(&buffer);
 6741                        start.row += row_delta;
 6742                        end.row += row_delta;
 6743                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6744                    }
 6745                }
 6746            }
 6747
 6748            // If we didn't move line(s), preserve the existing selections
 6749            new_selections.append(&mut contiguous_row_selections);
 6750        }
 6751
 6752        self.transact(cx, |this, cx| {
 6753            this.unfold_ranges(unfold_ranges, true, true, cx);
 6754            this.buffer.update(cx, |buffer, cx| {
 6755                for (range, text) in edits {
 6756                    buffer.edit([(range, text)], None, cx);
 6757                }
 6758            });
 6759            this.fold_ranges(refold_ranges, true, cx);
 6760            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6761        });
 6762    }
 6763
 6764    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6765        let text_layout_details = &self.text_layout_details(cx);
 6766        self.transact(cx, |this, cx| {
 6767            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6768                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6769                let line_mode = s.line_mode;
 6770                s.move_with(|display_map, selection| {
 6771                    if !selection.is_empty() || line_mode {
 6772                        return;
 6773                    }
 6774
 6775                    let mut head = selection.head();
 6776                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6777                    if head.column() == display_map.line_len(head.row()) {
 6778                        transpose_offset = display_map
 6779                            .buffer_snapshot
 6780                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6781                    }
 6782
 6783                    if transpose_offset == 0 {
 6784                        return;
 6785                    }
 6786
 6787                    *head.column_mut() += 1;
 6788                    head = display_map.clip_point(head, Bias::Right);
 6789                    let goal = SelectionGoal::HorizontalPosition(
 6790                        display_map
 6791                            .x_for_display_point(head, text_layout_details)
 6792                            .into(),
 6793                    );
 6794                    selection.collapse_to(head, goal);
 6795
 6796                    let transpose_start = display_map
 6797                        .buffer_snapshot
 6798                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6799                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6800                        let transpose_end = display_map
 6801                            .buffer_snapshot
 6802                            .clip_offset(transpose_offset + 1, Bias::Right);
 6803                        if let Some(ch) =
 6804                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6805                        {
 6806                            edits.push((transpose_start..transpose_offset, String::new()));
 6807                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6808                        }
 6809                    }
 6810                });
 6811                edits
 6812            });
 6813            this.buffer
 6814                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6815            let selections = this.selections.all::<usize>(cx);
 6816            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6817                s.select(selections);
 6818            });
 6819        });
 6820    }
 6821
 6822    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6823        self.rewrap_impl(true, cx)
 6824    }
 6825
 6826    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6827        let buffer = self.buffer.read(cx).snapshot(cx);
 6828        let selections = self.selections.all::<Point>(cx);
 6829        let mut selections = selections.iter().peekable();
 6830
 6831        let mut edits = Vec::new();
 6832        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6833
 6834        while let Some(selection) = selections.next() {
 6835            let mut start_row = selection.start.row;
 6836            let mut end_row = selection.end.row;
 6837
 6838            // Skip selections that overlap with a range that has already been rewrapped.
 6839            let selection_range = start_row..end_row;
 6840            if rewrapped_row_ranges
 6841                .iter()
 6842                .any(|range| range.overlaps(&selection_range))
 6843            {
 6844                continue;
 6845            }
 6846
 6847            let mut should_rewrap = !only_text;
 6848
 6849            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6850                match language_scope.language_name().0.as_ref() {
 6851                    "Markdown" | "Plain Text" => {
 6852                        should_rewrap = true;
 6853                    }
 6854                    _ => {}
 6855                }
 6856            }
 6857
 6858            // Since not all lines in the selection may be at the same indent
 6859            // level, choose the indent size that is the most common between all
 6860            // of the lines.
 6861            //
 6862            // If there is a tie, we use the deepest indent.
 6863            let (indent_size, indent_end) = {
 6864                let mut indent_size_occurrences = HashMap::default();
 6865                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6866
 6867                for row in start_row..=end_row {
 6868                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6869                    rows_by_indent_size.entry(indent).or_default().push(row);
 6870                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6871                }
 6872
 6873                let indent_size = indent_size_occurrences
 6874                    .into_iter()
 6875                    .max_by_key(|(indent, count)| (*count, indent.len))
 6876                    .map(|(indent, _)| indent)
 6877                    .unwrap_or_default();
 6878                let row = rows_by_indent_size[&indent_size][0];
 6879                let indent_end = Point::new(row, indent_size.len);
 6880
 6881                (indent_size, indent_end)
 6882            };
 6883
 6884            let mut line_prefix = indent_size.chars().collect::<String>();
 6885
 6886            if let Some(comment_prefix) =
 6887                buffer
 6888                    .language_scope_at(selection.head())
 6889                    .and_then(|language| {
 6890                        language
 6891                            .line_comment_prefixes()
 6892                            .iter()
 6893                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6894                            .cloned()
 6895                    })
 6896            {
 6897                line_prefix.push_str(&comment_prefix);
 6898                should_rewrap = true;
 6899            }
 6900
 6901            if selection.is_empty() {
 6902                'expand_upwards: while start_row > 0 {
 6903                    let prev_row = start_row - 1;
 6904                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6905                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6906                    {
 6907                        start_row = prev_row;
 6908                    } else {
 6909                        break 'expand_upwards;
 6910                    }
 6911                }
 6912
 6913                'expand_downwards: while end_row < buffer.max_point().row {
 6914                    let next_row = end_row + 1;
 6915                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6916                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6917                    {
 6918                        end_row = next_row;
 6919                    } else {
 6920                        break 'expand_downwards;
 6921                    }
 6922                }
 6923            }
 6924
 6925            if !should_rewrap {
 6926                continue;
 6927            }
 6928
 6929            let start = Point::new(start_row, 0);
 6930            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6931            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6932            let Some(lines_without_prefixes) = selection_text
 6933                .lines()
 6934                .map(|line| {
 6935                    line.strip_prefix(&line_prefix)
 6936                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6937                        .ok_or_else(|| {
 6938                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6939                        })
 6940                })
 6941                .collect::<Result<Vec<_>, _>>()
 6942                .log_err()
 6943            else {
 6944                continue;
 6945            };
 6946
 6947            let unwrapped_text = lines_without_prefixes.join(" ");
 6948            let wrap_column = buffer
 6949                .settings_at(Point::new(start_row, 0), cx)
 6950                .preferred_line_length as usize;
 6951            let mut wrapped_text = String::new();
 6952            let mut current_line = line_prefix.clone();
 6953            for word in unwrapped_text.split_whitespace() {
 6954                if current_line.len() + word.len() >= wrap_column {
 6955                    wrapped_text.push_str(&current_line);
 6956                    wrapped_text.push('\n');
 6957                    current_line.truncate(line_prefix.len());
 6958                }
 6959
 6960                if current_line.len() > line_prefix.len() {
 6961                    current_line.push(' ');
 6962                }
 6963
 6964                current_line.push_str(word);
 6965            }
 6966
 6967            if !current_line.is_empty() {
 6968                wrapped_text.push_str(&current_line);
 6969            }
 6970
 6971            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 6972            let mut offset = start.to_offset(&buffer);
 6973            let mut moved_since_edit = true;
 6974
 6975            for change in diff.iter_all_changes() {
 6976                let value = change.value();
 6977                match change.tag() {
 6978                    ChangeTag::Equal => {
 6979                        offset += value.len();
 6980                        moved_since_edit = true;
 6981                    }
 6982                    ChangeTag::Delete => {
 6983                        let start = buffer.anchor_after(offset);
 6984                        let end = buffer.anchor_before(offset + value.len());
 6985
 6986                        if moved_since_edit {
 6987                            edits.push((start..end, String::new()));
 6988                        } else {
 6989                            edits.last_mut().unwrap().0.end = end;
 6990                        }
 6991
 6992                        offset += value.len();
 6993                        moved_since_edit = false;
 6994                    }
 6995                    ChangeTag::Insert => {
 6996                        if moved_since_edit {
 6997                            let anchor = buffer.anchor_after(offset);
 6998                            edits.push((anchor..anchor, value.to_string()));
 6999                        } else {
 7000                            edits.last_mut().unwrap().1.push_str(value);
 7001                        }
 7002
 7003                        moved_since_edit = false;
 7004                    }
 7005                }
 7006            }
 7007
 7008            rewrapped_row_ranges.push(start_row..=end_row);
 7009        }
 7010
 7011        self.buffer
 7012            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7013    }
 7014
 7015    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7016        let mut text = String::new();
 7017        let buffer = self.buffer.read(cx).snapshot(cx);
 7018        let mut selections = self.selections.all::<Point>(cx);
 7019        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7020        {
 7021            let max_point = buffer.max_point();
 7022            let mut is_first = true;
 7023            for selection in &mut selections {
 7024                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7025                if is_entire_line {
 7026                    selection.start = Point::new(selection.start.row, 0);
 7027                    if !selection.is_empty() && selection.end.column == 0 {
 7028                        selection.end = cmp::min(max_point, selection.end);
 7029                    } else {
 7030                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7031                    }
 7032                    selection.goal = SelectionGoal::None;
 7033                }
 7034                if is_first {
 7035                    is_first = false;
 7036                } else {
 7037                    text += "\n";
 7038                }
 7039                let mut len = 0;
 7040                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7041                    text.push_str(chunk);
 7042                    len += chunk.len();
 7043                }
 7044                clipboard_selections.push(ClipboardSelection {
 7045                    len,
 7046                    is_entire_line,
 7047                    first_line_indent: buffer
 7048                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7049                        .len,
 7050                });
 7051            }
 7052        }
 7053
 7054        self.transact(cx, |this, cx| {
 7055            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7056                s.select(selections);
 7057            });
 7058            this.insert("", cx);
 7059            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7060                text,
 7061                clipboard_selections,
 7062            ));
 7063        });
 7064    }
 7065
 7066    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7067        let selections = self.selections.all::<Point>(cx);
 7068        let buffer = self.buffer.read(cx).read(cx);
 7069        let mut text = String::new();
 7070
 7071        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7072        {
 7073            let max_point = buffer.max_point();
 7074            let mut is_first = true;
 7075            for selection in selections.iter() {
 7076                let mut start = selection.start;
 7077                let mut end = selection.end;
 7078                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7079                if is_entire_line {
 7080                    start = Point::new(start.row, 0);
 7081                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7082                }
 7083                if is_first {
 7084                    is_first = false;
 7085                } else {
 7086                    text += "\n";
 7087                }
 7088                let mut len = 0;
 7089                for chunk in buffer.text_for_range(start..end) {
 7090                    text.push_str(chunk);
 7091                    len += chunk.len();
 7092                }
 7093                clipboard_selections.push(ClipboardSelection {
 7094                    len,
 7095                    is_entire_line,
 7096                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7097                });
 7098            }
 7099        }
 7100
 7101        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7102            text,
 7103            clipboard_selections,
 7104        ));
 7105    }
 7106
 7107    pub fn do_paste(
 7108        &mut self,
 7109        text: &String,
 7110        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7111        handle_entire_lines: bool,
 7112        cx: &mut ViewContext<Self>,
 7113    ) {
 7114        if self.read_only(cx) {
 7115            return;
 7116        }
 7117
 7118        let clipboard_text = Cow::Borrowed(text);
 7119
 7120        self.transact(cx, |this, cx| {
 7121            if let Some(mut clipboard_selections) = clipboard_selections {
 7122                let old_selections = this.selections.all::<usize>(cx);
 7123                let all_selections_were_entire_line =
 7124                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7125                let first_selection_indent_column =
 7126                    clipboard_selections.first().map(|s| s.first_line_indent);
 7127                if clipboard_selections.len() != old_selections.len() {
 7128                    clipboard_selections.drain(..);
 7129                }
 7130
 7131                this.buffer.update(cx, |buffer, cx| {
 7132                    let snapshot = buffer.read(cx);
 7133                    let mut start_offset = 0;
 7134                    let mut edits = Vec::new();
 7135                    let mut original_indent_columns = Vec::new();
 7136                    for (ix, selection) in old_selections.iter().enumerate() {
 7137                        let to_insert;
 7138                        let entire_line;
 7139                        let original_indent_column;
 7140                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7141                            let end_offset = start_offset + clipboard_selection.len;
 7142                            to_insert = &clipboard_text[start_offset..end_offset];
 7143                            entire_line = clipboard_selection.is_entire_line;
 7144                            start_offset = end_offset + 1;
 7145                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7146                        } else {
 7147                            to_insert = clipboard_text.as_str();
 7148                            entire_line = all_selections_were_entire_line;
 7149                            original_indent_column = first_selection_indent_column
 7150                        }
 7151
 7152                        // If the corresponding selection was empty when this slice of the
 7153                        // clipboard text was written, then the entire line containing the
 7154                        // selection was copied. If this selection is also currently empty,
 7155                        // then paste the line before the current line of the buffer.
 7156                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7157                            let column = selection.start.to_point(&snapshot).column as usize;
 7158                            let line_start = selection.start - column;
 7159                            line_start..line_start
 7160                        } else {
 7161                            selection.range()
 7162                        };
 7163
 7164                        edits.push((range, to_insert));
 7165                        original_indent_columns.extend(original_indent_column);
 7166                    }
 7167                    drop(snapshot);
 7168
 7169                    buffer.edit(
 7170                        edits,
 7171                        Some(AutoindentMode::Block {
 7172                            original_indent_columns,
 7173                        }),
 7174                        cx,
 7175                    );
 7176                });
 7177
 7178                let selections = this.selections.all::<usize>(cx);
 7179                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7180            } else {
 7181                this.insert(&clipboard_text, cx);
 7182            }
 7183        });
 7184    }
 7185
 7186    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7187        if let Some(item) = cx.read_from_clipboard() {
 7188            let entries = item.entries();
 7189
 7190            match entries.first() {
 7191                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7192                // of all the pasted entries.
 7193                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7194                    .do_paste(
 7195                        clipboard_string.text(),
 7196                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7197                        true,
 7198                        cx,
 7199                    ),
 7200                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7201            }
 7202        }
 7203    }
 7204
 7205    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7206        if self.read_only(cx) {
 7207            return;
 7208        }
 7209
 7210        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7211            if let Some((selections, _)) =
 7212                self.selection_history.transaction(transaction_id).cloned()
 7213            {
 7214                self.change_selections(None, cx, |s| {
 7215                    s.select_anchors(selections.to_vec());
 7216                });
 7217            }
 7218            self.request_autoscroll(Autoscroll::fit(), cx);
 7219            self.unmark_text(cx);
 7220            self.refresh_inline_completion(true, false, cx);
 7221            cx.emit(EditorEvent::Edited { transaction_id });
 7222            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7223        }
 7224    }
 7225
 7226    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7227        if self.read_only(cx) {
 7228            return;
 7229        }
 7230
 7231        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7232            if let Some((_, Some(selections))) =
 7233                self.selection_history.transaction(transaction_id).cloned()
 7234            {
 7235                self.change_selections(None, cx, |s| {
 7236                    s.select_anchors(selections.to_vec());
 7237                });
 7238            }
 7239            self.request_autoscroll(Autoscroll::fit(), cx);
 7240            self.unmark_text(cx);
 7241            self.refresh_inline_completion(true, false, cx);
 7242            cx.emit(EditorEvent::Edited { transaction_id });
 7243        }
 7244    }
 7245
 7246    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7247        self.buffer
 7248            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7249    }
 7250
 7251    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7252        self.buffer
 7253            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7254    }
 7255
 7256    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7257        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7258            let line_mode = s.line_mode;
 7259            s.move_with(|map, selection| {
 7260                let cursor = if selection.is_empty() && !line_mode {
 7261                    movement::left(map, selection.start)
 7262                } else {
 7263                    selection.start
 7264                };
 7265                selection.collapse_to(cursor, SelectionGoal::None);
 7266            });
 7267        })
 7268    }
 7269
 7270    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7271        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7272            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7273        })
 7274    }
 7275
 7276    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7277        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7278            let line_mode = s.line_mode;
 7279            s.move_with(|map, selection| {
 7280                let cursor = if selection.is_empty() && !line_mode {
 7281                    movement::right(map, selection.end)
 7282                } else {
 7283                    selection.end
 7284                };
 7285                selection.collapse_to(cursor, SelectionGoal::None)
 7286            });
 7287        })
 7288    }
 7289
 7290    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7291        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7292            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7293        })
 7294    }
 7295
 7296    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7297        if self.take_rename(true, cx).is_some() {
 7298            return;
 7299        }
 7300
 7301        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7302            cx.propagate();
 7303            return;
 7304        }
 7305
 7306        let text_layout_details = &self.text_layout_details(cx);
 7307        let selection_count = self.selections.count();
 7308        let first_selection = self.selections.first_anchor();
 7309
 7310        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7311            let line_mode = s.line_mode;
 7312            s.move_with(|map, selection| {
 7313                if !selection.is_empty() && !line_mode {
 7314                    selection.goal = SelectionGoal::None;
 7315                }
 7316                let (cursor, goal) = movement::up(
 7317                    map,
 7318                    selection.start,
 7319                    selection.goal,
 7320                    false,
 7321                    text_layout_details,
 7322                );
 7323                selection.collapse_to(cursor, goal);
 7324            });
 7325        });
 7326
 7327        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7328        {
 7329            cx.propagate();
 7330        }
 7331    }
 7332
 7333    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7334        if self.take_rename(true, cx).is_some() {
 7335            return;
 7336        }
 7337
 7338        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7339            cx.propagate();
 7340            return;
 7341        }
 7342
 7343        let text_layout_details = &self.text_layout_details(cx);
 7344
 7345        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7346            let line_mode = s.line_mode;
 7347            s.move_with(|map, selection| {
 7348                if !selection.is_empty() && !line_mode {
 7349                    selection.goal = SelectionGoal::None;
 7350                }
 7351                let (cursor, goal) = movement::up_by_rows(
 7352                    map,
 7353                    selection.start,
 7354                    action.lines,
 7355                    selection.goal,
 7356                    false,
 7357                    text_layout_details,
 7358                );
 7359                selection.collapse_to(cursor, goal);
 7360            });
 7361        })
 7362    }
 7363
 7364    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7365        if self.take_rename(true, cx).is_some() {
 7366            return;
 7367        }
 7368
 7369        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7370            cx.propagate();
 7371            return;
 7372        }
 7373
 7374        let text_layout_details = &self.text_layout_details(cx);
 7375
 7376        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7377            let line_mode = s.line_mode;
 7378            s.move_with(|map, selection| {
 7379                if !selection.is_empty() && !line_mode {
 7380                    selection.goal = SelectionGoal::None;
 7381                }
 7382                let (cursor, goal) = movement::down_by_rows(
 7383                    map,
 7384                    selection.start,
 7385                    action.lines,
 7386                    selection.goal,
 7387                    false,
 7388                    text_layout_details,
 7389                );
 7390                selection.collapse_to(cursor, goal);
 7391            });
 7392        })
 7393    }
 7394
 7395    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7396        let text_layout_details = &self.text_layout_details(cx);
 7397        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7398            s.move_heads_with(|map, head, goal| {
 7399                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7400            })
 7401        })
 7402    }
 7403
 7404    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7405        let text_layout_details = &self.text_layout_details(cx);
 7406        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7407            s.move_heads_with(|map, head, goal| {
 7408                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7409            })
 7410        })
 7411    }
 7412
 7413    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7414        let Some(row_count) = self.visible_row_count() else {
 7415            return;
 7416        };
 7417
 7418        let text_layout_details = &self.text_layout_details(cx);
 7419
 7420        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7421            s.move_heads_with(|map, head, goal| {
 7422                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7423            })
 7424        })
 7425    }
 7426
 7427    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7428        if self.take_rename(true, cx).is_some() {
 7429            return;
 7430        }
 7431
 7432        if self
 7433            .context_menu
 7434            .write()
 7435            .as_mut()
 7436            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 7437            .unwrap_or(false)
 7438        {
 7439            return;
 7440        }
 7441
 7442        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7443            cx.propagate();
 7444            return;
 7445        }
 7446
 7447        let Some(row_count) = self.visible_row_count() else {
 7448            return;
 7449        };
 7450
 7451        let autoscroll = if action.center_cursor {
 7452            Autoscroll::center()
 7453        } else {
 7454            Autoscroll::fit()
 7455        };
 7456
 7457        let text_layout_details = &self.text_layout_details(cx);
 7458
 7459        self.change_selections(Some(autoscroll), cx, |s| {
 7460            let line_mode = s.line_mode;
 7461            s.move_with(|map, selection| {
 7462                if !selection.is_empty() && !line_mode {
 7463                    selection.goal = SelectionGoal::None;
 7464                }
 7465                let (cursor, goal) = movement::up_by_rows(
 7466                    map,
 7467                    selection.end,
 7468                    row_count,
 7469                    selection.goal,
 7470                    false,
 7471                    text_layout_details,
 7472                );
 7473                selection.collapse_to(cursor, goal);
 7474            });
 7475        });
 7476    }
 7477
 7478    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7479        let text_layout_details = &self.text_layout_details(cx);
 7480        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7481            s.move_heads_with(|map, head, goal| {
 7482                movement::up(map, head, goal, false, text_layout_details)
 7483            })
 7484        })
 7485    }
 7486
 7487    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7488        self.take_rename(true, cx);
 7489
 7490        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7491            cx.propagate();
 7492            return;
 7493        }
 7494
 7495        let text_layout_details = &self.text_layout_details(cx);
 7496        let selection_count = self.selections.count();
 7497        let first_selection = self.selections.first_anchor();
 7498
 7499        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7500            let line_mode = s.line_mode;
 7501            s.move_with(|map, selection| {
 7502                if !selection.is_empty() && !line_mode {
 7503                    selection.goal = SelectionGoal::None;
 7504                }
 7505                let (cursor, goal) = movement::down(
 7506                    map,
 7507                    selection.end,
 7508                    selection.goal,
 7509                    false,
 7510                    text_layout_details,
 7511                );
 7512                selection.collapse_to(cursor, goal);
 7513            });
 7514        });
 7515
 7516        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7517        {
 7518            cx.propagate();
 7519        }
 7520    }
 7521
 7522    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7523        let Some(row_count) = self.visible_row_count() else {
 7524            return;
 7525        };
 7526
 7527        let text_layout_details = &self.text_layout_details(cx);
 7528
 7529        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7530            s.move_heads_with(|map, head, goal| {
 7531                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7532            })
 7533        })
 7534    }
 7535
 7536    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7537        if self.take_rename(true, cx).is_some() {
 7538            return;
 7539        }
 7540
 7541        if self
 7542            .context_menu
 7543            .write()
 7544            .as_mut()
 7545            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7546            .unwrap_or(false)
 7547        {
 7548            return;
 7549        }
 7550
 7551        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7552            cx.propagate();
 7553            return;
 7554        }
 7555
 7556        let Some(row_count) = self.visible_row_count() else {
 7557            return;
 7558        };
 7559
 7560        let autoscroll = if action.center_cursor {
 7561            Autoscroll::center()
 7562        } else {
 7563            Autoscroll::fit()
 7564        };
 7565
 7566        let text_layout_details = &self.text_layout_details(cx);
 7567        self.change_selections(Some(autoscroll), cx, |s| {
 7568            let line_mode = s.line_mode;
 7569            s.move_with(|map, selection| {
 7570                if !selection.is_empty() && !line_mode {
 7571                    selection.goal = SelectionGoal::None;
 7572                }
 7573                let (cursor, goal) = movement::down_by_rows(
 7574                    map,
 7575                    selection.end,
 7576                    row_count,
 7577                    selection.goal,
 7578                    false,
 7579                    text_layout_details,
 7580                );
 7581                selection.collapse_to(cursor, goal);
 7582            });
 7583        });
 7584    }
 7585
 7586    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7587        let text_layout_details = &self.text_layout_details(cx);
 7588        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7589            s.move_heads_with(|map, head, goal| {
 7590                movement::down(map, head, goal, false, text_layout_details)
 7591            })
 7592        });
 7593    }
 7594
 7595    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7596        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7597            context_menu.select_first(self.project.as_ref(), cx);
 7598        }
 7599    }
 7600
 7601    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7602        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7603            context_menu.select_prev(self.project.as_ref(), cx);
 7604        }
 7605    }
 7606
 7607    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7608        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7609            context_menu.select_next(self.project.as_ref(), cx);
 7610        }
 7611    }
 7612
 7613    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7614        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7615            context_menu.select_last(self.project.as_ref(), cx);
 7616        }
 7617    }
 7618
 7619    pub fn move_to_previous_word_start(
 7620        &mut self,
 7621        _: &MoveToPreviousWordStart,
 7622        cx: &mut ViewContext<Self>,
 7623    ) {
 7624        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7625            s.move_cursors_with(|map, head, _| {
 7626                (
 7627                    movement::previous_word_start(map, head),
 7628                    SelectionGoal::None,
 7629                )
 7630            });
 7631        })
 7632    }
 7633
 7634    pub fn move_to_previous_subword_start(
 7635        &mut self,
 7636        _: &MoveToPreviousSubwordStart,
 7637        cx: &mut ViewContext<Self>,
 7638    ) {
 7639        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7640            s.move_cursors_with(|map, head, _| {
 7641                (
 7642                    movement::previous_subword_start(map, head),
 7643                    SelectionGoal::None,
 7644                )
 7645            });
 7646        })
 7647    }
 7648
 7649    pub fn select_to_previous_word_start(
 7650        &mut self,
 7651        _: &SelectToPreviousWordStart,
 7652        cx: &mut ViewContext<Self>,
 7653    ) {
 7654        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7655            s.move_heads_with(|map, head, _| {
 7656                (
 7657                    movement::previous_word_start(map, head),
 7658                    SelectionGoal::None,
 7659                )
 7660            });
 7661        })
 7662    }
 7663
 7664    pub fn select_to_previous_subword_start(
 7665        &mut self,
 7666        _: &SelectToPreviousSubwordStart,
 7667        cx: &mut ViewContext<Self>,
 7668    ) {
 7669        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7670            s.move_heads_with(|map, head, _| {
 7671                (
 7672                    movement::previous_subword_start(map, head),
 7673                    SelectionGoal::None,
 7674                )
 7675            });
 7676        })
 7677    }
 7678
 7679    pub fn delete_to_previous_word_start(
 7680        &mut self,
 7681        action: &DeleteToPreviousWordStart,
 7682        cx: &mut ViewContext<Self>,
 7683    ) {
 7684        self.transact(cx, |this, cx| {
 7685            this.select_autoclose_pair(cx);
 7686            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7687                let line_mode = s.line_mode;
 7688                s.move_with(|map, selection| {
 7689                    if selection.is_empty() && !line_mode {
 7690                        let cursor = if action.ignore_newlines {
 7691                            movement::previous_word_start(map, selection.head())
 7692                        } else {
 7693                            movement::previous_word_start_or_newline(map, selection.head())
 7694                        };
 7695                        selection.set_head(cursor, SelectionGoal::None);
 7696                    }
 7697                });
 7698            });
 7699            this.insert("", cx);
 7700        });
 7701    }
 7702
 7703    pub fn delete_to_previous_subword_start(
 7704        &mut self,
 7705        _: &DeleteToPreviousSubwordStart,
 7706        cx: &mut ViewContext<Self>,
 7707    ) {
 7708        self.transact(cx, |this, cx| {
 7709            this.select_autoclose_pair(cx);
 7710            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7711                let line_mode = s.line_mode;
 7712                s.move_with(|map, selection| {
 7713                    if selection.is_empty() && !line_mode {
 7714                        let cursor = movement::previous_subword_start(map, selection.head());
 7715                        selection.set_head(cursor, SelectionGoal::None);
 7716                    }
 7717                });
 7718            });
 7719            this.insert("", cx);
 7720        });
 7721    }
 7722
 7723    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7724        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7725            s.move_cursors_with(|map, head, _| {
 7726                (movement::next_word_end(map, head), SelectionGoal::None)
 7727            });
 7728        })
 7729    }
 7730
 7731    pub fn move_to_next_subword_end(
 7732        &mut self,
 7733        _: &MoveToNextSubwordEnd,
 7734        cx: &mut ViewContext<Self>,
 7735    ) {
 7736        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7737            s.move_cursors_with(|map, head, _| {
 7738                (movement::next_subword_end(map, head), SelectionGoal::None)
 7739            });
 7740        })
 7741    }
 7742
 7743    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7744        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7745            s.move_heads_with(|map, head, _| {
 7746                (movement::next_word_end(map, head), SelectionGoal::None)
 7747            });
 7748        })
 7749    }
 7750
 7751    pub fn select_to_next_subword_end(
 7752        &mut self,
 7753        _: &SelectToNextSubwordEnd,
 7754        cx: &mut ViewContext<Self>,
 7755    ) {
 7756        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7757            s.move_heads_with(|map, head, _| {
 7758                (movement::next_subword_end(map, head), SelectionGoal::None)
 7759            });
 7760        })
 7761    }
 7762
 7763    pub fn delete_to_next_word_end(
 7764        &mut self,
 7765        action: &DeleteToNextWordEnd,
 7766        cx: &mut ViewContext<Self>,
 7767    ) {
 7768        self.transact(cx, |this, cx| {
 7769            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7770                let line_mode = s.line_mode;
 7771                s.move_with(|map, selection| {
 7772                    if selection.is_empty() && !line_mode {
 7773                        let cursor = if action.ignore_newlines {
 7774                            movement::next_word_end(map, selection.head())
 7775                        } else {
 7776                            movement::next_word_end_or_newline(map, selection.head())
 7777                        };
 7778                        selection.set_head(cursor, SelectionGoal::None);
 7779                    }
 7780                });
 7781            });
 7782            this.insert("", cx);
 7783        });
 7784    }
 7785
 7786    pub fn delete_to_next_subword_end(
 7787        &mut self,
 7788        _: &DeleteToNextSubwordEnd,
 7789        cx: &mut ViewContext<Self>,
 7790    ) {
 7791        self.transact(cx, |this, cx| {
 7792            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7793                s.move_with(|map, selection| {
 7794                    if selection.is_empty() {
 7795                        let cursor = movement::next_subword_end(map, selection.head());
 7796                        selection.set_head(cursor, SelectionGoal::None);
 7797                    }
 7798                });
 7799            });
 7800            this.insert("", cx);
 7801        });
 7802    }
 7803
 7804    pub fn move_to_beginning_of_line(
 7805        &mut self,
 7806        action: &MoveToBeginningOfLine,
 7807        cx: &mut ViewContext<Self>,
 7808    ) {
 7809        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7810            s.move_cursors_with(|map, head, _| {
 7811                (
 7812                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7813                    SelectionGoal::None,
 7814                )
 7815            });
 7816        })
 7817    }
 7818
 7819    pub fn select_to_beginning_of_line(
 7820        &mut self,
 7821        action: &SelectToBeginningOfLine,
 7822        cx: &mut ViewContext<Self>,
 7823    ) {
 7824        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7825            s.move_heads_with(|map, head, _| {
 7826                (
 7827                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7828                    SelectionGoal::None,
 7829                )
 7830            });
 7831        });
 7832    }
 7833
 7834    pub fn delete_to_beginning_of_line(
 7835        &mut self,
 7836        _: &DeleteToBeginningOfLine,
 7837        cx: &mut ViewContext<Self>,
 7838    ) {
 7839        self.transact(cx, |this, cx| {
 7840            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7841                s.move_with(|_, selection| {
 7842                    selection.reversed = true;
 7843                });
 7844            });
 7845
 7846            this.select_to_beginning_of_line(
 7847                &SelectToBeginningOfLine {
 7848                    stop_at_soft_wraps: false,
 7849                },
 7850                cx,
 7851            );
 7852            this.backspace(&Backspace, cx);
 7853        });
 7854    }
 7855
 7856    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7857        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7858            s.move_cursors_with(|map, head, _| {
 7859                (
 7860                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7861                    SelectionGoal::None,
 7862                )
 7863            });
 7864        })
 7865    }
 7866
 7867    pub fn select_to_end_of_line(
 7868        &mut self,
 7869        action: &SelectToEndOfLine,
 7870        cx: &mut ViewContext<Self>,
 7871    ) {
 7872        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7873            s.move_heads_with(|map, head, _| {
 7874                (
 7875                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7876                    SelectionGoal::None,
 7877                )
 7878            });
 7879        })
 7880    }
 7881
 7882    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7883        self.transact(cx, |this, cx| {
 7884            this.select_to_end_of_line(
 7885                &SelectToEndOfLine {
 7886                    stop_at_soft_wraps: false,
 7887                },
 7888                cx,
 7889            );
 7890            this.delete(&Delete, cx);
 7891        });
 7892    }
 7893
 7894    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7895        self.transact(cx, |this, cx| {
 7896            this.select_to_end_of_line(
 7897                &SelectToEndOfLine {
 7898                    stop_at_soft_wraps: false,
 7899                },
 7900                cx,
 7901            );
 7902            this.cut(&Cut, cx);
 7903        });
 7904    }
 7905
 7906    pub fn move_to_start_of_paragraph(
 7907        &mut self,
 7908        _: &MoveToStartOfParagraph,
 7909        cx: &mut ViewContext<Self>,
 7910    ) {
 7911        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7912            cx.propagate();
 7913            return;
 7914        }
 7915
 7916        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7917            s.move_with(|map, selection| {
 7918                selection.collapse_to(
 7919                    movement::start_of_paragraph(map, selection.head(), 1),
 7920                    SelectionGoal::None,
 7921                )
 7922            });
 7923        })
 7924    }
 7925
 7926    pub fn move_to_end_of_paragraph(
 7927        &mut self,
 7928        _: &MoveToEndOfParagraph,
 7929        cx: &mut ViewContext<Self>,
 7930    ) {
 7931        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7932            cx.propagate();
 7933            return;
 7934        }
 7935
 7936        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7937            s.move_with(|map, selection| {
 7938                selection.collapse_to(
 7939                    movement::end_of_paragraph(map, selection.head(), 1),
 7940                    SelectionGoal::None,
 7941                )
 7942            });
 7943        })
 7944    }
 7945
 7946    pub fn select_to_start_of_paragraph(
 7947        &mut self,
 7948        _: &SelectToStartOfParagraph,
 7949        cx: &mut ViewContext<Self>,
 7950    ) {
 7951        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7952            cx.propagate();
 7953            return;
 7954        }
 7955
 7956        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7957            s.move_heads_with(|map, head, _| {
 7958                (
 7959                    movement::start_of_paragraph(map, head, 1),
 7960                    SelectionGoal::None,
 7961                )
 7962            });
 7963        })
 7964    }
 7965
 7966    pub fn select_to_end_of_paragraph(
 7967        &mut self,
 7968        _: &SelectToEndOfParagraph,
 7969        cx: &mut ViewContext<Self>,
 7970    ) {
 7971        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7972            cx.propagate();
 7973            return;
 7974        }
 7975
 7976        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7977            s.move_heads_with(|map, head, _| {
 7978                (
 7979                    movement::end_of_paragraph(map, head, 1),
 7980                    SelectionGoal::None,
 7981                )
 7982            });
 7983        })
 7984    }
 7985
 7986    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7987        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7988            cx.propagate();
 7989            return;
 7990        }
 7991
 7992        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7993            s.select_ranges(vec![0..0]);
 7994        });
 7995    }
 7996
 7997    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7998        let mut selection = self.selections.last::<Point>(cx);
 7999        selection.set_head(Point::zero(), SelectionGoal::None);
 8000
 8001        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8002            s.select(vec![selection]);
 8003        });
 8004    }
 8005
 8006    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8007        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8008            cx.propagate();
 8009            return;
 8010        }
 8011
 8012        let cursor = self.buffer.read(cx).read(cx).len();
 8013        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8014            s.select_ranges(vec![cursor..cursor])
 8015        });
 8016    }
 8017
 8018    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8019        self.nav_history = nav_history;
 8020    }
 8021
 8022    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8023        self.nav_history.as_ref()
 8024    }
 8025
 8026    fn push_to_nav_history(
 8027        &mut self,
 8028        cursor_anchor: Anchor,
 8029        new_position: Option<Point>,
 8030        cx: &mut ViewContext<Self>,
 8031    ) {
 8032        if let Some(nav_history) = self.nav_history.as_mut() {
 8033            let buffer = self.buffer.read(cx).read(cx);
 8034            let cursor_position = cursor_anchor.to_point(&buffer);
 8035            let scroll_state = self.scroll_manager.anchor();
 8036            let scroll_top_row = scroll_state.top_row(&buffer);
 8037            drop(buffer);
 8038
 8039            if let Some(new_position) = new_position {
 8040                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8041                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8042                    return;
 8043                }
 8044            }
 8045
 8046            nav_history.push(
 8047                Some(NavigationData {
 8048                    cursor_anchor,
 8049                    cursor_position,
 8050                    scroll_anchor: scroll_state,
 8051                    scroll_top_row,
 8052                }),
 8053                cx,
 8054            );
 8055        }
 8056    }
 8057
 8058    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8059        let buffer = self.buffer.read(cx).snapshot(cx);
 8060        let mut selection = self.selections.first::<usize>(cx);
 8061        selection.set_head(buffer.len(), SelectionGoal::None);
 8062        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8063            s.select(vec![selection]);
 8064        });
 8065    }
 8066
 8067    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8068        let end = self.buffer.read(cx).read(cx).len();
 8069        self.change_selections(None, cx, |s| {
 8070            s.select_ranges(vec![0..end]);
 8071        });
 8072    }
 8073
 8074    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8075        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8076        let mut selections = self.selections.all::<Point>(cx);
 8077        let max_point = display_map.buffer_snapshot.max_point();
 8078        for selection in &mut selections {
 8079            let rows = selection.spanned_rows(true, &display_map);
 8080            selection.start = Point::new(rows.start.0, 0);
 8081            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8082            selection.reversed = false;
 8083        }
 8084        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8085            s.select(selections);
 8086        });
 8087    }
 8088
 8089    pub fn split_selection_into_lines(
 8090        &mut self,
 8091        _: &SplitSelectionIntoLines,
 8092        cx: &mut ViewContext<Self>,
 8093    ) {
 8094        let mut to_unfold = Vec::new();
 8095        let mut new_selection_ranges = Vec::new();
 8096        {
 8097            let selections = self.selections.all::<Point>(cx);
 8098            let buffer = self.buffer.read(cx).read(cx);
 8099            for selection in selections {
 8100                for row in selection.start.row..selection.end.row {
 8101                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8102                    new_selection_ranges.push(cursor..cursor);
 8103                }
 8104                new_selection_ranges.push(selection.end..selection.end);
 8105                to_unfold.push(selection.start..selection.end);
 8106            }
 8107        }
 8108        self.unfold_ranges(to_unfold, true, true, cx);
 8109        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8110            s.select_ranges(new_selection_ranges);
 8111        });
 8112    }
 8113
 8114    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8115        self.add_selection(true, cx);
 8116    }
 8117
 8118    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8119        self.add_selection(false, cx);
 8120    }
 8121
 8122    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8123        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8124        let mut selections = self.selections.all::<Point>(cx);
 8125        let text_layout_details = self.text_layout_details(cx);
 8126        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8127            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8128            let range = oldest_selection.display_range(&display_map).sorted();
 8129
 8130            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8131            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8132            let positions = start_x.min(end_x)..start_x.max(end_x);
 8133
 8134            selections.clear();
 8135            let mut stack = Vec::new();
 8136            for row in range.start.row().0..=range.end.row().0 {
 8137                if let Some(selection) = self.selections.build_columnar_selection(
 8138                    &display_map,
 8139                    DisplayRow(row),
 8140                    &positions,
 8141                    oldest_selection.reversed,
 8142                    &text_layout_details,
 8143                ) {
 8144                    stack.push(selection.id);
 8145                    selections.push(selection);
 8146                }
 8147            }
 8148
 8149            if above {
 8150                stack.reverse();
 8151            }
 8152
 8153            AddSelectionsState { above, stack }
 8154        });
 8155
 8156        let last_added_selection = *state.stack.last().unwrap();
 8157        let mut new_selections = Vec::new();
 8158        if above == state.above {
 8159            let end_row = if above {
 8160                DisplayRow(0)
 8161            } else {
 8162                display_map.max_point().row()
 8163            };
 8164
 8165            'outer: for selection in selections {
 8166                if selection.id == last_added_selection {
 8167                    let range = selection.display_range(&display_map).sorted();
 8168                    debug_assert_eq!(range.start.row(), range.end.row());
 8169                    let mut row = range.start.row();
 8170                    let positions =
 8171                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8172                            px(start)..px(end)
 8173                        } else {
 8174                            let start_x =
 8175                                display_map.x_for_display_point(range.start, &text_layout_details);
 8176                            let end_x =
 8177                                display_map.x_for_display_point(range.end, &text_layout_details);
 8178                            start_x.min(end_x)..start_x.max(end_x)
 8179                        };
 8180
 8181                    while row != end_row {
 8182                        if above {
 8183                            row.0 -= 1;
 8184                        } else {
 8185                            row.0 += 1;
 8186                        }
 8187
 8188                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8189                            &display_map,
 8190                            row,
 8191                            &positions,
 8192                            selection.reversed,
 8193                            &text_layout_details,
 8194                        ) {
 8195                            state.stack.push(new_selection.id);
 8196                            if above {
 8197                                new_selections.push(new_selection);
 8198                                new_selections.push(selection);
 8199                            } else {
 8200                                new_selections.push(selection);
 8201                                new_selections.push(new_selection);
 8202                            }
 8203
 8204                            continue 'outer;
 8205                        }
 8206                    }
 8207                }
 8208
 8209                new_selections.push(selection);
 8210            }
 8211        } else {
 8212            new_selections = selections;
 8213            new_selections.retain(|s| s.id != last_added_selection);
 8214            state.stack.pop();
 8215        }
 8216
 8217        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8218            s.select(new_selections);
 8219        });
 8220        if state.stack.len() > 1 {
 8221            self.add_selections_state = Some(state);
 8222        }
 8223    }
 8224
 8225    pub fn select_next_match_internal(
 8226        &mut self,
 8227        display_map: &DisplaySnapshot,
 8228        replace_newest: bool,
 8229        autoscroll: Option<Autoscroll>,
 8230        cx: &mut ViewContext<Self>,
 8231    ) -> Result<()> {
 8232        fn select_next_match_ranges(
 8233            this: &mut Editor,
 8234            range: Range<usize>,
 8235            replace_newest: bool,
 8236            auto_scroll: Option<Autoscroll>,
 8237            cx: &mut ViewContext<Editor>,
 8238        ) {
 8239            this.unfold_ranges([range.clone()], false, true, cx);
 8240            this.change_selections(auto_scroll, cx, |s| {
 8241                if replace_newest {
 8242                    s.delete(s.newest_anchor().id);
 8243                }
 8244                s.insert_range(range.clone());
 8245            });
 8246        }
 8247
 8248        let buffer = &display_map.buffer_snapshot;
 8249        let mut selections = self.selections.all::<usize>(cx);
 8250        if let Some(mut select_next_state) = self.select_next_state.take() {
 8251            let query = &select_next_state.query;
 8252            if !select_next_state.done {
 8253                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8254                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8255                let mut next_selected_range = None;
 8256
 8257                let bytes_after_last_selection =
 8258                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8259                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8260                let query_matches = query
 8261                    .stream_find_iter(bytes_after_last_selection)
 8262                    .map(|result| (last_selection.end, result))
 8263                    .chain(
 8264                        query
 8265                            .stream_find_iter(bytes_before_first_selection)
 8266                            .map(|result| (0, result)),
 8267                    );
 8268
 8269                for (start_offset, query_match) in query_matches {
 8270                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8271                    let offset_range =
 8272                        start_offset + query_match.start()..start_offset + query_match.end();
 8273                    let display_range = offset_range.start.to_display_point(display_map)
 8274                        ..offset_range.end.to_display_point(display_map);
 8275
 8276                    if !select_next_state.wordwise
 8277                        || (!movement::is_inside_word(display_map, display_range.start)
 8278                            && !movement::is_inside_word(display_map, display_range.end))
 8279                    {
 8280                        // TODO: This is n^2, because we might check all the selections
 8281                        if !selections
 8282                            .iter()
 8283                            .any(|selection| selection.range().overlaps(&offset_range))
 8284                        {
 8285                            next_selected_range = Some(offset_range);
 8286                            break;
 8287                        }
 8288                    }
 8289                }
 8290
 8291                if let Some(next_selected_range) = next_selected_range {
 8292                    select_next_match_ranges(
 8293                        self,
 8294                        next_selected_range,
 8295                        replace_newest,
 8296                        autoscroll,
 8297                        cx,
 8298                    );
 8299                } else {
 8300                    select_next_state.done = true;
 8301                }
 8302            }
 8303
 8304            self.select_next_state = Some(select_next_state);
 8305        } else {
 8306            let mut only_carets = true;
 8307            let mut same_text_selected = true;
 8308            let mut selected_text = None;
 8309
 8310            let mut selections_iter = selections.iter().peekable();
 8311            while let Some(selection) = selections_iter.next() {
 8312                if selection.start != selection.end {
 8313                    only_carets = false;
 8314                }
 8315
 8316                if same_text_selected {
 8317                    if selected_text.is_none() {
 8318                        selected_text =
 8319                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8320                    }
 8321
 8322                    if let Some(next_selection) = selections_iter.peek() {
 8323                        if next_selection.range().len() == selection.range().len() {
 8324                            let next_selected_text = buffer
 8325                                .text_for_range(next_selection.range())
 8326                                .collect::<String>();
 8327                            if Some(next_selected_text) != selected_text {
 8328                                same_text_selected = false;
 8329                                selected_text = None;
 8330                            }
 8331                        } else {
 8332                            same_text_selected = false;
 8333                            selected_text = None;
 8334                        }
 8335                    }
 8336                }
 8337            }
 8338
 8339            if only_carets {
 8340                for selection in &mut selections {
 8341                    let word_range = movement::surrounding_word(
 8342                        display_map,
 8343                        selection.start.to_display_point(display_map),
 8344                    );
 8345                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8346                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8347                    selection.goal = SelectionGoal::None;
 8348                    selection.reversed = false;
 8349                    select_next_match_ranges(
 8350                        self,
 8351                        selection.start..selection.end,
 8352                        replace_newest,
 8353                        autoscroll,
 8354                        cx,
 8355                    );
 8356                }
 8357
 8358                if selections.len() == 1 {
 8359                    let selection = selections
 8360                        .last()
 8361                        .expect("ensured that there's only one selection");
 8362                    let query = buffer
 8363                        .text_for_range(selection.start..selection.end)
 8364                        .collect::<String>();
 8365                    let is_empty = query.is_empty();
 8366                    let select_state = SelectNextState {
 8367                        query: AhoCorasick::new(&[query])?,
 8368                        wordwise: true,
 8369                        done: is_empty,
 8370                    };
 8371                    self.select_next_state = Some(select_state);
 8372                } else {
 8373                    self.select_next_state = None;
 8374                }
 8375            } else if let Some(selected_text) = selected_text {
 8376                self.select_next_state = Some(SelectNextState {
 8377                    query: AhoCorasick::new(&[selected_text])?,
 8378                    wordwise: false,
 8379                    done: false,
 8380                });
 8381                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8382            }
 8383        }
 8384        Ok(())
 8385    }
 8386
 8387    pub fn select_all_matches(
 8388        &mut self,
 8389        _action: &SelectAllMatches,
 8390        cx: &mut ViewContext<Self>,
 8391    ) -> Result<()> {
 8392        self.push_to_selection_history();
 8393        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8394
 8395        self.select_next_match_internal(&display_map, false, None, cx)?;
 8396        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8397            return Ok(());
 8398        };
 8399        if select_next_state.done {
 8400            return Ok(());
 8401        }
 8402
 8403        let mut new_selections = self.selections.all::<usize>(cx);
 8404
 8405        let buffer = &display_map.buffer_snapshot;
 8406        let query_matches = select_next_state
 8407            .query
 8408            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8409
 8410        for query_match in query_matches {
 8411            let query_match = query_match.unwrap(); // can only fail due to I/O
 8412            let offset_range = query_match.start()..query_match.end();
 8413            let display_range = offset_range.start.to_display_point(&display_map)
 8414                ..offset_range.end.to_display_point(&display_map);
 8415
 8416            if !select_next_state.wordwise
 8417                || (!movement::is_inside_word(&display_map, display_range.start)
 8418                    && !movement::is_inside_word(&display_map, display_range.end))
 8419            {
 8420                self.selections.change_with(cx, |selections| {
 8421                    new_selections.push(Selection {
 8422                        id: selections.new_selection_id(),
 8423                        start: offset_range.start,
 8424                        end: offset_range.end,
 8425                        reversed: false,
 8426                        goal: SelectionGoal::None,
 8427                    });
 8428                });
 8429            }
 8430        }
 8431
 8432        new_selections.sort_by_key(|selection| selection.start);
 8433        let mut ix = 0;
 8434        while ix + 1 < new_selections.len() {
 8435            let current_selection = &new_selections[ix];
 8436            let next_selection = &new_selections[ix + 1];
 8437            if current_selection.range().overlaps(&next_selection.range()) {
 8438                if current_selection.id < next_selection.id {
 8439                    new_selections.remove(ix + 1);
 8440                } else {
 8441                    new_selections.remove(ix);
 8442                }
 8443            } else {
 8444                ix += 1;
 8445            }
 8446        }
 8447
 8448        select_next_state.done = true;
 8449        self.unfold_ranges(
 8450            new_selections.iter().map(|selection| selection.range()),
 8451            false,
 8452            false,
 8453            cx,
 8454        );
 8455        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8456            selections.select(new_selections)
 8457        });
 8458
 8459        Ok(())
 8460    }
 8461
 8462    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8463        self.push_to_selection_history();
 8464        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8465        self.select_next_match_internal(
 8466            &display_map,
 8467            action.replace_newest,
 8468            Some(Autoscroll::newest()),
 8469            cx,
 8470        )?;
 8471        Ok(())
 8472    }
 8473
 8474    pub fn select_previous(
 8475        &mut self,
 8476        action: &SelectPrevious,
 8477        cx: &mut ViewContext<Self>,
 8478    ) -> Result<()> {
 8479        self.push_to_selection_history();
 8480        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8481        let buffer = &display_map.buffer_snapshot;
 8482        let mut selections = self.selections.all::<usize>(cx);
 8483        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8484            let query = &select_prev_state.query;
 8485            if !select_prev_state.done {
 8486                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8487                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8488                let mut next_selected_range = None;
 8489                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8490                let bytes_before_last_selection =
 8491                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8492                let bytes_after_first_selection =
 8493                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8494                let query_matches = query
 8495                    .stream_find_iter(bytes_before_last_selection)
 8496                    .map(|result| (last_selection.start, result))
 8497                    .chain(
 8498                        query
 8499                            .stream_find_iter(bytes_after_first_selection)
 8500                            .map(|result| (buffer.len(), result)),
 8501                    );
 8502                for (end_offset, query_match) in query_matches {
 8503                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8504                    let offset_range =
 8505                        end_offset - query_match.end()..end_offset - query_match.start();
 8506                    let display_range = offset_range.start.to_display_point(&display_map)
 8507                        ..offset_range.end.to_display_point(&display_map);
 8508
 8509                    if !select_prev_state.wordwise
 8510                        || (!movement::is_inside_word(&display_map, display_range.start)
 8511                            && !movement::is_inside_word(&display_map, display_range.end))
 8512                    {
 8513                        next_selected_range = Some(offset_range);
 8514                        break;
 8515                    }
 8516                }
 8517
 8518                if let Some(next_selected_range) = next_selected_range {
 8519                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8520                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8521                        if action.replace_newest {
 8522                            s.delete(s.newest_anchor().id);
 8523                        }
 8524                        s.insert_range(next_selected_range);
 8525                    });
 8526                } else {
 8527                    select_prev_state.done = true;
 8528                }
 8529            }
 8530
 8531            self.select_prev_state = Some(select_prev_state);
 8532        } else {
 8533            let mut only_carets = true;
 8534            let mut same_text_selected = true;
 8535            let mut selected_text = None;
 8536
 8537            let mut selections_iter = selections.iter().peekable();
 8538            while let Some(selection) = selections_iter.next() {
 8539                if selection.start != selection.end {
 8540                    only_carets = false;
 8541                }
 8542
 8543                if same_text_selected {
 8544                    if selected_text.is_none() {
 8545                        selected_text =
 8546                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8547                    }
 8548
 8549                    if let Some(next_selection) = selections_iter.peek() {
 8550                        if next_selection.range().len() == selection.range().len() {
 8551                            let next_selected_text = buffer
 8552                                .text_for_range(next_selection.range())
 8553                                .collect::<String>();
 8554                            if Some(next_selected_text) != selected_text {
 8555                                same_text_selected = false;
 8556                                selected_text = None;
 8557                            }
 8558                        } else {
 8559                            same_text_selected = false;
 8560                            selected_text = None;
 8561                        }
 8562                    }
 8563                }
 8564            }
 8565
 8566            if only_carets {
 8567                for selection in &mut selections {
 8568                    let word_range = movement::surrounding_word(
 8569                        &display_map,
 8570                        selection.start.to_display_point(&display_map),
 8571                    );
 8572                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8573                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8574                    selection.goal = SelectionGoal::None;
 8575                    selection.reversed = false;
 8576                }
 8577                if selections.len() == 1 {
 8578                    let selection = selections
 8579                        .last()
 8580                        .expect("ensured that there's only one selection");
 8581                    let query = buffer
 8582                        .text_for_range(selection.start..selection.end)
 8583                        .collect::<String>();
 8584                    let is_empty = query.is_empty();
 8585                    let select_state = SelectNextState {
 8586                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8587                        wordwise: true,
 8588                        done: is_empty,
 8589                    };
 8590                    self.select_prev_state = Some(select_state);
 8591                } else {
 8592                    self.select_prev_state = None;
 8593                }
 8594
 8595                self.unfold_ranges(
 8596                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8597                    false,
 8598                    true,
 8599                    cx,
 8600                );
 8601                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8602                    s.select(selections);
 8603                });
 8604            } else if let Some(selected_text) = selected_text {
 8605                self.select_prev_state = Some(SelectNextState {
 8606                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8607                    wordwise: false,
 8608                    done: false,
 8609                });
 8610                self.select_previous(action, cx)?;
 8611            }
 8612        }
 8613        Ok(())
 8614    }
 8615
 8616    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8617        let text_layout_details = &self.text_layout_details(cx);
 8618        self.transact(cx, |this, cx| {
 8619            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8620            let mut edits = Vec::new();
 8621            let mut selection_edit_ranges = Vec::new();
 8622            let mut last_toggled_row = None;
 8623            let snapshot = this.buffer.read(cx).read(cx);
 8624            let empty_str: Arc<str> = Arc::default();
 8625            let mut suffixes_inserted = Vec::new();
 8626
 8627            fn comment_prefix_range(
 8628                snapshot: &MultiBufferSnapshot,
 8629                row: MultiBufferRow,
 8630                comment_prefix: &str,
 8631                comment_prefix_whitespace: &str,
 8632            ) -> Range<Point> {
 8633                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8634
 8635                let mut line_bytes = snapshot
 8636                    .bytes_in_range(start..snapshot.max_point())
 8637                    .flatten()
 8638                    .copied();
 8639
 8640                // If this line currently begins with the line comment prefix, then record
 8641                // the range containing the prefix.
 8642                if line_bytes
 8643                    .by_ref()
 8644                    .take(comment_prefix.len())
 8645                    .eq(comment_prefix.bytes())
 8646                {
 8647                    // Include any whitespace that matches the comment prefix.
 8648                    let matching_whitespace_len = line_bytes
 8649                        .zip(comment_prefix_whitespace.bytes())
 8650                        .take_while(|(a, b)| a == b)
 8651                        .count() as u32;
 8652                    let end = Point::new(
 8653                        start.row,
 8654                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8655                    );
 8656                    start..end
 8657                } else {
 8658                    start..start
 8659                }
 8660            }
 8661
 8662            fn comment_suffix_range(
 8663                snapshot: &MultiBufferSnapshot,
 8664                row: MultiBufferRow,
 8665                comment_suffix: &str,
 8666                comment_suffix_has_leading_space: bool,
 8667            ) -> Range<Point> {
 8668                let end = Point::new(row.0, snapshot.line_len(row));
 8669                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8670
 8671                let mut line_end_bytes = snapshot
 8672                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8673                    .flatten()
 8674                    .copied();
 8675
 8676                let leading_space_len = if suffix_start_column > 0
 8677                    && line_end_bytes.next() == Some(b' ')
 8678                    && comment_suffix_has_leading_space
 8679                {
 8680                    1
 8681                } else {
 8682                    0
 8683                };
 8684
 8685                // If this line currently begins with the line comment prefix, then record
 8686                // the range containing the prefix.
 8687                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8688                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8689                    start..end
 8690                } else {
 8691                    end..end
 8692                }
 8693            }
 8694
 8695            // TODO: Handle selections that cross excerpts
 8696            for selection in &mut selections {
 8697                let start_column = snapshot
 8698                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8699                    .len;
 8700                let language = if let Some(language) =
 8701                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8702                {
 8703                    language
 8704                } else {
 8705                    continue;
 8706                };
 8707
 8708                selection_edit_ranges.clear();
 8709
 8710                // If multiple selections contain a given row, avoid processing that
 8711                // row more than once.
 8712                let mut start_row = MultiBufferRow(selection.start.row);
 8713                if last_toggled_row == Some(start_row) {
 8714                    start_row = start_row.next_row();
 8715                }
 8716                let end_row =
 8717                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8718                        MultiBufferRow(selection.end.row - 1)
 8719                    } else {
 8720                        MultiBufferRow(selection.end.row)
 8721                    };
 8722                last_toggled_row = Some(end_row);
 8723
 8724                if start_row > end_row {
 8725                    continue;
 8726                }
 8727
 8728                // If the language has line comments, toggle those.
 8729                let full_comment_prefixes = language.line_comment_prefixes();
 8730                if !full_comment_prefixes.is_empty() {
 8731                    let first_prefix = full_comment_prefixes
 8732                        .first()
 8733                        .expect("prefixes is non-empty");
 8734                    let prefix_trimmed_lengths = full_comment_prefixes
 8735                        .iter()
 8736                        .map(|p| p.trim_end_matches(' ').len())
 8737                        .collect::<SmallVec<[usize; 4]>>();
 8738
 8739                    let mut all_selection_lines_are_comments = true;
 8740
 8741                    for row in start_row.0..=end_row.0 {
 8742                        let row = MultiBufferRow(row);
 8743                        if start_row < end_row && snapshot.is_line_blank(row) {
 8744                            continue;
 8745                        }
 8746
 8747                        let prefix_range = full_comment_prefixes
 8748                            .iter()
 8749                            .zip(prefix_trimmed_lengths.iter().copied())
 8750                            .map(|(prefix, trimmed_prefix_len)| {
 8751                                comment_prefix_range(
 8752                                    snapshot.deref(),
 8753                                    row,
 8754                                    &prefix[..trimmed_prefix_len],
 8755                                    &prefix[trimmed_prefix_len..],
 8756                                )
 8757                            })
 8758                            .max_by_key(|range| range.end.column - range.start.column)
 8759                            .expect("prefixes is non-empty");
 8760
 8761                        if prefix_range.is_empty() {
 8762                            all_selection_lines_are_comments = false;
 8763                        }
 8764
 8765                        selection_edit_ranges.push(prefix_range);
 8766                    }
 8767
 8768                    if all_selection_lines_are_comments {
 8769                        edits.extend(
 8770                            selection_edit_ranges
 8771                                .iter()
 8772                                .cloned()
 8773                                .map(|range| (range, empty_str.clone())),
 8774                        );
 8775                    } else {
 8776                        let min_column = selection_edit_ranges
 8777                            .iter()
 8778                            .map(|range| range.start.column)
 8779                            .min()
 8780                            .unwrap_or(0);
 8781                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8782                            let position = Point::new(range.start.row, min_column);
 8783                            (position..position, first_prefix.clone())
 8784                        }));
 8785                    }
 8786                } else if let Some((full_comment_prefix, comment_suffix)) =
 8787                    language.block_comment_delimiters()
 8788                {
 8789                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8790                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8791                    let prefix_range = comment_prefix_range(
 8792                        snapshot.deref(),
 8793                        start_row,
 8794                        comment_prefix,
 8795                        comment_prefix_whitespace,
 8796                    );
 8797                    let suffix_range = comment_suffix_range(
 8798                        snapshot.deref(),
 8799                        end_row,
 8800                        comment_suffix.trim_start_matches(' '),
 8801                        comment_suffix.starts_with(' '),
 8802                    );
 8803
 8804                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8805                        edits.push((
 8806                            prefix_range.start..prefix_range.start,
 8807                            full_comment_prefix.clone(),
 8808                        ));
 8809                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8810                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8811                    } else {
 8812                        edits.push((prefix_range, empty_str.clone()));
 8813                        edits.push((suffix_range, empty_str.clone()));
 8814                    }
 8815                } else {
 8816                    continue;
 8817                }
 8818            }
 8819
 8820            drop(snapshot);
 8821            this.buffer.update(cx, |buffer, cx| {
 8822                buffer.edit(edits, None, cx);
 8823            });
 8824
 8825            // Adjust selections so that they end before any comment suffixes that
 8826            // were inserted.
 8827            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8828            let mut selections = this.selections.all::<Point>(cx);
 8829            let snapshot = this.buffer.read(cx).read(cx);
 8830            for selection in &mut selections {
 8831                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8832                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8833                        Ordering::Less => {
 8834                            suffixes_inserted.next();
 8835                            continue;
 8836                        }
 8837                        Ordering::Greater => break,
 8838                        Ordering::Equal => {
 8839                            if selection.end.column == snapshot.line_len(row) {
 8840                                if selection.is_empty() {
 8841                                    selection.start.column -= suffix_len as u32;
 8842                                }
 8843                                selection.end.column -= suffix_len as u32;
 8844                            }
 8845                            break;
 8846                        }
 8847                    }
 8848                }
 8849            }
 8850
 8851            drop(snapshot);
 8852            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8853
 8854            let selections = this.selections.all::<Point>(cx);
 8855            let selections_on_single_row = selections.windows(2).all(|selections| {
 8856                selections[0].start.row == selections[1].start.row
 8857                    && selections[0].end.row == selections[1].end.row
 8858                    && selections[0].start.row == selections[0].end.row
 8859            });
 8860            let selections_selecting = selections
 8861                .iter()
 8862                .any(|selection| selection.start != selection.end);
 8863            let advance_downwards = action.advance_downwards
 8864                && selections_on_single_row
 8865                && !selections_selecting
 8866                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8867
 8868            if advance_downwards {
 8869                let snapshot = this.buffer.read(cx).snapshot(cx);
 8870
 8871                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8872                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8873                        let mut point = display_point.to_point(display_snapshot);
 8874                        point.row += 1;
 8875                        point = snapshot.clip_point(point, Bias::Left);
 8876                        let display_point = point.to_display_point(display_snapshot);
 8877                        let goal = SelectionGoal::HorizontalPosition(
 8878                            display_snapshot
 8879                                .x_for_display_point(display_point, text_layout_details)
 8880                                .into(),
 8881                        );
 8882                        (display_point, goal)
 8883                    })
 8884                });
 8885            }
 8886        });
 8887    }
 8888
 8889    pub fn select_enclosing_symbol(
 8890        &mut self,
 8891        _: &SelectEnclosingSymbol,
 8892        cx: &mut ViewContext<Self>,
 8893    ) {
 8894        let buffer = self.buffer.read(cx).snapshot(cx);
 8895        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8896
 8897        fn update_selection(
 8898            selection: &Selection<usize>,
 8899            buffer_snap: &MultiBufferSnapshot,
 8900        ) -> Option<Selection<usize>> {
 8901            let cursor = selection.head();
 8902            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8903            for symbol in symbols.iter().rev() {
 8904                let start = symbol.range.start.to_offset(buffer_snap);
 8905                let end = symbol.range.end.to_offset(buffer_snap);
 8906                let new_range = start..end;
 8907                if start < selection.start || end > selection.end {
 8908                    return Some(Selection {
 8909                        id: selection.id,
 8910                        start: new_range.start,
 8911                        end: new_range.end,
 8912                        goal: SelectionGoal::None,
 8913                        reversed: selection.reversed,
 8914                    });
 8915                }
 8916            }
 8917            None
 8918        }
 8919
 8920        let mut selected_larger_symbol = false;
 8921        let new_selections = old_selections
 8922            .iter()
 8923            .map(|selection| match update_selection(selection, &buffer) {
 8924                Some(new_selection) => {
 8925                    if new_selection.range() != selection.range() {
 8926                        selected_larger_symbol = true;
 8927                    }
 8928                    new_selection
 8929                }
 8930                None => selection.clone(),
 8931            })
 8932            .collect::<Vec<_>>();
 8933
 8934        if selected_larger_symbol {
 8935            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8936                s.select(new_selections);
 8937            });
 8938        }
 8939    }
 8940
 8941    pub fn select_larger_syntax_node(
 8942        &mut self,
 8943        _: &SelectLargerSyntaxNode,
 8944        cx: &mut ViewContext<Self>,
 8945    ) {
 8946        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8947        let buffer = self.buffer.read(cx).snapshot(cx);
 8948        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8949
 8950        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8951        let mut selected_larger_node = false;
 8952        let new_selections = old_selections
 8953            .iter()
 8954            .map(|selection| {
 8955                let old_range = selection.start..selection.end;
 8956                let mut new_range = old_range.clone();
 8957                while let Some(containing_range) =
 8958                    buffer.range_for_syntax_ancestor(new_range.clone())
 8959                {
 8960                    new_range = containing_range;
 8961                    if !display_map.intersects_fold(new_range.start)
 8962                        && !display_map.intersects_fold(new_range.end)
 8963                    {
 8964                        break;
 8965                    }
 8966                }
 8967
 8968                selected_larger_node |= new_range != old_range;
 8969                Selection {
 8970                    id: selection.id,
 8971                    start: new_range.start,
 8972                    end: new_range.end,
 8973                    goal: SelectionGoal::None,
 8974                    reversed: selection.reversed,
 8975                }
 8976            })
 8977            .collect::<Vec<_>>();
 8978
 8979        if selected_larger_node {
 8980            stack.push(old_selections);
 8981            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8982                s.select(new_selections);
 8983            });
 8984        }
 8985        self.select_larger_syntax_node_stack = stack;
 8986    }
 8987
 8988    pub fn select_smaller_syntax_node(
 8989        &mut self,
 8990        _: &SelectSmallerSyntaxNode,
 8991        cx: &mut ViewContext<Self>,
 8992    ) {
 8993        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8994        if let Some(selections) = stack.pop() {
 8995            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8996                s.select(selections.to_vec());
 8997            });
 8998        }
 8999        self.select_larger_syntax_node_stack = stack;
 9000    }
 9001
 9002    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9003        if !EditorSettings::get_global(cx).gutter.runnables {
 9004            self.clear_tasks();
 9005            return Task::ready(());
 9006        }
 9007        let project = self.project.clone();
 9008        cx.spawn(|this, mut cx| async move {
 9009            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9010                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9011            }) else {
 9012                return;
 9013            };
 9014
 9015            let Some(project) = project else {
 9016                return;
 9017            };
 9018
 9019            let hide_runnables = project
 9020                .update(&mut cx, |project, cx| {
 9021                    // Do not display any test indicators in non-dev server remote projects.
 9022                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9023                })
 9024                .unwrap_or(true);
 9025            if hide_runnables {
 9026                return;
 9027            }
 9028            let new_rows =
 9029                cx.background_executor()
 9030                    .spawn({
 9031                        let snapshot = display_snapshot.clone();
 9032                        async move {
 9033                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9034                        }
 9035                    })
 9036                    .await;
 9037            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9038
 9039            this.update(&mut cx, |this, _| {
 9040                this.clear_tasks();
 9041                for (key, value) in rows {
 9042                    this.insert_tasks(key, value);
 9043                }
 9044            })
 9045            .ok();
 9046        })
 9047    }
 9048    fn fetch_runnable_ranges(
 9049        snapshot: &DisplaySnapshot,
 9050        range: Range<Anchor>,
 9051    ) -> Vec<language::RunnableRange> {
 9052        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9053    }
 9054
 9055    fn runnable_rows(
 9056        project: Model<Project>,
 9057        snapshot: DisplaySnapshot,
 9058        runnable_ranges: Vec<RunnableRange>,
 9059        mut cx: AsyncWindowContext,
 9060    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9061        runnable_ranges
 9062            .into_iter()
 9063            .filter_map(|mut runnable| {
 9064                let tasks = cx
 9065                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9066                    .ok()?;
 9067                if tasks.is_empty() {
 9068                    return None;
 9069                }
 9070
 9071                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9072
 9073                let row = snapshot
 9074                    .buffer_snapshot
 9075                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9076                    .1
 9077                    .start
 9078                    .row;
 9079
 9080                let context_range =
 9081                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9082                Some((
 9083                    (runnable.buffer_id, row),
 9084                    RunnableTasks {
 9085                        templates: tasks,
 9086                        offset: MultiBufferOffset(runnable.run_range.start),
 9087                        context_range,
 9088                        column: point.column,
 9089                        extra_variables: runnable.extra_captures,
 9090                    },
 9091                ))
 9092            })
 9093            .collect()
 9094    }
 9095
 9096    fn templates_with_tags(
 9097        project: &Model<Project>,
 9098        runnable: &mut Runnable,
 9099        cx: &WindowContext<'_>,
 9100    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9101        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9102            let (worktree_id, file) = project
 9103                .buffer_for_id(runnable.buffer, cx)
 9104                .and_then(|buffer| buffer.read(cx).file())
 9105                .map(|file| (file.worktree_id(cx), file.clone()))
 9106                .unzip();
 9107
 9108            (project.task_inventory().clone(), worktree_id, file)
 9109        });
 9110
 9111        let inventory = inventory.read(cx);
 9112        let tags = mem::take(&mut runnable.tags);
 9113        let mut tags: Vec<_> = tags
 9114            .into_iter()
 9115            .flat_map(|tag| {
 9116                let tag = tag.0.clone();
 9117                inventory
 9118                    .list_tasks(
 9119                        file.clone(),
 9120                        Some(runnable.language.clone()),
 9121                        worktree_id,
 9122                        cx,
 9123                    )
 9124                    .into_iter()
 9125                    .filter(move |(_, template)| {
 9126                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9127                    })
 9128            })
 9129            .sorted_by_key(|(kind, _)| kind.to_owned())
 9130            .collect();
 9131        if let Some((leading_tag_source, _)) = tags.first() {
 9132            // Strongest source wins; if we have worktree tag binding, prefer that to
 9133            // global and language bindings;
 9134            // if we have a global binding, prefer that to language binding.
 9135            let first_mismatch = tags
 9136                .iter()
 9137                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9138            if let Some(index) = first_mismatch {
 9139                tags.truncate(index);
 9140            }
 9141        }
 9142
 9143        tags
 9144    }
 9145
 9146    pub fn move_to_enclosing_bracket(
 9147        &mut self,
 9148        _: &MoveToEnclosingBracket,
 9149        cx: &mut ViewContext<Self>,
 9150    ) {
 9151        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9152            s.move_offsets_with(|snapshot, selection| {
 9153                let Some(enclosing_bracket_ranges) =
 9154                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9155                else {
 9156                    return;
 9157                };
 9158
 9159                let mut best_length = usize::MAX;
 9160                let mut best_inside = false;
 9161                let mut best_in_bracket_range = false;
 9162                let mut best_destination = None;
 9163                for (open, close) in enclosing_bracket_ranges {
 9164                    let close = close.to_inclusive();
 9165                    let length = close.end() - open.start;
 9166                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9167                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9168                        || close.contains(&selection.head());
 9169
 9170                    // If best is next to a bracket and current isn't, skip
 9171                    if !in_bracket_range && best_in_bracket_range {
 9172                        continue;
 9173                    }
 9174
 9175                    // Prefer smaller lengths unless best is inside and current isn't
 9176                    if length > best_length && (best_inside || !inside) {
 9177                        continue;
 9178                    }
 9179
 9180                    best_length = length;
 9181                    best_inside = inside;
 9182                    best_in_bracket_range = in_bracket_range;
 9183                    best_destination = Some(
 9184                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9185                            if inside {
 9186                                open.end
 9187                            } else {
 9188                                open.start
 9189                            }
 9190                        } else if inside {
 9191                            *close.start()
 9192                        } else {
 9193                            *close.end()
 9194                        },
 9195                    );
 9196                }
 9197
 9198                if let Some(destination) = best_destination {
 9199                    selection.collapse_to(destination, SelectionGoal::None);
 9200                }
 9201            })
 9202        });
 9203    }
 9204
 9205    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9206        self.end_selection(cx);
 9207        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9208        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9209            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9210            self.select_next_state = entry.select_next_state;
 9211            self.select_prev_state = entry.select_prev_state;
 9212            self.add_selections_state = entry.add_selections_state;
 9213            self.request_autoscroll(Autoscroll::newest(), cx);
 9214        }
 9215        self.selection_history.mode = SelectionHistoryMode::Normal;
 9216    }
 9217
 9218    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9219        self.end_selection(cx);
 9220        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9221        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9222            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9223            self.select_next_state = entry.select_next_state;
 9224            self.select_prev_state = entry.select_prev_state;
 9225            self.add_selections_state = entry.add_selections_state;
 9226            self.request_autoscroll(Autoscroll::newest(), cx);
 9227        }
 9228        self.selection_history.mode = SelectionHistoryMode::Normal;
 9229    }
 9230
 9231    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9232        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9233    }
 9234
 9235    pub fn expand_excerpts_down(
 9236        &mut self,
 9237        action: &ExpandExcerptsDown,
 9238        cx: &mut ViewContext<Self>,
 9239    ) {
 9240        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9241    }
 9242
 9243    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9244        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9245    }
 9246
 9247    pub fn expand_excerpts_for_direction(
 9248        &mut self,
 9249        lines: u32,
 9250        direction: ExpandExcerptDirection,
 9251        cx: &mut ViewContext<Self>,
 9252    ) {
 9253        let selections = self.selections.disjoint_anchors();
 9254
 9255        let lines = if lines == 0 {
 9256            EditorSettings::get_global(cx).expand_excerpt_lines
 9257        } else {
 9258            lines
 9259        };
 9260
 9261        self.buffer.update(cx, |buffer, cx| {
 9262            buffer.expand_excerpts(
 9263                selections
 9264                    .iter()
 9265                    .map(|selection| selection.head().excerpt_id)
 9266                    .dedup(),
 9267                lines,
 9268                direction,
 9269                cx,
 9270            )
 9271        })
 9272    }
 9273
 9274    pub fn expand_excerpt(
 9275        &mut self,
 9276        excerpt: ExcerptId,
 9277        direction: ExpandExcerptDirection,
 9278        cx: &mut ViewContext<Self>,
 9279    ) {
 9280        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9281        self.buffer.update(cx, |buffer, cx| {
 9282            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9283        })
 9284    }
 9285
 9286    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9287        self.go_to_diagnostic_impl(Direction::Next, cx)
 9288    }
 9289
 9290    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9291        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9292    }
 9293
 9294    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9295        let buffer = self.buffer.read(cx).snapshot(cx);
 9296        let selection = self.selections.newest::<usize>(cx);
 9297
 9298        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9299        if direction == Direction::Next {
 9300            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9301                let (group_id, jump_to) = popover.activation_info();
 9302                if self.activate_diagnostics(group_id, cx) {
 9303                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9304                        let mut new_selection = s.newest_anchor().clone();
 9305                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9306                        s.select_anchors(vec![new_selection.clone()]);
 9307                    });
 9308                }
 9309                return;
 9310            }
 9311        }
 9312
 9313        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9314            active_diagnostics
 9315                .primary_range
 9316                .to_offset(&buffer)
 9317                .to_inclusive()
 9318        });
 9319        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9320            if active_primary_range.contains(&selection.head()) {
 9321                *active_primary_range.start()
 9322            } else {
 9323                selection.head()
 9324            }
 9325        } else {
 9326            selection.head()
 9327        };
 9328        let snapshot = self.snapshot(cx);
 9329        loop {
 9330            let diagnostics = if direction == Direction::Prev {
 9331                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9332            } else {
 9333                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9334            }
 9335            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9336            let group = diagnostics
 9337                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9338                // be sorted in a stable way
 9339                // skip until we are at current active diagnostic, if it exists
 9340                .skip_while(|entry| {
 9341                    (match direction {
 9342                        Direction::Prev => entry.range.start >= search_start,
 9343                        Direction::Next => entry.range.start <= search_start,
 9344                    }) && self
 9345                        .active_diagnostics
 9346                        .as_ref()
 9347                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9348                })
 9349                .find_map(|entry| {
 9350                    if entry.diagnostic.is_primary
 9351                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9352                        && !entry.range.is_empty()
 9353                        // if we match with the active diagnostic, skip it
 9354                        && Some(entry.diagnostic.group_id)
 9355                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9356                    {
 9357                        Some((entry.range, entry.diagnostic.group_id))
 9358                    } else {
 9359                        None
 9360                    }
 9361                });
 9362
 9363            if let Some((primary_range, group_id)) = group {
 9364                if self.activate_diagnostics(group_id, cx) {
 9365                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9366                        s.select(vec![Selection {
 9367                            id: selection.id,
 9368                            start: primary_range.start,
 9369                            end: primary_range.start,
 9370                            reversed: false,
 9371                            goal: SelectionGoal::None,
 9372                        }]);
 9373                    });
 9374                }
 9375                break;
 9376            } else {
 9377                // Cycle around to the start of the buffer, potentially moving back to the start of
 9378                // the currently active diagnostic.
 9379                active_primary_range.take();
 9380                if direction == Direction::Prev {
 9381                    if search_start == buffer.len() {
 9382                        break;
 9383                    } else {
 9384                        search_start = buffer.len();
 9385                    }
 9386                } else if search_start == 0 {
 9387                    break;
 9388                } else {
 9389                    search_start = 0;
 9390                }
 9391            }
 9392        }
 9393    }
 9394
 9395    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9396        let snapshot = self
 9397            .display_map
 9398            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9399        let selection = self.selections.newest::<Point>(cx);
 9400        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9401    }
 9402
 9403    fn go_to_hunk_after_position(
 9404        &mut self,
 9405        snapshot: &DisplaySnapshot,
 9406        position: Point,
 9407        cx: &mut ViewContext<'_, Editor>,
 9408    ) -> Option<MultiBufferDiffHunk> {
 9409        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9410            snapshot,
 9411            position,
 9412            false,
 9413            snapshot
 9414                .buffer_snapshot
 9415                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9416            cx,
 9417        ) {
 9418            return Some(hunk);
 9419        }
 9420
 9421        let wrapped_point = Point::zero();
 9422        self.go_to_next_hunk_in_direction(
 9423            snapshot,
 9424            wrapped_point,
 9425            true,
 9426            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9427                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9428            ),
 9429            cx,
 9430        )
 9431    }
 9432
 9433    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9434        let snapshot = self
 9435            .display_map
 9436            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9437        let selection = self.selections.newest::<Point>(cx);
 9438
 9439        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9440    }
 9441
 9442    fn go_to_hunk_before_position(
 9443        &mut self,
 9444        snapshot: &DisplaySnapshot,
 9445        position: Point,
 9446        cx: &mut ViewContext<'_, Editor>,
 9447    ) -> Option<MultiBufferDiffHunk> {
 9448        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9449            snapshot,
 9450            position,
 9451            false,
 9452            snapshot
 9453                .buffer_snapshot
 9454                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9455            cx,
 9456        ) {
 9457            return Some(hunk);
 9458        }
 9459
 9460        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9461        self.go_to_next_hunk_in_direction(
 9462            snapshot,
 9463            wrapped_point,
 9464            true,
 9465            snapshot
 9466                .buffer_snapshot
 9467                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9468            cx,
 9469        )
 9470    }
 9471
 9472    fn go_to_next_hunk_in_direction(
 9473        &mut self,
 9474        snapshot: &DisplaySnapshot,
 9475        initial_point: Point,
 9476        is_wrapped: bool,
 9477        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9478        cx: &mut ViewContext<Editor>,
 9479    ) -> Option<MultiBufferDiffHunk> {
 9480        let display_point = initial_point.to_display_point(snapshot);
 9481        let mut hunks = hunks
 9482            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9483            .filter(|(display_hunk, _)| {
 9484                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9485            })
 9486            .dedup();
 9487
 9488        if let Some((display_hunk, hunk)) = hunks.next() {
 9489            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9490                let row = display_hunk.start_display_row();
 9491                let point = DisplayPoint::new(row, 0);
 9492                s.select_display_ranges([point..point]);
 9493            });
 9494
 9495            Some(hunk)
 9496        } else {
 9497            None
 9498        }
 9499    }
 9500
 9501    pub fn go_to_definition(
 9502        &mut self,
 9503        _: &GoToDefinition,
 9504        cx: &mut ViewContext<Self>,
 9505    ) -> Task<Result<Navigated>> {
 9506        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9507        cx.spawn(|editor, mut cx| async move {
 9508            if definition.await? == Navigated::Yes {
 9509                return Ok(Navigated::Yes);
 9510            }
 9511            match editor.update(&mut cx, |editor, cx| {
 9512                editor.find_all_references(&FindAllReferences, cx)
 9513            })? {
 9514                Some(references) => references.await,
 9515                None => Ok(Navigated::No),
 9516            }
 9517        })
 9518    }
 9519
 9520    pub fn go_to_declaration(
 9521        &mut self,
 9522        _: &GoToDeclaration,
 9523        cx: &mut ViewContext<Self>,
 9524    ) -> Task<Result<Navigated>> {
 9525        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9526    }
 9527
 9528    pub fn go_to_declaration_split(
 9529        &mut self,
 9530        _: &GoToDeclaration,
 9531        cx: &mut ViewContext<Self>,
 9532    ) -> Task<Result<Navigated>> {
 9533        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9534    }
 9535
 9536    pub fn go_to_implementation(
 9537        &mut self,
 9538        _: &GoToImplementation,
 9539        cx: &mut ViewContext<Self>,
 9540    ) -> Task<Result<Navigated>> {
 9541        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9542    }
 9543
 9544    pub fn go_to_implementation_split(
 9545        &mut self,
 9546        _: &GoToImplementationSplit,
 9547        cx: &mut ViewContext<Self>,
 9548    ) -> Task<Result<Navigated>> {
 9549        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9550    }
 9551
 9552    pub fn go_to_type_definition(
 9553        &mut self,
 9554        _: &GoToTypeDefinition,
 9555        cx: &mut ViewContext<Self>,
 9556    ) -> Task<Result<Navigated>> {
 9557        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9558    }
 9559
 9560    pub fn go_to_definition_split(
 9561        &mut self,
 9562        _: &GoToDefinitionSplit,
 9563        cx: &mut ViewContext<Self>,
 9564    ) -> Task<Result<Navigated>> {
 9565        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9566    }
 9567
 9568    pub fn go_to_type_definition_split(
 9569        &mut self,
 9570        _: &GoToTypeDefinitionSplit,
 9571        cx: &mut ViewContext<Self>,
 9572    ) -> Task<Result<Navigated>> {
 9573        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9574    }
 9575
 9576    fn go_to_definition_of_kind(
 9577        &mut self,
 9578        kind: GotoDefinitionKind,
 9579        split: bool,
 9580        cx: &mut ViewContext<Self>,
 9581    ) -> Task<Result<Navigated>> {
 9582        let Some(workspace) = self.workspace() else {
 9583            return Task::ready(Ok(Navigated::No));
 9584        };
 9585        let buffer = self.buffer.read(cx);
 9586        let head = self.selections.newest::<usize>(cx).head();
 9587        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9588            text_anchor
 9589        } else {
 9590            return Task::ready(Ok(Navigated::No));
 9591        };
 9592
 9593        let project = workspace.read(cx).project().clone();
 9594        let definitions = project.update(cx, |project, cx| match kind {
 9595            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 9596            GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
 9597            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 9598            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 9599        });
 9600
 9601        cx.spawn(|editor, mut cx| async move {
 9602            let definitions = definitions.await?;
 9603            let navigated = editor
 9604                .update(&mut cx, |editor, cx| {
 9605                    editor.navigate_to_hover_links(
 9606                        Some(kind),
 9607                        definitions
 9608                            .into_iter()
 9609                            .filter(|location| {
 9610                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9611                            })
 9612                            .map(HoverLink::Text)
 9613                            .collect::<Vec<_>>(),
 9614                        split,
 9615                        cx,
 9616                    )
 9617                })?
 9618                .await?;
 9619            anyhow::Ok(navigated)
 9620        })
 9621    }
 9622
 9623    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9624        let position = self.selections.newest_anchor().head();
 9625        let Some((buffer, buffer_position)) =
 9626            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9627        else {
 9628            return;
 9629        };
 9630
 9631        cx.spawn(|editor, mut cx| async move {
 9632            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9633                editor.update(&mut cx, |_, cx| {
 9634                    cx.open_url(&url);
 9635                })
 9636            } else {
 9637                Ok(())
 9638            }
 9639        })
 9640        .detach();
 9641    }
 9642
 9643    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9644        let Some(workspace) = self.workspace() else {
 9645            return;
 9646        };
 9647
 9648        let position = self.selections.newest_anchor().head();
 9649
 9650        let Some((buffer, buffer_position)) =
 9651            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9652        else {
 9653            return;
 9654        };
 9655
 9656        let Some(project) = self.project.clone() else {
 9657            return;
 9658        };
 9659
 9660        cx.spawn(|_, mut cx| async move {
 9661            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9662
 9663            if let Some((_, path)) = result {
 9664                workspace
 9665                    .update(&mut cx, |workspace, cx| {
 9666                        workspace.open_resolved_path(path, cx)
 9667                    })?
 9668                    .await?;
 9669            }
 9670            anyhow::Ok(())
 9671        })
 9672        .detach();
 9673    }
 9674
 9675    pub(crate) fn navigate_to_hover_links(
 9676        &mut self,
 9677        kind: Option<GotoDefinitionKind>,
 9678        mut definitions: Vec<HoverLink>,
 9679        split: bool,
 9680        cx: &mut ViewContext<Editor>,
 9681    ) -> Task<Result<Navigated>> {
 9682        // If there is one definition, just open it directly
 9683        if definitions.len() == 1 {
 9684            let definition = definitions.pop().unwrap();
 9685
 9686            enum TargetTaskResult {
 9687                Location(Option<Location>),
 9688                AlreadyNavigated,
 9689            }
 9690
 9691            let target_task = match definition {
 9692                HoverLink::Text(link) => {
 9693                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9694                }
 9695                HoverLink::InlayHint(lsp_location, server_id) => {
 9696                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9697                    cx.background_executor().spawn(async move {
 9698                        let location = computation.await?;
 9699                        Ok(TargetTaskResult::Location(location))
 9700                    })
 9701                }
 9702                HoverLink::Url(url) => {
 9703                    cx.open_url(&url);
 9704                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9705                }
 9706                HoverLink::File(path) => {
 9707                    if let Some(workspace) = self.workspace() {
 9708                        cx.spawn(|_, mut cx| async move {
 9709                            workspace
 9710                                .update(&mut cx, |workspace, cx| {
 9711                                    workspace.open_resolved_path(path, cx)
 9712                                })?
 9713                                .await
 9714                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9715                        })
 9716                    } else {
 9717                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9718                    }
 9719                }
 9720            };
 9721            cx.spawn(|editor, mut cx| async move {
 9722                let target = match target_task.await.context("target resolution task")? {
 9723                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9724                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9725                    TargetTaskResult::Location(Some(target)) => target,
 9726                };
 9727
 9728                editor.update(&mut cx, |editor, cx| {
 9729                    let Some(workspace) = editor.workspace() else {
 9730                        return Navigated::No;
 9731                    };
 9732                    let pane = workspace.read(cx).active_pane().clone();
 9733
 9734                    let range = target.range.to_offset(target.buffer.read(cx));
 9735                    let range = editor.range_for_match(&range);
 9736
 9737                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9738                        let buffer = target.buffer.read(cx);
 9739                        let range = check_multiline_range(buffer, range);
 9740                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9741                            s.select_ranges([range]);
 9742                        });
 9743                    } else {
 9744                        cx.window_context().defer(move |cx| {
 9745                            let target_editor: View<Self> =
 9746                                workspace.update(cx, |workspace, cx| {
 9747                                    let pane = if split {
 9748                                        workspace.adjacent_pane(cx)
 9749                                    } else {
 9750                                        workspace.active_pane().clone()
 9751                                    };
 9752
 9753                                    workspace.open_project_item(
 9754                                        pane,
 9755                                        target.buffer.clone(),
 9756                                        true,
 9757                                        true,
 9758                                        cx,
 9759                                    )
 9760                                });
 9761                            target_editor.update(cx, |target_editor, cx| {
 9762                                // When selecting a definition in a different buffer, disable the nav history
 9763                                // to avoid creating a history entry at the previous cursor location.
 9764                                pane.update(cx, |pane, _| pane.disable_history());
 9765                                let buffer = target.buffer.read(cx);
 9766                                let range = check_multiline_range(buffer, range);
 9767                                target_editor.change_selections(
 9768                                    Some(Autoscroll::focused()),
 9769                                    cx,
 9770                                    |s| {
 9771                                        s.select_ranges([range]);
 9772                                    },
 9773                                );
 9774                                pane.update(cx, |pane, _| pane.enable_history());
 9775                            });
 9776                        });
 9777                    }
 9778                    Navigated::Yes
 9779                })
 9780            })
 9781        } else if !definitions.is_empty() {
 9782            cx.spawn(|editor, mut cx| async move {
 9783                let (title, location_tasks, workspace) = editor
 9784                    .update(&mut cx, |editor, cx| {
 9785                        let tab_kind = match kind {
 9786                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9787                            _ => "Definitions",
 9788                        };
 9789                        let title = definitions
 9790                            .iter()
 9791                            .find_map(|definition| match definition {
 9792                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9793                                    let buffer = origin.buffer.read(cx);
 9794                                    format!(
 9795                                        "{} for {}",
 9796                                        tab_kind,
 9797                                        buffer
 9798                                            .text_for_range(origin.range.clone())
 9799                                            .collect::<String>()
 9800                                    )
 9801                                }),
 9802                                HoverLink::InlayHint(_, _) => None,
 9803                                HoverLink::Url(_) => None,
 9804                                HoverLink::File(_) => None,
 9805                            })
 9806                            .unwrap_or(tab_kind.to_string());
 9807                        let location_tasks = definitions
 9808                            .into_iter()
 9809                            .map(|definition| match definition {
 9810                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9811                                HoverLink::InlayHint(lsp_location, server_id) => {
 9812                                    editor.compute_target_location(lsp_location, server_id, cx)
 9813                                }
 9814                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9815                                HoverLink::File(_) => Task::ready(Ok(None)),
 9816                            })
 9817                            .collect::<Vec<_>>();
 9818                        (title, location_tasks, editor.workspace().clone())
 9819                    })
 9820                    .context("location tasks preparation")?;
 9821
 9822                let locations = future::join_all(location_tasks)
 9823                    .await
 9824                    .into_iter()
 9825                    .filter_map(|location| location.transpose())
 9826                    .collect::<Result<_>>()
 9827                    .context("location tasks")?;
 9828
 9829                let Some(workspace) = workspace else {
 9830                    return Ok(Navigated::No);
 9831                };
 9832                let opened = workspace
 9833                    .update(&mut cx, |workspace, cx| {
 9834                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9835                    })
 9836                    .ok();
 9837
 9838                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9839            })
 9840        } else {
 9841            Task::ready(Ok(Navigated::No))
 9842        }
 9843    }
 9844
 9845    fn compute_target_location(
 9846        &self,
 9847        lsp_location: lsp::Location,
 9848        server_id: LanguageServerId,
 9849        cx: &mut ViewContext<Editor>,
 9850    ) -> Task<anyhow::Result<Option<Location>>> {
 9851        let Some(project) = self.project.clone() else {
 9852            return Task::Ready(Some(Ok(None)));
 9853        };
 9854
 9855        cx.spawn(move |editor, mut cx| async move {
 9856            let location_task = editor.update(&mut cx, |editor, cx| {
 9857                project.update(cx, |project, cx| {
 9858                    let language_server_name =
 9859                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9860                            project
 9861                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9862                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9863                        });
 9864                    language_server_name.map(|language_server_name| {
 9865                        project.open_local_buffer_via_lsp(
 9866                            lsp_location.uri.clone(),
 9867                            server_id,
 9868                            language_server_name,
 9869                            cx,
 9870                        )
 9871                    })
 9872                })
 9873            })?;
 9874            let location = match location_task {
 9875                Some(task) => Some({
 9876                    let target_buffer_handle = task.await.context("open local buffer")?;
 9877                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9878                        let target_start = target_buffer
 9879                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9880                        let target_end = target_buffer
 9881                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9882                        target_buffer.anchor_after(target_start)
 9883                            ..target_buffer.anchor_before(target_end)
 9884                    })?;
 9885                    Location {
 9886                        buffer: target_buffer_handle,
 9887                        range,
 9888                    }
 9889                }),
 9890                None => None,
 9891            };
 9892            Ok(location)
 9893        })
 9894    }
 9895
 9896    pub fn find_all_references(
 9897        &mut self,
 9898        _: &FindAllReferences,
 9899        cx: &mut ViewContext<Self>,
 9900    ) -> Option<Task<Result<Navigated>>> {
 9901        let multi_buffer = self.buffer.read(cx);
 9902        let selection = self.selections.newest::<usize>(cx);
 9903        let head = selection.head();
 9904
 9905        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9906        let head_anchor = multi_buffer_snapshot.anchor_at(
 9907            head,
 9908            if head < selection.tail() {
 9909                Bias::Right
 9910            } else {
 9911                Bias::Left
 9912            },
 9913        );
 9914
 9915        match self
 9916            .find_all_references_task_sources
 9917            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9918        {
 9919            Ok(_) => {
 9920                log::info!(
 9921                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9922                );
 9923                return None;
 9924            }
 9925            Err(i) => {
 9926                self.find_all_references_task_sources.insert(i, head_anchor);
 9927            }
 9928        }
 9929
 9930        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9931        let workspace = self.workspace()?;
 9932        let project = workspace.read(cx).project().clone();
 9933        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9934        Some(cx.spawn(|editor, mut cx| async move {
 9935            let _cleanup = defer({
 9936                let mut cx = cx.clone();
 9937                move || {
 9938                    let _ = editor.update(&mut cx, |editor, _| {
 9939                        if let Ok(i) =
 9940                            editor
 9941                                .find_all_references_task_sources
 9942                                .binary_search_by(|anchor| {
 9943                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9944                                })
 9945                        {
 9946                            editor.find_all_references_task_sources.remove(i);
 9947                        }
 9948                    });
 9949                }
 9950            });
 9951
 9952            let locations = references.await?;
 9953            if locations.is_empty() {
 9954                return anyhow::Ok(Navigated::No);
 9955            }
 9956
 9957            workspace.update(&mut cx, |workspace, cx| {
 9958                let title = locations
 9959                    .first()
 9960                    .as_ref()
 9961                    .map(|location| {
 9962                        let buffer = location.buffer.read(cx);
 9963                        format!(
 9964                            "References to `{}`",
 9965                            buffer
 9966                                .text_for_range(location.range.clone())
 9967                                .collect::<String>()
 9968                        )
 9969                    })
 9970                    .unwrap();
 9971                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9972                Navigated::Yes
 9973            })
 9974        }))
 9975    }
 9976
 9977    /// Opens a multibuffer with the given project locations in it
 9978    pub fn open_locations_in_multibuffer(
 9979        workspace: &mut Workspace,
 9980        mut locations: Vec<Location>,
 9981        title: String,
 9982        split: bool,
 9983        cx: &mut ViewContext<Workspace>,
 9984    ) {
 9985        // If there are multiple definitions, open them in a multibuffer
 9986        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9987        let mut locations = locations.into_iter().peekable();
 9988        let mut ranges_to_highlight = Vec::new();
 9989        let capability = workspace.project().read(cx).capability();
 9990
 9991        let excerpt_buffer = cx.new_model(|cx| {
 9992            let mut multibuffer = MultiBuffer::new(capability);
 9993            while let Some(location) = locations.next() {
 9994                let buffer = location.buffer.read(cx);
 9995                let mut ranges_for_buffer = Vec::new();
 9996                let range = location.range.to_offset(buffer);
 9997                ranges_for_buffer.push(range.clone());
 9998
 9999                while let Some(next_location) = locations.peek() {
10000                    if next_location.buffer == location.buffer {
10001                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10002                        locations.next();
10003                    } else {
10004                        break;
10005                    }
10006                }
10007
10008                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10009                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10010                    location.buffer.clone(),
10011                    ranges_for_buffer,
10012                    DEFAULT_MULTIBUFFER_CONTEXT,
10013                    cx,
10014                ))
10015            }
10016
10017            multibuffer.with_title(title)
10018        });
10019
10020        let editor = cx.new_view(|cx| {
10021            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10022        });
10023        editor.update(cx, |editor, cx| {
10024            if let Some(first_range) = ranges_to_highlight.first() {
10025                editor.change_selections(None, cx, |selections| {
10026                    selections.clear_disjoint();
10027                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10028                });
10029            }
10030            editor.highlight_background::<Self>(
10031                &ranges_to_highlight,
10032                |theme| theme.editor_highlighted_line_background,
10033                cx,
10034            );
10035        });
10036
10037        let item = Box::new(editor);
10038        let item_id = item.item_id();
10039
10040        if split {
10041            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10042        } else {
10043            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10044                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10045                    pane.close_current_preview_item(cx)
10046                } else {
10047                    None
10048                }
10049            });
10050            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10051        }
10052        workspace.active_pane().update(cx, |pane, cx| {
10053            pane.set_preview_item_id(Some(item_id), cx);
10054        });
10055    }
10056
10057    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10058        use language::ToOffset as _;
10059
10060        let project = self.project.clone()?;
10061        let selection = self.selections.newest_anchor().clone();
10062        let (cursor_buffer, cursor_buffer_position) = self
10063            .buffer
10064            .read(cx)
10065            .text_anchor_for_position(selection.head(), cx)?;
10066        let (tail_buffer, cursor_buffer_position_end) = self
10067            .buffer
10068            .read(cx)
10069            .text_anchor_for_position(selection.tail(), cx)?;
10070        if tail_buffer != cursor_buffer {
10071            return None;
10072        }
10073
10074        let snapshot = cursor_buffer.read(cx).snapshot();
10075        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10076        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10077        let prepare_rename = project.update(cx, |project, cx| {
10078            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10079        });
10080        drop(snapshot);
10081
10082        Some(cx.spawn(|this, mut cx| async move {
10083            let rename_range = if let Some(range) = prepare_rename.await? {
10084                Some(range)
10085            } else {
10086                this.update(&mut cx, |this, cx| {
10087                    let buffer = this.buffer.read(cx).snapshot(cx);
10088                    let mut buffer_highlights = this
10089                        .document_highlights_for_position(selection.head(), &buffer)
10090                        .filter(|highlight| {
10091                            highlight.start.excerpt_id == selection.head().excerpt_id
10092                                && highlight.end.excerpt_id == selection.head().excerpt_id
10093                        });
10094                    buffer_highlights
10095                        .next()
10096                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10097                })?
10098            };
10099            if let Some(rename_range) = rename_range {
10100                this.update(&mut cx, |this, cx| {
10101                    let snapshot = cursor_buffer.read(cx).snapshot();
10102                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10103                    let cursor_offset_in_rename_range =
10104                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10105                    let cursor_offset_in_rename_range_end =
10106                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10107
10108                    this.take_rename(false, cx);
10109                    let buffer = this.buffer.read(cx).read(cx);
10110                    let cursor_offset = selection.head().to_offset(&buffer);
10111                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10112                    let rename_end = rename_start + rename_buffer_range.len();
10113                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10114                    let mut old_highlight_id = None;
10115                    let old_name: Arc<str> = buffer
10116                        .chunks(rename_start..rename_end, true)
10117                        .map(|chunk| {
10118                            if old_highlight_id.is_none() {
10119                                old_highlight_id = chunk.syntax_highlight_id;
10120                            }
10121                            chunk.text
10122                        })
10123                        .collect::<String>()
10124                        .into();
10125
10126                    drop(buffer);
10127
10128                    // Position the selection in the rename editor so that it matches the current selection.
10129                    this.show_local_selections = false;
10130                    let rename_editor = cx.new_view(|cx| {
10131                        let mut editor = Editor::single_line(cx);
10132                        editor.buffer.update(cx, |buffer, cx| {
10133                            buffer.edit([(0..0, old_name.clone())], None, cx)
10134                        });
10135                        let rename_selection_range = match cursor_offset_in_rename_range
10136                            .cmp(&cursor_offset_in_rename_range_end)
10137                        {
10138                            Ordering::Equal => {
10139                                editor.select_all(&SelectAll, cx);
10140                                return editor;
10141                            }
10142                            Ordering::Less => {
10143                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10144                            }
10145                            Ordering::Greater => {
10146                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10147                            }
10148                        };
10149                        if rename_selection_range.end > old_name.len() {
10150                            editor.select_all(&SelectAll, cx);
10151                        } else {
10152                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10153                                s.select_ranges([rename_selection_range]);
10154                            });
10155                        }
10156                        editor
10157                    });
10158                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10159                        if e == &EditorEvent::Focused {
10160                            cx.emit(EditorEvent::FocusedIn)
10161                        }
10162                    })
10163                    .detach();
10164
10165                    let write_highlights =
10166                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10167                    let read_highlights =
10168                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10169                    let ranges = write_highlights
10170                        .iter()
10171                        .flat_map(|(_, ranges)| ranges.iter())
10172                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10173                        .cloned()
10174                        .collect();
10175
10176                    this.highlight_text::<Rename>(
10177                        ranges,
10178                        HighlightStyle {
10179                            fade_out: Some(0.6),
10180                            ..Default::default()
10181                        },
10182                        cx,
10183                    );
10184                    let rename_focus_handle = rename_editor.focus_handle(cx);
10185                    cx.focus(&rename_focus_handle);
10186                    let block_id = this.insert_blocks(
10187                        [BlockProperties {
10188                            style: BlockStyle::Flex,
10189                            position: range.start,
10190                            height: 1,
10191                            render: Box::new({
10192                                let rename_editor = rename_editor.clone();
10193                                move |cx: &mut BlockContext| {
10194                                    let mut text_style = cx.editor_style.text.clone();
10195                                    if let Some(highlight_style) = old_highlight_id
10196                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10197                                    {
10198                                        text_style = text_style.highlight(highlight_style);
10199                                    }
10200                                    div()
10201                                        .pl(cx.anchor_x)
10202                                        .child(EditorElement::new(
10203                                            &rename_editor,
10204                                            EditorStyle {
10205                                                background: cx.theme().system().transparent,
10206                                                local_player: cx.editor_style.local_player,
10207                                                text: text_style,
10208                                                scrollbar_width: cx.editor_style.scrollbar_width,
10209                                                syntax: cx.editor_style.syntax.clone(),
10210                                                status: cx.editor_style.status.clone(),
10211                                                inlay_hints_style: HighlightStyle {
10212                                                    font_weight: Some(FontWeight::BOLD),
10213                                                    ..make_inlay_hints_style(cx)
10214                                                },
10215                                                suggestions_style: HighlightStyle {
10216                                                    color: Some(cx.theme().status().predictive),
10217                                                    ..HighlightStyle::default()
10218                                                },
10219                                                ..EditorStyle::default()
10220                                            },
10221                                        ))
10222                                        .into_any_element()
10223                                }
10224                            }),
10225                            disposition: BlockDisposition::Below,
10226                            priority: 0,
10227                        }],
10228                        Some(Autoscroll::fit()),
10229                        cx,
10230                    )[0];
10231                    this.pending_rename = Some(RenameState {
10232                        range,
10233                        old_name,
10234                        editor: rename_editor,
10235                        block_id,
10236                    });
10237                })?;
10238            }
10239
10240            Ok(())
10241        }))
10242    }
10243
10244    pub fn confirm_rename(
10245        &mut self,
10246        _: &ConfirmRename,
10247        cx: &mut ViewContext<Self>,
10248    ) -> Option<Task<Result<()>>> {
10249        let rename = self.take_rename(false, cx)?;
10250        let workspace = self.workspace()?;
10251        let (start_buffer, start) = self
10252            .buffer
10253            .read(cx)
10254            .text_anchor_for_position(rename.range.start, cx)?;
10255        let (end_buffer, end) = self
10256            .buffer
10257            .read(cx)
10258            .text_anchor_for_position(rename.range.end, cx)?;
10259        if start_buffer != end_buffer {
10260            return None;
10261        }
10262
10263        let buffer = start_buffer;
10264        let range = start..end;
10265        let old_name = rename.old_name;
10266        let new_name = rename.editor.read(cx).text(cx);
10267
10268        let rename = workspace
10269            .read(cx)
10270            .project()
10271            .clone()
10272            .update(cx, |project, cx| {
10273                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10274            });
10275        let workspace = workspace.downgrade();
10276
10277        Some(cx.spawn(|editor, mut cx| async move {
10278            let project_transaction = rename.await?;
10279            Self::open_project_transaction(
10280                &editor,
10281                workspace,
10282                project_transaction,
10283                format!("Rename: {}{}", old_name, new_name),
10284                cx.clone(),
10285            )
10286            .await?;
10287
10288            editor.update(&mut cx, |editor, cx| {
10289                editor.refresh_document_highlights(cx);
10290            })?;
10291            Ok(())
10292        }))
10293    }
10294
10295    fn take_rename(
10296        &mut self,
10297        moving_cursor: bool,
10298        cx: &mut ViewContext<Self>,
10299    ) -> Option<RenameState> {
10300        let rename = self.pending_rename.take()?;
10301        if rename.editor.focus_handle(cx).is_focused(cx) {
10302            cx.focus(&self.focus_handle);
10303        }
10304
10305        self.remove_blocks(
10306            [rename.block_id].into_iter().collect(),
10307            Some(Autoscroll::fit()),
10308            cx,
10309        );
10310        self.clear_highlights::<Rename>(cx);
10311        self.show_local_selections = true;
10312
10313        if moving_cursor {
10314            let rename_editor = rename.editor.read(cx);
10315            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10316
10317            // Update the selection to match the position of the selection inside
10318            // the rename editor.
10319            let snapshot = self.buffer.read(cx).read(cx);
10320            let rename_range = rename.range.to_offset(&snapshot);
10321            let cursor_in_editor = snapshot
10322                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10323                .min(rename_range.end);
10324            drop(snapshot);
10325
10326            self.change_selections(None, cx, |s| {
10327                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10328            });
10329        } else {
10330            self.refresh_document_highlights(cx);
10331        }
10332
10333        Some(rename)
10334    }
10335
10336    pub fn pending_rename(&self) -> Option<&RenameState> {
10337        self.pending_rename.as_ref()
10338    }
10339
10340    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10341        let project = match &self.project {
10342            Some(project) => project.clone(),
10343            None => return None,
10344        };
10345
10346        Some(self.perform_format(project, FormatTrigger::Manual, cx))
10347    }
10348
10349    fn perform_format(
10350        &mut self,
10351        project: Model<Project>,
10352        trigger: FormatTrigger,
10353        cx: &mut ViewContext<Self>,
10354    ) -> Task<Result<()>> {
10355        let buffer = self.buffer().clone();
10356        let mut buffers = buffer.read(cx).all_buffers();
10357        if trigger == FormatTrigger::Save {
10358            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10359        }
10360
10361        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10362        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10363
10364        cx.spawn(|_, mut cx| async move {
10365            let transaction = futures::select_biased! {
10366                () = timeout => {
10367                    log::warn!("timed out waiting for formatting");
10368                    None
10369                }
10370                transaction = format.log_err().fuse() => transaction,
10371            };
10372
10373            buffer
10374                .update(&mut cx, |buffer, cx| {
10375                    if let Some(transaction) = transaction {
10376                        if !buffer.is_singleton() {
10377                            buffer.push_transaction(&transaction.0, cx);
10378                        }
10379                    }
10380
10381                    cx.notify();
10382                })
10383                .ok();
10384
10385            Ok(())
10386        })
10387    }
10388
10389    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10390        if let Some(project) = self.project.clone() {
10391            self.buffer.update(cx, |multi_buffer, cx| {
10392                project.update(cx, |project, cx| {
10393                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10394                });
10395            })
10396        }
10397    }
10398
10399    fn cancel_language_server_work(
10400        &mut self,
10401        _: &CancelLanguageServerWork,
10402        cx: &mut ViewContext<Self>,
10403    ) {
10404        if let Some(project) = self.project.clone() {
10405            self.buffer.update(cx, |multi_buffer, cx| {
10406                project.update(cx, |project, cx| {
10407                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10408                });
10409            })
10410        }
10411    }
10412
10413    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10414        cx.show_character_palette();
10415    }
10416
10417    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10418        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10419            let buffer = self.buffer.read(cx).snapshot(cx);
10420            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10421            let is_valid = buffer
10422                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10423                .any(|entry| {
10424                    entry.diagnostic.is_primary
10425                        && !entry.range.is_empty()
10426                        && entry.range.start == primary_range_start
10427                        && entry.diagnostic.message == active_diagnostics.primary_message
10428                });
10429
10430            if is_valid != active_diagnostics.is_valid {
10431                active_diagnostics.is_valid = is_valid;
10432                let mut new_styles = HashMap::default();
10433                for (block_id, diagnostic) in &active_diagnostics.blocks {
10434                    new_styles.insert(
10435                        *block_id,
10436                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10437                    );
10438                }
10439                self.display_map.update(cx, |display_map, _cx| {
10440                    display_map.replace_blocks(new_styles)
10441                });
10442            }
10443        }
10444    }
10445
10446    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10447        self.dismiss_diagnostics(cx);
10448        let snapshot = self.snapshot(cx);
10449        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10450            let buffer = self.buffer.read(cx).snapshot(cx);
10451
10452            let mut primary_range = None;
10453            let mut primary_message = None;
10454            let mut group_end = Point::zero();
10455            let diagnostic_group = buffer
10456                .diagnostic_group::<MultiBufferPoint>(group_id)
10457                .filter_map(|entry| {
10458                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10459                        && (entry.range.start.row == entry.range.end.row
10460                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10461                    {
10462                        return None;
10463                    }
10464                    if entry.range.end > group_end {
10465                        group_end = entry.range.end;
10466                    }
10467                    if entry.diagnostic.is_primary {
10468                        primary_range = Some(entry.range.clone());
10469                        primary_message = Some(entry.diagnostic.message.clone());
10470                    }
10471                    Some(entry)
10472                })
10473                .collect::<Vec<_>>();
10474            let primary_range = primary_range?;
10475            let primary_message = primary_message?;
10476            let primary_range =
10477                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10478
10479            let blocks = display_map
10480                .insert_blocks(
10481                    diagnostic_group.iter().map(|entry| {
10482                        let diagnostic = entry.diagnostic.clone();
10483                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10484                        BlockProperties {
10485                            style: BlockStyle::Fixed,
10486                            position: buffer.anchor_after(entry.range.start),
10487                            height: message_height,
10488                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10489                            disposition: BlockDisposition::Below,
10490                            priority: 0,
10491                        }
10492                    }),
10493                    cx,
10494                )
10495                .into_iter()
10496                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10497                .collect();
10498
10499            Some(ActiveDiagnosticGroup {
10500                primary_range,
10501                primary_message,
10502                group_id,
10503                blocks,
10504                is_valid: true,
10505            })
10506        });
10507        self.active_diagnostics.is_some()
10508    }
10509
10510    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10511        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10512            self.display_map.update(cx, |display_map, cx| {
10513                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10514            });
10515            cx.notify();
10516        }
10517    }
10518
10519    pub fn set_selections_from_remote(
10520        &mut self,
10521        selections: Vec<Selection<Anchor>>,
10522        pending_selection: Option<Selection<Anchor>>,
10523        cx: &mut ViewContext<Self>,
10524    ) {
10525        let old_cursor_position = self.selections.newest_anchor().head();
10526        self.selections.change_with(cx, |s| {
10527            s.select_anchors(selections);
10528            if let Some(pending_selection) = pending_selection {
10529                s.set_pending(pending_selection, SelectMode::Character);
10530            } else {
10531                s.clear_pending();
10532            }
10533        });
10534        self.selections_did_change(false, &old_cursor_position, true, cx);
10535    }
10536
10537    fn push_to_selection_history(&mut self) {
10538        self.selection_history.push(SelectionHistoryEntry {
10539            selections: self.selections.disjoint_anchors(),
10540            select_next_state: self.select_next_state.clone(),
10541            select_prev_state: self.select_prev_state.clone(),
10542            add_selections_state: self.add_selections_state.clone(),
10543        });
10544    }
10545
10546    pub fn transact(
10547        &mut self,
10548        cx: &mut ViewContext<Self>,
10549        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10550    ) -> Option<TransactionId> {
10551        self.start_transaction_at(Instant::now(), cx);
10552        update(self, cx);
10553        self.end_transaction_at(Instant::now(), cx)
10554    }
10555
10556    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10557        self.end_selection(cx);
10558        if let Some(tx_id) = self
10559            .buffer
10560            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10561        {
10562            self.selection_history
10563                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10564            cx.emit(EditorEvent::TransactionBegun {
10565                transaction_id: tx_id,
10566            })
10567        }
10568    }
10569
10570    fn end_transaction_at(
10571        &mut self,
10572        now: Instant,
10573        cx: &mut ViewContext<Self>,
10574    ) -> Option<TransactionId> {
10575        if let Some(transaction_id) = self
10576            .buffer
10577            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10578        {
10579            if let Some((_, end_selections)) =
10580                self.selection_history.transaction_mut(transaction_id)
10581            {
10582                *end_selections = Some(self.selections.disjoint_anchors());
10583            } else {
10584                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10585            }
10586
10587            cx.emit(EditorEvent::Edited { transaction_id });
10588            Some(transaction_id)
10589        } else {
10590            None
10591        }
10592    }
10593
10594    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10595        let selection = self.selections.newest::<Point>(cx);
10596
10597        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10598        let range = if selection.is_empty() {
10599            let point = selection.head().to_display_point(&display_map);
10600            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10601            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10602                .to_point(&display_map);
10603            start..end
10604        } else {
10605            selection.range()
10606        };
10607        if display_map.folds_in_range(range).next().is_some() {
10608            self.unfold_lines(&Default::default(), cx)
10609        } else {
10610            self.fold(&Default::default(), cx)
10611        }
10612    }
10613
10614    pub fn toggle_fold_recursive(
10615        &mut self,
10616        _: &actions::ToggleFoldRecursive,
10617        cx: &mut ViewContext<Self>,
10618    ) {
10619        let selection = self.selections.newest::<Point>(cx);
10620
10621        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10622        let range = if selection.is_empty() {
10623            let point = selection.head().to_display_point(&display_map);
10624            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10625            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10626                .to_point(&display_map);
10627            start..end
10628        } else {
10629            selection.range()
10630        };
10631        if display_map.folds_in_range(range).next().is_some() {
10632            self.unfold_recursive(&Default::default(), cx)
10633        } else {
10634            self.fold_recursive(&Default::default(), cx)
10635        }
10636    }
10637
10638    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10639        let mut fold_ranges = Vec::new();
10640        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10641        let selections = self.selections.all_adjusted(cx);
10642
10643        for selection in selections {
10644            let range = selection.range().sorted();
10645            let buffer_start_row = range.start.row;
10646
10647            if range.start.row != range.end.row {
10648                let mut found = false;
10649                let mut row = range.start.row;
10650                while row <= range.end.row {
10651                    if let Some((foldable_range, fold_text)) =
10652                        { display_map.foldable_range(MultiBufferRow(row)) }
10653                    {
10654                        found = true;
10655                        row = foldable_range.end.row + 1;
10656                        fold_ranges.push((foldable_range, fold_text));
10657                    } else {
10658                        row += 1
10659                    }
10660                }
10661                if found {
10662                    continue;
10663                }
10664            }
10665
10666            for row in (0..=range.start.row).rev() {
10667                if let Some((foldable_range, fold_text)) =
10668                    display_map.foldable_range(MultiBufferRow(row))
10669                {
10670                    if foldable_range.end.row >= buffer_start_row {
10671                        fold_ranges.push((foldable_range, fold_text));
10672                        if row <= range.start.row {
10673                            break;
10674                        }
10675                    }
10676                }
10677            }
10678        }
10679
10680        self.fold_ranges(fold_ranges, true, cx);
10681    }
10682
10683    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10684        let mut fold_ranges = Vec::new();
10685        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10686
10687        for row in 0..display_map.max_buffer_row().0 {
10688            if let Some((foldable_range, fold_text)) =
10689                display_map.foldable_range(MultiBufferRow(row))
10690            {
10691                fold_ranges.push((foldable_range, fold_text));
10692            }
10693        }
10694
10695        self.fold_ranges(fold_ranges, true, cx);
10696    }
10697
10698    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10699        let mut fold_ranges = Vec::new();
10700        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10701        let selections = self.selections.all_adjusted(cx);
10702
10703        for selection in selections {
10704            let range = selection.range().sorted();
10705            let buffer_start_row = range.start.row;
10706
10707            if range.start.row != range.end.row {
10708                let mut found = false;
10709                for row in range.start.row..=range.end.row {
10710                    if let Some((foldable_range, fold_text)) =
10711                        { display_map.foldable_range(MultiBufferRow(row)) }
10712                    {
10713                        found = true;
10714                        fold_ranges.push((foldable_range, fold_text));
10715                    }
10716                }
10717                if found {
10718                    continue;
10719                }
10720            }
10721
10722            for row in (0..=range.start.row).rev() {
10723                if let Some((foldable_range, fold_text)) =
10724                    display_map.foldable_range(MultiBufferRow(row))
10725                {
10726                    if foldable_range.end.row >= buffer_start_row {
10727                        fold_ranges.push((foldable_range, fold_text));
10728                    } else {
10729                        break;
10730                    }
10731                }
10732            }
10733        }
10734
10735        self.fold_ranges(fold_ranges, true, cx);
10736    }
10737
10738    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10739        let buffer_row = fold_at.buffer_row;
10740        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10741
10742        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10743            let autoscroll = self
10744                .selections
10745                .all::<Point>(cx)
10746                .iter()
10747                .any(|selection| fold_range.overlaps(&selection.range()));
10748
10749            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10750        }
10751    }
10752
10753    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10754        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10755        let buffer = &display_map.buffer_snapshot;
10756        let selections = self.selections.all::<Point>(cx);
10757        let ranges = selections
10758            .iter()
10759            .map(|s| {
10760                let range = s.display_range(&display_map).sorted();
10761                let mut start = range.start.to_point(&display_map);
10762                let mut end = range.end.to_point(&display_map);
10763                start.column = 0;
10764                end.column = buffer.line_len(MultiBufferRow(end.row));
10765                start..end
10766            })
10767            .collect::<Vec<_>>();
10768
10769        self.unfold_ranges(ranges, true, true, cx);
10770    }
10771
10772    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10773        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10774        let selections = self.selections.all::<Point>(cx);
10775        let ranges = selections
10776            .iter()
10777            .map(|s| {
10778                let mut range = s.display_range(&display_map).sorted();
10779                *range.start.column_mut() = 0;
10780                *range.end.column_mut() = display_map.line_len(range.end.row());
10781                let start = range.start.to_point(&display_map);
10782                let end = range.end.to_point(&display_map);
10783                start..end
10784            })
10785            .collect::<Vec<_>>();
10786
10787        self.unfold_ranges(ranges, true, true, cx);
10788    }
10789
10790    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10791        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10792
10793        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10794            ..Point::new(
10795                unfold_at.buffer_row.0,
10796                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10797            );
10798
10799        let autoscroll = self
10800            .selections
10801            .all::<Point>(cx)
10802            .iter()
10803            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10804
10805        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10806    }
10807
10808    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10809        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10810        self.unfold_ranges(
10811            [Point::zero()..display_map.max_point().to_point(&display_map)],
10812            true,
10813            true,
10814            cx,
10815        );
10816    }
10817
10818    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10819        let selections = self.selections.all::<Point>(cx);
10820        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10821        let line_mode = self.selections.line_mode;
10822        let ranges = selections.into_iter().map(|s| {
10823            if line_mode {
10824                let start = Point::new(s.start.row, 0);
10825                let end = Point::new(
10826                    s.end.row,
10827                    display_map
10828                        .buffer_snapshot
10829                        .line_len(MultiBufferRow(s.end.row)),
10830                );
10831                (start..end, display_map.fold_placeholder.clone())
10832            } else {
10833                (s.start..s.end, display_map.fold_placeholder.clone())
10834            }
10835        });
10836        self.fold_ranges(ranges, true, cx);
10837    }
10838
10839    pub fn fold_ranges<T: ToOffset + Clone>(
10840        &mut self,
10841        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10842        auto_scroll: bool,
10843        cx: &mut ViewContext<Self>,
10844    ) {
10845        let mut fold_ranges = Vec::new();
10846        let mut buffers_affected = HashMap::default();
10847        let multi_buffer = self.buffer().read(cx);
10848        for (fold_range, fold_text) in ranges {
10849            if let Some((_, buffer, _)) =
10850                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10851            {
10852                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10853            };
10854            fold_ranges.push((fold_range, fold_text));
10855        }
10856
10857        let mut ranges = fold_ranges.into_iter().peekable();
10858        if ranges.peek().is_some() {
10859            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10860
10861            if auto_scroll {
10862                self.request_autoscroll(Autoscroll::fit(), cx);
10863            }
10864
10865            for buffer in buffers_affected.into_values() {
10866                self.sync_expanded_diff_hunks(buffer, cx);
10867            }
10868
10869            cx.notify();
10870
10871            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10872                // Clear diagnostics block when folding a range that contains it.
10873                let snapshot = self.snapshot(cx);
10874                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10875                    drop(snapshot);
10876                    self.active_diagnostics = Some(active_diagnostics);
10877                    self.dismiss_diagnostics(cx);
10878                } else {
10879                    self.active_diagnostics = Some(active_diagnostics);
10880                }
10881            }
10882
10883            self.scrollbar_marker_state.dirty = true;
10884        }
10885    }
10886
10887    pub fn unfold_ranges<T: ToOffset + Clone>(
10888        &mut self,
10889        ranges: impl IntoIterator<Item = Range<T>>,
10890        inclusive: bool,
10891        auto_scroll: bool,
10892        cx: &mut ViewContext<Self>,
10893    ) {
10894        let mut unfold_ranges = Vec::new();
10895        let mut buffers_affected = HashMap::default();
10896        let multi_buffer = self.buffer().read(cx);
10897        for range in ranges {
10898            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10899                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10900            };
10901            unfold_ranges.push(range);
10902        }
10903
10904        let mut ranges = unfold_ranges.into_iter().peekable();
10905        if ranges.peek().is_some() {
10906            self.display_map
10907                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10908            if auto_scroll {
10909                self.request_autoscroll(Autoscroll::fit(), cx);
10910            }
10911
10912            for buffer in buffers_affected.into_values() {
10913                self.sync_expanded_diff_hunks(buffer, cx);
10914            }
10915
10916            cx.notify();
10917            self.scrollbar_marker_state.dirty = true;
10918            self.active_indent_guides_state.dirty = true;
10919        }
10920    }
10921
10922    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10923        self.display_map.read(cx).fold_placeholder.clone()
10924    }
10925
10926    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10927        if hovered != self.gutter_hovered {
10928            self.gutter_hovered = hovered;
10929            cx.notify();
10930        }
10931    }
10932
10933    pub fn insert_blocks(
10934        &mut self,
10935        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10936        autoscroll: Option<Autoscroll>,
10937        cx: &mut ViewContext<Self>,
10938    ) -> Vec<CustomBlockId> {
10939        let blocks = self
10940            .display_map
10941            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10942        if let Some(autoscroll) = autoscroll {
10943            self.request_autoscroll(autoscroll, cx);
10944        }
10945        cx.notify();
10946        blocks
10947    }
10948
10949    pub fn resize_blocks(
10950        &mut self,
10951        heights: HashMap<CustomBlockId, u32>,
10952        autoscroll: Option<Autoscroll>,
10953        cx: &mut ViewContext<Self>,
10954    ) {
10955        self.display_map
10956            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10957        if let Some(autoscroll) = autoscroll {
10958            self.request_autoscroll(autoscroll, cx);
10959        }
10960        cx.notify();
10961    }
10962
10963    pub fn replace_blocks(
10964        &mut self,
10965        renderers: HashMap<CustomBlockId, RenderBlock>,
10966        autoscroll: Option<Autoscroll>,
10967        cx: &mut ViewContext<Self>,
10968    ) {
10969        self.display_map
10970            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10971        if let Some(autoscroll) = autoscroll {
10972            self.request_autoscroll(autoscroll, cx);
10973        }
10974        cx.notify();
10975    }
10976
10977    pub fn remove_blocks(
10978        &mut self,
10979        block_ids: HashSet<CustomBlockId>,
10980        autoscroll: Option<Autoscroll>,
10981        cx: &mut ViewContext<Self>,
10982    ) {
10983        self.display_map.update(cx, |display_map, cx| {
10984            display_map.remove_blocks(block_ids, cx)
10985        });
10986        if let Some(autoscroll) = autoscroll {
10987            self.request_autoscroll(autoscroll, cx);
10988        }
10989        cx.notify();
10990    }
10991
10992    pub fn row_for_block(
10993        &self,
10994        block_id: CustomBlockId,
10995        cx: &mut ViewContext<Self>,
10996    ) -> Option<DisplayRow> {
10997        self.display_map
10998            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10999    }
11000
11001    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11002        self.focused_block = Some(focused_block);
11003    }
11004
11005    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11006        self.focused_block.take()
11007    }
11008
11009    pub fn insert_creases(
11010        &mut self,
11011        creases: impl IntoIterator<Item = Crease>,
11012        cx: &mut ViewContext<Self>,
11013    ) -> Vec<CreaseId> {
11014        self.display_map
11015            .update(cx, |map, cx| map.insert_creases(creases, cx))
11016    }
11017
11018    pub fn remove_creases(
11019        &mut self,
11020        ids: impl IntoIterator<Item = CreaseId>,
11021        cx: &mut ViewContext<Self>,
11022    ) {
11023        self.display_map
11024            .update(cx, |map, cx| map.remove_creases(ids, cx));
11025    }
11026
11027    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11028        self.display_map
11029            .update(cx, |map, cx| map.snapshot(cx))
11030            .longest_row()
11031    }
11032
11033    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11034        self.display_map
11035            .update(cx, |map, cx| map.snapshot(cx))
11036            .max_point()
11037    }
11038
11039    pub fn text(&self, cx: &AppContext) -> String {
11040        self.buffer.read(cx).read(cx).text()
11041    }
11042
11043    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11044        let text = self.text(cx);
11045        let text = text.trim();
11046
11047        if text.is_empty() {
11048            return None;
11049        }
11050
11051        Some(text.to_string())
11052    }
11053
11054    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11055        self.transact(cx, |this, cx| {
11056            this.buffer
11057                .read(cx)
11058                .as_singleton()
11059                .expect("you can only call set_text on editors for singleton buffers")
11060                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11061        });
11062    }
11063
11064    pub fn display_text(&self, cx: &mut AppContext) -> String {
11065        self.display_map
11066            .update(cx, |map, cx| map.snapshot(cx))
11067            .text()
11068    }
11069
11070    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11071        let mut wrap_guides = smallvec::smallvec![];
11072
11073        if self.show_wrap_guides == Some(false) {
11074            return wrap_guides;
11075        }
11076
11077        let settings = self.buffer.read(cx).settings_at(0, cx);
11078        if settings.show_wrap_guides {
11079            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11080                wrap_guides.push((soft_wrap as usize, true));
11081            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11082                wrap_guides.push((soft_wrap as usize, true));
11083            }
11084            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11085        }
11086
11087        wrap_guides
11088    }
11089
11090    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11091        let settings = self.buffer.read(cx).settings_at(0, cx);
11092        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11093        match mode {
11094            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11095                SoftWrap::None
11096            }
11097            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11098            language_settings::SoftWrap::PreferredLineLength => {
11099                SoftWrap::Column(settings.preferred_line_length)
11100            }
11101            language_settings::SoftWrap::Bounded => {
11102                SoftWrap::Bounded(settings.preferred_line_length)
11103            }
11104        }
11105    }
11106
11107    pub fn set_soft_wrap_mode(
11108        &mut self,
11109        mode: language_settings::SoftWrap,
11110        cx: &mut ViewContext<Self>,
11111    ) {
11112        self.soft_wrap_mode_override = Some(mode);
11113        cx.notify();
11114    }
11115
11116    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11117        let rem_size = cx.rem_size();
11118        self.display_map.update(cx, |map, cx| {
11119            map.set_font(
11120                style.text.font(),
11121                style.text.font_size.to_pixels(rem_size),
11122                cx,
11123            )
11124        });
11125        self.style = Some(style);
11126    }
11127
11128    pub fn style(&self) -> Option<&EditorStyle> {
11129        self.style.as_ref()
11130    }
11131
11132    // Called by the element. This method is not designed to be called outside of the editor
11133    // element's layout code because it does not notify when rewrapping is computed synchronously.
11134    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11135        self.display_map
11136            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11137    }
11138
11139    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11140        if self.soft_wrap_mode_override.is_some() {
11141            self.soft_wrap_mode_override.take();
11142        } else {
11143            let soft_wrap = match self.soft_wrap_mode(cx) {
11144                SoftWrap::GitDiff => return,
11145                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11146                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11147                    language_settings::SoftWrap::None
11148                }
11149            };
11150            self.soft_wrap_mode_override = Some(soft_wrap);
11151        }
11152        cx.notify();
11153    }
11154
11155    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11156        let Some(workspace) = self.workspace() else {
11157            return;
11158        };
11159        let fs = workspace.read(cx).app_state().fs.clone();
11160        let current_show = TabBarSettings::get_global(cx).show;
11161        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11162            setting.show = Some(!current_show);
11163        });
11164    }
11165
11166    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11167        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11168            self.buffer
11169                .read(cx)
11170                .settings_at(0, cx)
11171                .indent_guides
11172                .enabled
11173        });
11174        self.show_indent_guides = Some(!currently_enabled);
11175        cx.notify();
11176    }
11177
11178    fn should_show_indent_guides(&self) -> Option<bool> {
11179        self.show_indent_guides
11180    }
11181
11182    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11183        let mut editor_settings = EditorSettings::get_global(cx).clone();
11184        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11185        EditorSettings::override_global(editor_settings, cx);
11186    }
11187
11188    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11189        self.use_relative_line_numbers
11190            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11191    }
11192
11193    pub fn toggle_relative_line_numbers(
11194        &mut self,
11195        _: &ToggleRelativeLineNumbers,
11196        cx: &mut ViewContext<Self>,
11197    ) {
11198        let is_relative = self.should_use_relative_line_numbers(cx);
11199        self.set_relative_line_number(Some(!is_relative), cx)
11200    }
11201
11202    pub fn set_relative_line_number(
11203        &mut self,
11204        is_relative: Option<bool>,
11205        cx: &mut ViewContext<Self>,
11206    ) {
11207        self.use_relative_line_numbers = is_relative;
11208        cx.notify();
11209    }
11210
11211    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11212        self.show_gutter = show_gutter;
11213        cx.notify();
11214    }
11215
11216    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11217        self.show_line_numbers = Some(show_line_numbers);
11218        cx.notify();
11219    }
11220
11221    pub fn set_show_git_diff_gutter(
11222        &mut self,
11223        show_git_diff_gutter: bool,
11224        cx: &mut ViewContext<Self>,
11225    ) {
11226        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11227        cx.notify();
11228    }
11229
11230    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11231        self.show_code_actions = Some(show_code_actions);
11232        cx.notify();
11233    }
11234
11235    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11236        self.show_runnables = Some(show_runnables);
11237        cx.notify();
11238    }
11239
11240    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11241        if self.display_map.read(cx).masked != masked {
11242            self.display_map.update(cx, |map, _| map.masked = masked);
11243        }
11244        cx.notify()
11245    }
11246
11247    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11248        self.show_wrap_guides = Some(show_wrap_guides);
11249        cx.notify();
11250    }
11251
11252    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11253        self.show_indent_guides = Some(show_indent_guides);
11254        cx.notify();
11255    }
11256
11257    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11258        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11259            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11260                if let Some(dir) = file.abs_path(cx).parent() {
11261                    return Some(dir.to_owned());
11262                }
11263            }
11264
11265            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11266                return Some(project_path.path.to_path_buf());
11267            }
11268        }
11269
11270        None
11271    }
11272
11273    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11274        self.active_excerpt(cx)?
11275            .1
11276            .read(cx)
11277            .file()
11278            .and_then(|f| f.as_local())
11279    }
11280
11281    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11282        if let Some(target) = self.target_file(cx) {
11283            cx.reveal_path(&target.abs_path(cx));
11284        }
11285    }
11286
11287    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11288        if let Some(file) = self.target_file(cx) {
11289            if let Some(path) = file.abs_path(cx).to_str() {
11290                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11291            }
11292        }
11293    }
11294
11295    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11296        if let Some(file) = self.target_file(cx) {
11297            if let Some(path) = file.path().to_str() {
11298                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11299            }
11300        }
11301    }
11302
11303    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11304        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11305
11306        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11307            self.start_git_blame(true, cx);
11308        }
11309
11310        cx.notify();
11311    }
11312
11313    pub fn toggle_git_blame_inline(
11314        &mut self,
11315        _: &ToggleGitBlameInline,
11316        cx: &mut ViewContext<Self>,
11317    ) {
11318        self.toggle_git_blame_inline_internal(true, cx);
11319        cx.notify();
11320    }
11321
11322    pub fn git_blame_inline_enabled(&self) -> bool {
11323        self.git_blame_inline_enabled
11324    }
11325
11326    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11327        self.show_selection_menu = self
11328            .show_selection_menu
11329            .map(|show_selections_menu| !show_selections_menu)
11330            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11331
11332        cx.notify();
11333    }
11334
11335    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11336        self.show_selection_menu
11337            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11338    }
11339
11340    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11341        if let Some(project) = self.project.as_ref() {
11342            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11343                return;
11344            };
11345
11346            if buffer.read(cx).file().is_none() {
11347                return;
11348            }
11349
11350            let focused = self.focus_handle(cx).contains_focused(cx);
11351
11352            let project = project.clone();
11353            let blame =
11354                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11355            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11356            self.blame = Some(blame);
11357        }
11358    }
11359
11360    fn toggle_git_blame_inline_internal(
11361        &mut self,
11362        user_triggered: bool,
11363        cx: &mut ViewContext<Self>,
11364    ) {
11365        if self.git_blame_inline_enabled {
11366            self.git_blame_inline_enabled = false;
11367            self.show_git_blame_inline = false;
11368            self.show_git_blame_inline_delay_task.take();
11369        } else {
11370            self.git_blame_inline_enabled = true;
11371            self.start_git_blame_inline(user_triggered, cx);
11372        }
11373
11374        cx.notify();
11375    }
11376
11377    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11378        self.start_git_blame(user_triggered, cx);
11379
11380        if ProjectSettings::get_global(cx)
11381            .git
11382            .inline_blame_delay()
11383            .is_some()
11384        {
11385            self.start_inline_blame_timer(cx);
11386        } else {
11387            self.show_git_blame_inline = true
11388        }
11389    }
11390
11391    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11392        self.blame.as_ref()
11393    }
11394
11395    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11396        self.show_git_blame_gutter && self.has_blame_entries(cx)
11397    }
11398
11399    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11400        self.show_git_blame_inline
11401            && self.focus_handle.is_focused(cx)
11402            && !self.newest_selection_head_on_empty_line(cx)
11403            && self.has_blame_entries(cx)
11404    }
11405
11406    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11407        self.blame()
11408            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11409    }
11410
11411    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11412        let cursor_anchor = self.selections.newest_anchor().head();
11413
11414        let snapshot = self.buffer.read(cx).snapshot(cx);
11415        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11416
11417        snapshot.line_len(buffer_row) == 0
11418    }
11419
11420    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11421        let (path, selection, repo) = maybe!({
11422            let project_handle = self.project.as_ref()?.clone();
11423            let project = project_handle.read(cx);
11424
11425            let selection = self.selections.newest::<Point>(cx);
11426            let selection_range = selection.range();
11427
11428            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11429                (buffer, selection_range.start.row..selection_range.end.row)
11430            } else {
11431                let buffer_ranges = self
11432                    .buffer()
11433                    .read(cx)
11434                    .range_to_buffer_ranges(selection_range, cx);
11435
11436                let (buffer, range, _) = if selection.reversed {
11437                    buffer_ranges.first()
11438                } else {
11439                    buffer_ranges.last()
11440                }?;
11441
11442                let snapshot = buffer.read(cx).snapshot();
11443                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11444                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11445                (buffer.clone(), selection)
11446            };
11447
11448            let path = buffer
11449                .read(cx)
11450                .file()?
11451                .as_local()?
11452                .path()
11453                .to_str()?
11454                .to_string();
11455            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11456            Some((path, selection, repo))
11457        })
11458        .ok_or_else(|| anyhow!("unable to open git repository"))?;
11459
11460        const REMOTE_NAME: &str = "origin";
11461        let origin_url = repo
11462            .remote_url(REMOTE_NAME)
11463            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11464        let sha = repo
11465            .head_sha()
11466            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11467
11468        let (provider, remote) =
11469            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11470                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11471
11472        Ok(provider.build_permalink(
11473            remote,
11474            BuildPermalinkParams {
11475                sha: &sha,
11476                path: &path,
11477                selection: Some(selection),
11478            },
11479        ))
11480    }
11481
11482    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11483        let permalink = self.get_permalink_to_line(cx);
11484
11485        match permalink {
11486            Ok(permalink) => {
11487                cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11488            }
11489            Err(err) => {
11490                let message = format!("Failed to copy permalink: {err}");
11491
11492                Err::<(), anyhow::Error>(err).log_err();
11493
11494                if let Some(workspace) = self.workspace() {
11495                    workspace.update(cx, |workspace, cx| {
11496                        struct CopyPermalinkToLine;
11497
11498                        workspace.show_toast(
11499                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11500                            cx,
11501                        )
11502                    })
11503                }
11504            }
11505        }
11506    }
11507
11508    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11509        if let Some(file) = self.target_file(cx) {
11510            if let Some(path) = file.path().to_str() {
11511                let selection = self.selections.newest::<Point>(cx).start.row + 1;
11512                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11513            }
11514        }
11515    }
11516
11517    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11518        let permalink = self.get_permalink_to_line(cx);
11519
11520        match permalink {
11521            Ok(permalink) => {
11522                cx.open_url(permalink.as_ref());
11523            }
11524            Err(err) => {
11525                let message = format!("Failed to open permalink: {err}");
11526
11527                Err::<(), anyhow::Error>(err).log_err();
11528
11529                if let Some(workspace) = self.workspace() {
11530                    workspace.update(cx, |workspace, cx| {
11531                        struct OpenPermalinkToLine;
11532
11533                        workspace.show_toast(
11534                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11535                            cx,
11536                        )
11537                    })
11538                }
11539            }
11540        }
11541    }
11542
11543    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11544    /// last highlight added will be used.
11545    ///
11546    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11547    pub fn highlight_rows<T: 'static>(
11548        &mut self,
11549        range: Range<Anchor>,
11550        color: Hsla,
11551        should_autoscroll: bool,
11552        cx: &mut ViewContext<Self>,
11553    ) {
11554        let snapshot = self.buffer().read(cx).snapshot(cx);
11555        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11556        let ix = row_highlights.binary_search_by(|highlight| {
11557            Ordering::Equal
11558                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11559                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11560        });
11561
11562        if let Err(mut ix) = ix {
11563            let index = post_inc(&mut self.highlight_order);
11564
11565            // If this range intersects with the preceding highlight, then merge it with
11566            // the preceding highlight. Otherwise insert a new highlight.
11567            let mut merged = false;
11568            if ix > 0 {
11569                let prev_highlight = &mut row_highlights[ix - 1];
11570                if prev_highlight
11571                    .range
11572                    .end
11573                    .cmp(&range.start, &snapshot)
11574                    .is_ge()
11575                {
11576                    ix -= 1;
11577                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11578                        prev_highlight.range.end = range.end;
11579                    }
11580                    merged = true;
11581                    prev_highlight.index = index;
11582                    prev_highlight.color = color;
11583                    prev_highlight.should_autoscroll = should_autoscroll;
11584                }
11585            }
11586
11587            if !merged {
11588                row_highlights.insert(
11589                    ix,
11590                    RowHighlight {
11591                        range: range.clone(),
11592                        index,
11593                        color,
11594                        should_autoscroll,
11595                    },
11596                );
11597            }
11598
11599            // If any of the following highlights intersect with this one, merge them.
11600            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11601                let highlight = &row_highlights[ix];
11602                if next_highlight
11603                    .range
11604                    .start
11605                    .cmp(&highlight.range.end, &snapshot)
11606                    .is_le()
11607                {
11608                    if next_highlight
11609                        .range
11610                        .end
11611                        .cmp(&highlight.range.end, &snapshot)
11612                        .is_gt()
11613                    {
11614                        row_highlights[ix].range.end = next_highlight.range.end;
11615                    }
11616                    row_highlights.remove(ix + 1);
11617                } else {
11618                    break;
11619                }
11620            }
11621        }
11622    }
11623
11624    /// Remove any highlighted row ranges of the given type that intersect the
11625    /// given ranges.
11626    pub fn remove_highlighted_rows<T: 'static>(
11627        &mut self,
11628        ranges_to_remove: Vec<Range<Anchor>>,
11629        cx: &mut ViewContext<Self>,
11630    ) {
11631        let snapshot = self.buffer().read(cx).snapshot(cx);
11632        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11633        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11634        row_highlights.retain(|highlight| {
11635            while let Some(range_to_remove) = ranges_to_remove.peek() {
11636                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11637                    Ordering::Less | Ordering::Equal => {
11638                        ranges_to_remove.next();
11639                    }
11640                    Ordering::Greater => {
11641                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11642                            Ordering::Less | Ordering::Equal => {
11643                                return false;
11644                            }
11645                            Ordering::Greater => break,
11646                        }
11647                    }
11648                }
11649            }
11650
11651            true
11652        })
11653    }
11654
11655    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11656    pub fn clear_row_highlights<T: 'static>(&mut self) {
11657        self.highlighted_rows.remove(&TypeId::of::<T>());
11658    }
11659
11660    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11661    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11662        self.highlighted_rows
11663            .get(&TypeId::of::<T>())
11664            .map_or(&[] as &[_], |vec| vec.as_slice())
11665            .iter()
11666            .map(|highlight| (highlight.range.clone(), highlight.color))
11667    }
11668
11669    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11670    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11671    /// Allows to ignore certain kinds of highlights.
11672    pub fn highlighted_display_rows(
11673        &mut self,
11674        cx: &mut WindowContext,
11675    ) -> BTreeMap<DisplayRow, Hsla> {
11676        let snapshot = self.snapshot(cx);
11677        let mut used_highlight_orders = HashMap::default();
11678        self.highlighted_rows
11679            .iter()
11680            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11681            .fold(
11682                BTreeMap::<DisplayRow, Hsla>::new(),
11683                |mut unique_rows, highlight| {
11684                    let start = highlight.range.start.to_display_point(&snapshot);
11685                    let end = highlight.range.end.to_display_point(&snapshot);
11686                    let start_row = start.row().0;
11687                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11688                        && end.column() == 0
11689                    {
11690                        end.row().0.saturating_sub(1)
11691                    } else {
11692                        end.row().0
11693                    };
11694                    for row in start_row..=end_row {
11695                        let used_index =
11696                            used_highlight_orders.entry(row).or_insert(highlight.index);
11697                        if highlight.index >= *used_index {
11698                            *used_index = highlight.index;
11699                            unique_rows.insert(DisplayRow(row), highlight.color);
11700                        }
11701                    }
11702                    unique_rows
11703                },
11704            )
11705    }
11706
11707    pub fn highlighted_display_row_for_autoscroll(
11708        &self,
11709        snapshot: &DisplaySnapshot,
11710    ) -> Option<DisplayRow> {
11711        self.highlighted_rows
11712            .values()
11713            .flat_map(|highlighted_rows| highlighted_rows.iter())
11714            .filter_map(|highlight| {
11715                if highlight.should_autoscroll {
11716                    Some(highlight.range.start.to_display_point(snapshot).row())
11717                } else {
11718                    None
11719                }
11720            })
11721            .min()
11722    }
11723
11724    pub fn set_search_within_ranges(
11725        &mut self,
11726        ranges: &[Range<Anchor>],
11727        cx: &mut ViewContext<Self>,
11728    ) {
11729        self.highlight_background::<SearchWithinRange>(
11730            ranges,
11731            |colors| colors.editor_document_highlight_read_background,
11732            cx,
11733        )
11734    }
11735
11736    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11737        self.breadcrumb_header = Some(new_header);
11738    }
11739
11740    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11741        self.clear_background_highlights::<SearchWithinRange>(cx);
11742    }
11743
11744    pub fn highlight_background<T: 'static>(
11745        &mut self,
11746        ranges: &[Range<Anchor>],
11747        color_fetcher: fn(&ThemeColors) -> Hsla,
11748        cx: &mut ViewContext<Self>,
11749    ) {
11750        self.background_highlights
11751            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11752        self.scrollbar_marker_state.dirty = true;
11753        cx.notify();
11754    }
11755
11756    pub fn clear_background_highlights<T: 'static>(
11757        &mut self,
11758        cx: &mut ViewContext<Self>,
11759    ) -> Option<BackgroundHighlight> {
11760        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11761        if !text_highlights.1.is_empty() {
11762            self.scrollbar_marker_state.dirty = true;
11763            cx.notify();
11764        }
11765        Some(text_highlights)
11766    }
11767
11768    pub fn highlight_gutter<T: 'static>(
11769        &mut self,
11770        ranges: &[Range<Anchor>],
11771        color_fetcher: fn(&AppContext) -> Hsla,
11772        cx: &mut ViewContext<Self>,
11773    ) {
11774        self.gutter_highlights
11775            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11776        cx.notify();
11777    }
11778
11779    pub fn clear_gutter_highlights<T: 'static>(
11780        &mut self,
11781        cx: &mut ViewContext<Self>,
11782    ) -> Option<GutterHighlight> {
11783        cx.notify();
11784        self.gutter_highlights.remove(&TypeId::of::<T>())
11785    }
11786
11787    #[cfg(feature = "test-support")]
11788    pub fn all_text_background_highlights(
11789        &mut self,
11790        cx: &mut ViewContext<Self>,
11791    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11792        let snapshot = self.snapshot(cx);
11793        let buffer = &snapshot.buffer_snapshot;
11794        let start = buffer.anchor_before(0);
11795        let end = buffer.anchor_after(buffer.len());
11796        let theme = cx.theme().colors();
11797        self.background_highlights_in_range(start..end, &snapshot, theme)
11798    }
11799
11800    #[cfg(feature = "test-support")]
11801    pub fn search_background_highlights(
11802        &mut self,
11803        cx: &mut ViewContext<Self>,
11804    ) -> Vec<Range<Point>> {
11805        let snapshot = self.buffer().read(cx).snapshot(cx);
11806
11807        let highlights = self
11808            .background_highlights
11809            .get(&TypeId::of::<items::BufferSearchHighlights>());
11810
11811        if let Some((_color, ranges)) = highlights {
11812            ranges
11813                .iter()
11814                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11815                .collect_vec()
11816        } else {
11817            vec![]
11818        }
11819    }
11820
11821    fn document_highlights_for_position<'a>(
11822        &'a self,
11823        position: Anchor,
11824        buffer: &'a MultiBufferSnapshot,
11825    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11826        let read_highlights = self
11827            .background_highlights
11828            .get(&TypeId::of::<DocumentHighlightRead>())
11829            .map(|h| &h.1);
11830        let write_highlights = self
11831            .background_highlights
11832            .get(&TypeId::of::<DocumentHighlightWrite>())
11833            .map(|h| &h.1);
11834        let left_position = position.bias_left(buffer);
11835        let right_position = position.bias_right(buffer);
11836        read_highlights
11837            .into_iter()
11838            .chain(write_highlights)
11839            .flat_map(move |ranges| {
11840                let start_ix = match ranges.binary_search_by(|probe| {
11841                    let cmp = probe.end.cmp(&left_position, buffer);
11842                    if cmp.is_ge() {
11843                        Ordering::Greater
11844                    } else {
11845                        Ordering::Less
11846                    }
11847                }) {
11848                    Ok(i) | Err(i) => i,
11849                };
11850
11851                ranges[start_ix..]
11852                    .iter()
11853                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11854            })
11855    }
11856
11857    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11858        self.background_highlights
11859            .get(&TypeId::of::<T>())
11860            .map_or(false, |(_, highlights)| !highlights.is_empty())
11861    }
11862
11863    pub fn background_highlights_in_range(
11864        &self,
11865        search_range: Range<Anchor>,
11866        display_snapshot: &DisplaySnapshot,
11867        theme: &ThemeColors,
11868    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11869        let mut results = Vec::new();
11870        for (color_fetcher, ranges) in self.background_highlights.values() {
11871            let color = color_fetcher(theme);
11872            let start_ix = match ranges.binary_search_by(|probe| {
11873                let cmp = probe
11874                    .end
11875                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11876                if cmp.is_gt() {
11877                    Ordering::Greater
11878                } else {
11879                    Ordering::Less
11880                }
11881            }) {
11882                Ok(i) | Err(i) => i,
11883            };
11884            for range in &ranges[start_ix..] {
11885                if range
11886                    .start
11887                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11888                    .is_ge()
11889                {
11890                    break;
11891                }
11892
11893                let start = range.start.to_display_point(display_snapshot);
11894                let end = range.end.to_display_point(display_snapshot);
11895                results.push((start..end, color))
11896            }
11897        }
11898        results
11899    }
11900
11901    pub fn background_highlight_row_ranges<T: 'static>(
11902        &self,
11903        search_range: Range<Anchor>,
11904        display_snapshot: &DisplaySnapshot,
11905        count: usize,
11906    ) -> Vec<RangeInclusive<DisplayPoint>> {
11907        let mut results = Vec::new();
11908        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11909            return vec![];
11910        };
11911
11912        let start_ix = match ranges.binary_search_by(|probe| {
11913            let cmp = probe
11914                .end
11915                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11916            if cmp.is_gt() {
11917                Ordering::Greater
11918            } else {
11919                Ordering::Less
11920            }
11921        }) {
11922            Ok(i) | Err(i) => i,
11923        };
11924        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11925            if let (Some(start_display), Some(end_display)) = (start, end) {
11926                results.push(
11927                    start_display.to_display_point(display_snapshot)
11928                        ..=end_display.to_display_point(display_snapshot),
11929                );
11930            }
11931        };
11932        let mut start_row: Option<Point> = None;
11933        let mut end_row: Option<Point> = None;
11934        if ranges.len() > count {
11935            return Vec::new();
11936        }
11937        for range in &ranges[start_ix..] {
11938            if range
11939                .start
11940                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11941                .is_ge()
11942            {
11943                break;
11944            }
11945            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11946            if let Some(current_row) = &end_row {
11947                if end.row == current_row.row {
11948                    continue;
11949                }
11950            }
11951            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11952            if start_row.is_none() {
11953                assert_eq!(end_row, None);
11954                start_row = Some(start);
11955                end_row = Some(end);
11956                continue;
11957            }
11958            if let Some(current_end) = end_row.as_mut() {
11959                if start.row > current_end.row + 1 {
11960                    push_region(start_row, end_row);
11961                    start_row = Some(start);
11962                    end_row = Some(end);
11963                } else {
11964                    // Merge two hunks.
11965                    *current_end = end;
11966                }
11967            } else {
11968                unreachable!();
11969            }
11970        }
11971        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11972        push_region(start_row, end_row);
11973        results
11974    }
11975
11976    pub fn gutter_highlights_in_range(
11977        &self,
11978        search_range: Range<Anchor>,
11979        display_snapshot: &DisplaySnapshot,
11980        cx: &AppContext,
11981    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11982        let mut results = Vec::new();
11983        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11984            let color = color_fetcher(cx);
11985            let start_ix = match ranges.binary_search_by(|probe| {
11986                let cmp = probe
11987                    .end
11988                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11989                if cmp.is_gt() {
11990                    Ordering::Greater
11991                } else {
11992                    Ordering::Less
11993                }
11994            }) {
11995                Ok(i) | Err(i) => i,
11996            };
11997            for range in &ranges[start_ix..] {
11998                if range
11999                    .start
12000                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12001                    .is_ge()
12002                {
12003                    break;
12004                }
12005
12006                let start = range.start.to_display_point(display_snapshot);
12007                let end = range.end.to_display_point(display_snapshot);
12008                results.push((start..end, color))
12009            }
12010        }
12011        results
12012    }
12013
12014    /// Get the text ranges corresponding to the redaction query
12015    pub fn redacted_ranges(
12016        &self,
12017        search_range: Range<Anchor>,
12018        display_snapshot: &DisplaySnapshot,
12019        cx: &WindowContext,
12020    ) -> Vec<Range<DisplayPoint>> {
12021        display_snapshot
12022            .buffer_snapshot
12023            .redacted_ranges(search_range, |file| {
12024                if let Some(file) = file {
12025                    file.is_private()
12026                        && EditorSettings::get(
12027                            Some(SettingsLocation {
12028                                worktree_id: file.worktree_id(cx),
12029                                path: file.path().as_ref(),
12030                            }),
12031                            cx,
12032                        )
12033                        .redact_private_values
12034                } else {
12035                    false
12036                }
12037            })
12038            .map(|range| {
12039                range.start.to_display_point(display_snapshot)
12040                    ..range.end.to_display_point(display_snapshot)
12041            })
12042            .collect()
12043    }
12044
12045    pub fn highlight_text<T: 'static>(
12046        &mut self,
12047        ranges: Vec<Range<Anchor>>,
12048        style: HighlightStyle,
12049        cx: &mut ViewContext<Self>,
12050    ) {
12051        self.display_map.update(cx, |map, _| {
12052            map.highlight_text(TypeId::of::<T>(), ranges, style)
12053        });
12054        cx.notify();
12055    }
12056
12057    pub(crate) fn highlight_inlays<T: 'static>(
12058        &mut self,
12059        highlights: Vec<InlayHighlight>,
12060        style: HighlightStyle,
12061        cx: &mut ViewContext<Self>,
12062    ) {
12063        self.display_map.update(cx, |map, _| {
12064            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12065        });
12066        cx.notify();
12067    }
12068
12069    pub fn text_highlights<'a, T: 'static>(
12070        &'a self,
12071        cx: &'a AppContext,
12072    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12073        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12074    }
12075
12076    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12077        let cleared = self
12078            .display_map
12079            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12080        if cleared {
12081            cx.notify();
12082        }
12083    }
12084
12085    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12086        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12087            && self.focus_handle.is_focused(cx)
12088    }
12089
12090    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12091        self.show_cursor_when_unfocused = is_enabled;
12092        cx.notify();
12093    }
12094
12095    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12096        cx.notify();
12097    }
12098
12099    fn on_buffer_event(
12100        &mut self,
12101        multibuffer: Model<MultiBuffer>,
12102        event: &multi_buffer::Event,
12103        cx: &mut ViewContext<Self>,
12104    ) {
12105        match event {
12106            multi_buffer::Event::Edited {
12107                singleton_buffer_edited,
12108            } => {
12109                self.scrollbar_marker_state.dirty = true;
12110                self.active_indent_guides_state.dirty = true;
12111                self.refresh_active_diagnostics(cx);
12112                self.refresh_code_actions(cx);
12113                if self.has_active_inline_completion(cx) {
12114                    self.update_visible_inline_completion(cx);
12115                }
12116                cx.emit(EditorEvent::BufferEdited);
12117                cx.emit(SearchEvent::MatchesInvalidated);
12118                if *singleton_buffer_edited {
12119                    if let Some(project) = &self.project {
12120                        let project = project.read(cx);
12121                        #[allow(clippy::mutable_key_type)]
12122                        let languages_affected = multibuffer
12123                            .read(cx)
12124                            .all_buffers()
12125                            .into_iter()
12126                            .filter_map(|buffer| {
12127                                let buffer = buffer.read(cx);
12128                                let language = buffer.language()?;
12129                                if project.is_local()
12130                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12131                                {
12132                                    None
12133                                } else {
12134                                    Some(language)
12135                                }
12136                            })
12137                            .cloned()
12138                            .collect::<HashSet<_>>();
12139                        if !languages_affected.is_empty() {
12140                            self.refresh_inlay_hints(
12141                                InlayHintRefreshReason::BufferEdited(languages_affected),
12142                                cx,
12143                            );
12144                        }
12145                    }
12146                }
12147
12148                let Some(project) = &self.project else { return };
12149                let (telemetry, is_via_ssh) = {
12150                    let project = project.read(cx);
12151                    let telemetry = project.client().telemetry().clone();
12152                    let is_via_ssh = project.is_via_ssh();
12153                    (telemetry, is_via_ssh)
12154                };
12155                refresh_linked_ranges(self, cx);
12156                telemetry.log_edit_event("editor", is_via_ssh);
12157            }
12158            multi_buffer::Event::ExcerptsAdded {
12159                buffer,
12160                predecessor,
12161                excerpts,
12162            } => {
12163                self.tasks_update_task = Some(self.refresh_runnables(cx));
12164                cx.emit(EditorEvent::ExcerptsAdded {
12165                    buffer: buffer.clone(),
12166                    predecessor: *predecessor,
12167                    excerpts: excerpts.clone(),
12168                });
12169                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12170            }
12171            multi_buffer::Event::ExcerptsRemoved { ids } => {
12172                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12173                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12174            }
12175            multi_buffer::Event::ExcerptsEdited { ids } => {
12176                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12177            }
12178            multi_buffer::Event::ExcerptsExpanded { ids } => {
12179                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12180            }
12181            multi_buffer::Event::Reparsed(buffer_id) => {
12182                self.tasks_update_task = Some(self.refresh_runnables(cx));
12183
12184                cx.emit(EditorEvent::Reparsed(*buffer_id));
12185            }
12186            multi_buffer::Event::LanguageChanged(buffer_id) => {
12187                linked_editing_ranges::refresh_linked_ranges(self, cx);
12188                cx.emit(EditorEvent::Reparsed(*buffer_id));
12189                cx.notify();
12190            }
12191            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12192            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12193            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12194                cx.emit(EditorEvent::TitleChanged)
12195            }
12196            multi_buffer::Event::DiffBaseChanged => {
12197                self.scrollbar_marker_state.dirty = true;
12198                cx.emit(EditorEvent::DiffBaseChanged);
12199                cx.notify();
12200            }
12201            multi_buffer::Event::DiffUpdated { buffer } => {
12202                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12203                cx.notify();
12204            }
12205            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12206            multi_buffer::Event::DiagnosticsUpdated => {
12207                self.refresh_active_diagnostics(cx);
12208                self.scrollbar_marker_state.dirty = true;
12209                cx.notify();
12210            }
12211            _ => {}
12212        };
12213    }
12214
12215    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12216        cx.notify();
12217    }
12218
12219    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12220        self.tasks_update_task = Some(self.refresh_runnables(cx));
12221        self.refresh_inline_completion(true, false, cx);
12222        self.refresh_inlay_hints(
12223            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12224                self.selections.newest_anchor().head(),
12225                &self.buffer.read(cx).snapshot(cx),
12226                cx,
12227            )),
12228            cx,
12229        );
12230
12231        let old_cursor_shape = self.cursor_shape;
12232
12233        {
12234            let editor_settings = EditorSettings::get_global(cx);
12235            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12236            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12237            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12238        }
12239
12240        if old_cursor_shape != self.cursor_shape {
12241            cx.emit(EditorEvent::CursorShapeChanged);
12242        }
12243
12244        let project_settings = ProjectSettings::get_global(cx);
12245        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12246
12247        if self.mode == EditorMode::Full {
12248            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12249            if self.git_blame_inline_enabled != inline_blame_enabled {
12250                self.toggle_git_blame_inline_internal(false, cx);
12251            }
12252        }
12253
12254        cx.notify();
12255    }
12256
12257    pub fn set_searchable(&mut self, searchable: bool) {
12258        self.searchable = searchable;
12259    }
12260
12261    pub fn searchable(&self) -> bool {
12262        self.searchable
12263    }
12264
12265    fn open_proposed_changes_editor(
12266        &mut self,
12267        _: &OpenProposedChangesEditor,
12268        cx: &mut ViewContext<Self>,
12269    ) {
12270        let Some(workspace) = self.workspace() else {
12271            cx.propagate();
12272            return;
12273        };
12274
12275        let buffer = self.buffer.read(cx);
12276        let mut new_selections_by_buffer = HashMap::default();
12277        for selection in self.selections.all::<usize>(cx) {
12278            for (buffer, range, _) in
12279                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12280            {
12281                let mut range = range.to_point(buffer.read(cx));
12282                range.start.column = 0;
12283                range.end.column = buffer.read(cx).line_len(range.end.row);
12284                new_selections_by_buffer
12285                    .entry(buffer)
12286                    .or_insert(Vec::new())
12287                    .push(range)
12288            }
12289        }
12290
12291        let proposed_changes_buffers = new_selections_by_buffer
12292            .into_iter()
12293            .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12294            .collect::<Vec<_>>();
12295        let proposed_changes_editor = cx.new_view(|cx| {
12296            ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12297        });
12298
12299        cx.window_context().defer(move |cx| {
12300            workspace.update(cx, |workspace, cx| {
12301                workspace.active_pane().update(cx, |pane, cx| {
12302                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12303                });
12304            });
12305        });
12306    }
12307
12308    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12309        self.open_excerpts_common(true, cx)
12310    }
12311
12312    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12313        self.open_excerpts_common(false, cx)
12314    }
12315
12316    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12317        let buffer = self.buffer.read(cx);
12318        if buffer.is_singleton() {
12319            cx.propagate();
12320            return;
12321        }
12322
12323        let Some(workspace) = self.workspace() else {
12324            cx.propagate();
12325            return;
12326        };
12327
12328        let mut new_selections_by_buffer = HashMap::default();
12329        for selection in self.selections.all::<usize>(cx) {
12330            for (buffer, mut range, _) in
12331                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12332            {
12333                if selection.reversed {
12334                    mem::swap(&mut range.start, &mut range.end);
12335                }
12336                new_selections_by_buffer
12337                    .entry(buffer)
12338                    .or_insert(Vec::new())
12339                    .push(range)
12340            }
12341        }
12342
12343        // We defer the pane interaction because we ourselves are a workspace item
12344        // and activating a new item causes the pane to call a method on us reentrantly,
12345        // which panics if we're on the stack.
12346        cx.window_context().defer(move |cx| {
12347            workspace.update(cx, |workspace, cx| {
12348                let pane = if split {
12349                    workspace.adjacent_pane(cx)
12350                } else {
12351                    workspace.active_pane().clone()
12352                };
12353
12354                for (buffer, ranges) in new_selections_by_buffer {
12355                    let editor =
12356                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12357                    editor.update(cx, |editor, cx| {
12358                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12359                            s.select_ranges(ranges);
12360                        });
12361                    });
12362                }
12363            })
12364        });
12365    }
12366
12367    fn jump(
12368        &mut self,
12369        path: ProjectPath,
12370        position: Point,
12371        anchor: language::Anchor,
12372        offset_from_top: u32,
12373        cx: &mut ViewContext<Self>,
12374    ) {
12375        let workspace = self.workspace();
12376        cx.spawn(|_, mut cx| async move {
12377            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12378            let editor = workspace.update(&mut cx, |workspace, cx| {
12379                // Reset the preview item id before opening the new item
12380                workspace.active_pane().update(cx, |pane, cx| {
12381                    pane.set_preview_item_id(None, cx);
12382                });
12383                workspace.open_path_preview(path, None, true, true, cx)
12384            })?;
12385            let editor = editor
12386                .await?
12387                .downcast::<Editor>()
12388                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12389                .downgrade();
12390            editor.update(&mut cx, |editor, cx| {
12391                let buffer = editor
12392                    .buffer()
12393                    .read(cx)
12394                    .as_singleton()
12395                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12396                let buffer = buffer.read(cx);
12397                let cursor = if buffer.can_resolve(&anchor) {
12398                    language::ToPoint::to_point(&anchor, buffer)
12399                } else {
12400                    buffer.clip_point(position, Bias::Left)
12401                };
12402
12403                let nav_history = editor.nav_history.take();
12404                editor.change_selections(
12405                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12406                    cx,
12407                    |s| {
12408                        s.select_ranges([cursor..cursor]);
12409                    },
12410                );
12411                editor.nav_history = nav_history;
12412
12413                anyhow::Ok(())
12414            })??;
12415
12416            anyhow::Ok(())
12417        })
12418        .detach_and_log_err(cx);
12419    }
12420
12421    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12422        let snapshot = self.buffer.read(cx).read(cx);
12423        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12424        Some(
12425            ranges
12426                .iter()
12427                .map(move |range| {
12428                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12429                })
12430                .collect(),
12431        )
12432    }
12433
12434    fn selection_replacement_ranges(
12435        &self,
12436        range: Range<OffsetUtf16>,
12437        cx: &AppContext,
12438    ) -> Vec<Range<OffsetUtf16>> {
12439        let selections = self.selections.all::<OffsetUtf16>(cx);
12440        let newest_selection = selections
12441            .iter()
12442            .max_by_key(|selection| selection.id)
12443            .unwrap();
12444        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12445        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12446        let snapshot = self.buffer.read(cx).read(cx);
12447        selections
12448            .into_iter()
12449            .map(|mut selection| {
12450                selection.start.0 =
12451                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12452                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12453                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12454                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12455            })
12456            .collect()
12457    }
12458
12459    fn report_editor_event(
12460        &self,
12461        operation: &'static str,
12462        file_extension: Option<String>,
12463        cx: &AppContext,
12464    ) {
12465        if cfg!(any(test, feature = "test-support")) {
12466            return;
12467        }
12468
12469        let Some(project) = &self.project else { return };
12470
12471        // If None, we are in a file without an extension
12472        let file = self
12473            .buffer
12474            .read(cx)
12475            .as_singleton()
12476            .and_then(|b| b.read(cx).file());
12477        let file_extension = file_extension.or(file
12478            .as_ref()
12479            .and_then(|file| Path::new(file.file_name(cx)).extension())
12480            .and_then(|e| e.to_str())
12481            .map(|a| a.to_string()));
12482
12483        let vim_mode = cx
12484            .global::<SettingsStore>()
12485            .raw_user_settings()
12486            .get("vim_mode")
12487            == Some(&serde_json::Value::Bool(true));
12488
12489        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12490            == language::language_settings::InlineCompletionProvider::Copilot;
12491        let copilot_enabled_for_language = self
12492            .buffer
12493            .read(cx)
12494            .settings_at(0, cx)
12495            .show_inline_completions;
12496
12497        let project = project.read(cx);
12498        let telemetry = project.client().telemetry().clone();
12499        telemetry.report_editor_event(
12500            file_extension,
12501            vim_mode,
12502            operation,
12503            copilot_enabled,
12504            copilot_enabled_for_language,
12505            project.is_via_ssh(),
12506        )
12507    }
12508
12509    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12510    /// with each line being an array of {text, highlight} objects.
12511    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12512        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12513            return;
12514        };
12515
12516        #[derive(Serialize)]
12517        struct Chunk<'a> {
12518            text: String,
12519            highlight: Option<&'a str>,
12520        }
12521
12522        let snapshot = buffer.read(cx).snapshot();
12523        let range = self
12524            .selected_text_range(false, cx)
12525            .and_then(|selection| {
12526                if selection.range.is_empty() {
12527                    None
12528                } else {
12529                    Some(selection.range)
12530                }
12531            })
12532            .unwrap_or_else(|| 0..snapshot.len());
12533
12534        let chunks = snapshot.chunks(range, true);
12535        let mut lines = Vec::new();
12536        let mut line: VecDeque<Chunk> = VecDeque::new();
12537
12538        let Some(style) = self.style.as_ref() else {
12539            return;
12540        };
12541
12542        for chunk in chunks {
12543            let highlight = chunk
12544                .syntax_highlight_id
12545                .and_then(|id| id.name(&style.syntax));
12546            let mut chunk_lines = chunk.text.split('\n').peekable();
12547            while let Some(text) = chunk_lines.next() {
12548                let mut merged_with_last_token = false;
12549                if let Some(last_token) = line.back_mut() {
12550                    if last_token.highlight == highlight {
12551                        last_token.text.push_str(text);
12552                        merged_with_last_token = true;
12553                    }
12554                }
12555
12556                if !merged_with_last_token {
12557                    line.push_back(Chunk {
12558                        text: text.into(),
12559                        highlight,
12560                    });
12561                }
12562
12563                if chunk_lines.peek().is_some() {
12564                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12565                        line.pop_front();
12566                    }
12567                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12568                        line.pop_back();
12569                    }
12570
12571                    lines.push(mem::take(&mut line));
12572                }
12573            }
12574        }
12575
12576        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12577            return;
12578        };
12579        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12580    }
12581
12582    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12583        &self.inlay_hint_cache
12584    }
12585
12586    pub fn replay_insert_event(
12587        &mut self,
12588        text: &str,
12589        relative_utf16_range: Option<Range<isize>>,
12590        cx: &mut ViewContext<Self>,
12591    ) {
12592        if !self.input_enabled {
12593            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12594            return;
12595        }
12596        if let Some(relative_utf16_range) = relative_utf16_range {
12597            let selections = self.selections.all::<OffsetUtf16>(cx);
12598            self.change_selections(None, cx, |s| {
12599                let new_ranges = selections.into_iter().map(|range| {
12600                    let start = OffsetUtf16(
12601                        range
12602                            .head()
12603                            .0
12604                            .saturating_add_signed(relative_utf16_range.start),
12605                    );
12606                    let end = OffsetUtf16(
12607                        range
12608                            .head()
12609                            .0
12610                            .saturating_add_signed(relative_utf16_range.end),
12611                    );
12612                    start..end
12613                });
12614                s.select_ranges(new_ranges);
12615            });
12616        }
12617
12618        self.handle_input(text, cx);
12619    }
12620
12621    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12622        let Some(project) = self.project.as_ref() else {
12623            return false;
12624        };
12625        let project = project.read(cx);
12626
12627        let mut supports = false;
12628        self.buffer().read(cx).for_each_buffer(|buffer| {
12629            if !supports {
12630                supports = project
12631                    .language_servers_for_buffer(buffer.read(cx), cx)
12632                    .any(
12633                        |(_, server)| match server.capabilities().inlay_hint_provider {
12634                            Some(lsp::OneOf::Left(enabled)) => enabled,
12635                            Some(lsp::OneOf::Right(_)) => true,
12636                            None => false,
12637                        },
12638                    )
12639            }
12640        });
12641        supports
12642    }
12643
12644    pub fn focus(&self, cx: &mut WindowContext) {
12645        cx.focus(&self.focus_handle)
12646    }
12647
12648    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12649        self.focus_handle.is_focused(cx)
12650    }
12651
12652    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12653        cx.emit(EditorEvent::Focused);
12654
12655        if let Some(descendant) = self
12656            .last_focused_descendant
12657            .take()
12658            .and_then(|descendant| descendant.upgrade())
12659        {
12660            cx.focus(&descendant);
12661        } else {
12662            if let Some(blame) = self.blame.as_ref() {
12663                blame.update(cx, GitBlame::focus)
12664            }
12665
12666            self.blink_manager.update(cx, BlinkManager::enable);
12667            self.show_cursor_names(cx);
12668            self.buffer.update(cx, |buffer, cx| {
12669                buffer.finalize_last_transaction(cx);
12670                if self.leader_peer_id.is_none() {
12671                    buffer.set_active_selections(
12672                        &self.selections.disjoint_anchors(),
12673                        self.selections.line_mode,
12674                        self.cursor_shape,
12675                        cx,
12676                    );
12677                }
12678            });
12679        }
12680    }
12681
12682    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12683        cx.emit(EditorEvent::FocusedIn)
12684    }
12685
12686    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12687        if event.blurred != self.focus_handle {
12688            self.last_focused_descendant = Some(event.blurred);
12689        }
12690    }
12691
12692    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12693        self.blink_manager.update(cx, BlinkManager::disable);
12694        self.buffer
12695            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12696
12697        if let Some(blame) = self.blame.as_ref() {
12698            blame.update(cx, GitBlame::blur)
12699        }
12700        if !self.hover_state.focused(cx) {
12701            hide_hover(self, cx);
12702        }
12703
12704        self.hide_context_menu(cx);
12705        cx.emit(EditorEvent::Blurred);
12706        cx.notify();
12707    }
12708
12709    pub fn register_action<A: Action>(
12710        &mut self,
12711        listener: impl Fn(&A, &mut WindowContext) + 'static,
12712    ) -> Subscription {
12713        let id = self.next_editor_action_id.post_inc();
12714        let listener = Arc::new(listener);
12715        self.editor_actions.borrow_mut().insert(
12716            id,
12717            Box::new(move |cx| {
12718                let cx = cx.window_context();
12719                let listener = listener.clone();
12720                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12721                    let action = action.downcast_ref().unwrap();
12722                    if phase == DispatchPhase::Bubble {
12723                        listener(action, cx)
12724                    }
12725                })
12726            }),
12727        );
12728
12729        let editor_actions = self.editor_actions.clone();
12730        Subscription::new(move || {
12731            editor_actions.borrow_mut().remove(&id);
12732        })
12733    }
12734
12735    pub fn file_header_size(&self) -> u32 {
12736        self.file_header_size
12737    }
12738
12739    pub fn revert(
12740        &mut self,
12741        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12742        cx: &mut ViewContext<Self>,
12743    ) {
12744        self.buffer().update(cx, |multi_buffer, cx| {
12745            for (buffer_id, changes) in revert_changes {
12746                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12747                    buffer.update(cx, |buffer, cx| {
12748                        buffer.edit(
12749                            changes.into_iter().map(|(range, text)| {
12750                                (range, text.to_string().map(Arc::<str>::from))
12751                            }),
12752                            None,
12753                            cx,
12754                        );
12755                    });
12756                }
12757            }
12758        });
12759        self.change_selections(None, cx, |selections| selections.refresh());
12760    }
12761
12762    pub fn to_pixel_point(
12763        &mut self,
12764        source: multi_buffer::Anchor,
12765        editor_snapshot: &EditorSnapshot,
12766        cx: &mut ViewContext<Self>,
12767    ) -> Option<gpui::Point<Pixels>> {
12768        let source_point = source.to_display_point(editor_snapshot);
12769        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12770    }
12771
12772    pub fn display_to_pixel_point(
12773        &mut self,
12774        source: DisplayPoint,
12775        editor_snapshot: &EditorSnapshot,
12776        cx: &mut ViewContext<Self>,
12777    ) -> Option<gpui::Point<Pixels>> {
12778        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12779        let text_layout_details = self.text_layout_details(cx);
12780        let scroll_top = text_layout_details
12781            .scroll_anchor
12782            .scroll_position(editor_snapshot)
12783            .y;
12784
12785        if source.row().as_f32() < scroll_top.floor() {
12786            return None;
12787        }
12788        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12789        let source_y = line_height * (source.row().as_f32() - scroll_top);
12790        Some(gpui::Point::new(source_x, source_y))
12791    }
12792
12793    pub fn has_active_completions_menu(&self) -> bool {
12794        self.context_menu.read().as_ref().map_or(false, |menu| {
12795            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12796        })
12797    }
12798
12799    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12800        self.addons
12801            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12802    }
12803
12804    pub fn unregister_addon<T: Addon>(&mut self) {
12805        self.addons.remove(&std::any::TypeId::of::<T>());
12806    }
12807
12808    pub fn addon<T: Addon>(&self) -> Option<&T> {
12809        let type_id = std::any::TypeId::of::<T>();
12810        self.addons
12811            .get(&type_id)
12812            .and_then(|item| item.to_any().downcast_ref::<T>())
12813    }
12814}
12815
12816fn hunks_for_selections(
12817    multi_buffer_snapshot: &MultiBufferSnapshot,
12818    selections: &[Selection<Anchor>],
12819) -> Vec<MultiBufferDiffHunk> {
12820    let buffer_rows_for_selections = selections.iter().map(|selection| {
12821        let head = selection.head();
12822        let tail = selection.tail();
12823        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12824        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12825        if start > end {
12826            end..start
12827        } else {
12828            start..end
12829        }
12830    });
12831
12832    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12833}
12834
12835pub fn hunks_for_rows(
12836    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12837    multi_buffer_snapshot: &MultiBufferSnapshot,
12838) -> Vec<MultiBufferDiffHunk> {
12839    let mut hunks = Vec::new();
12840    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12841        HashMap::default();
12842    for selected_multi_buffer_rows in rows {
12843        let query_rows =
12844            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12845        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12846            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12847            // when the caret is just above or just below the deleted hunk.
12848            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12849            let related_to_selection = if allow_adjacent {
12850                hunk.row_range.overlaps(&query_rows)
12851                    || hunk.row_range.start == query_rows.end
12852                    || hunk.row_range.end == query_rows.start
12853            } else {
12854                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12855                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12856                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12857                    || selected_multi_buffer_rows.end == hunk.row_range.start
12858            };
12859            if related_to_selection {
12860                if !processed_buffer_rows
12861                    .entry(hunk.buffer_id)
12862                    .or_default()
12863                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12864                {
12865                    continue;
12866                }
12867                hunks.push(hunk);
12868            }
12869        }
12870    }
12871
12872    hunks
12873}
12874
12875pub trait CollaborationHub {
12876    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12877    fn user_participant_indices<'a>(
12878        &self,
12879        cx: &'a AppContext,
12880    ) -> &'a HashMap<u64, ParticipantIndex>;
12881    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12882}
12883
12884impl CollaborationHub for Model<Project> {
12885    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12886        self.read(cx).collaborators()
12887    }
12888
12889    fn user_participant_indices<'a>(
12890        &self,
12891        cx: &'a AppContext,
12892    ) -> &'a HashMap<u64, ParticipantIndex> {
12893        self.read(cx).user_store().read(cx).participant_indices()
12894    }
12895
12896    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12897        let this = self.read(cx);
12898        let user_ids = this.collaborators().values().map(|c| c.user_id);
12899        this.user_store().read_with(cx, |user_store, cx| {
12900            user_store.participant_names(user_ids, cx)
12901        })
12902    }
12903}
12904
12905pub trait CompletionProvider {
12906    fn completions(
12907        &self,
12908        buffer: &Model<Buffer>,
12909        buffer_position: text::Anchor,
12910        trigger: CompletionContext,
12911        cx: &mut ViewContext<Editor>,
12912    ) -> Task<Result<Vec<Completion>>>;
12913
12914    fn resolve_completions(
12915        &self,
12916        buffer: Model<Buffer>,
12917        completion_indices: Vec<usize>,
12918        completions: Arc<RwLock<Box<[Completion]>>>,
12919        cx: &mut ViewContext<Editor>,
12920    ) -> Task<Result<bool>>;
12921
12922    fn apply_additional_edits_for_completion(
12923        &self,
12924        buffer: Model<Buffer>,
12925        completion: Completion,
12926        push_to_history: bool,
12927        cx: &mut ViewContext<Editor>,
12928    ) -> Task<Result<Option<language::Transaction>>>;
12929
12930    fn is_completion_trigger(
12931        &self,
12932        buffer: &Model<Buffer>,
12933        position: language::Anchor,
12934        text: &str,
12935        trigger_in_words: bool,
12936        cx: &mut ViewContext<Editor>,
12937    ) -> bool;
12938
12939    fn sort_completions(&self) -> bool {
12940        true
12941    }
12942}
12943
12944pub trait CodeActionProvider {
12945    fn code_actions(
12946        &self,
12947        buffer: &Model<Buffer>,
12948        range: Range<text::Anchor>,
12949        cx: &mut WindowContext,
12950    ) -> Task<Result<Vec<CodeAction>>>;
12951
12952    fn apply_code_action(
12953        &self,
12954        buffer_handle: Model<Buffer>,
12955        action: CodeAction,
12956        excerpt_id: ExcerptId,
12957        push_to_history: bool,
12958        cx: &mut WindowContext,
12959    ) -> Task<Result<ProjectTransaction>>;
12960}
12961
12962impl CodeActionProvider for Model<Project> {
12963    fn code_actions(
12964        &self,
12965        buffer: &Model<Buffer>,
12966        range: Range<text::Anchor>,
12967        cx: &mut WindowContext,
12968    ) -> Task<Result<Vec<CodeAction>>> {
12969        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12970    }
12971
12972    fn apply_code_action(
12973        &self,
12974        buffer_handle: Model<Buffer>,
12975        action: CodeAction,
12976        _excerpt_id: ExcerptId,
12977        push_to_history: bool,
12978        cx: &mut WindowContext,
12979    ) -> Task<Result<ProjectTransaction>> {
12980        self.update(cx, |project, cx| {
12981            project.apply_code_action(buffer_handle, action, push_to_history, cx)
12982        })
12983    }
12984}
12985
12986fn snippet_completions(
12987    project: &Project,
12988    buffer: &Model<Buffer>,
12989    buffer_position: text::Anchor,
12990    cx: &mut AppContext,
12991) -> Vec<Completion> {
12992    let language = buffer.read(cx).language_at(buffer_position);
12993    let language_name = language.as_ref().map(|language| language.lsp_id());
12994    let snippet_store = project.snippets().read(cx);
12995    let snippets = snippet_store.snippets_for(language_name, cx);
12996
12997    if snippets.is_empty() {
12998        return vec![];
12999    }
13000    let snapshot = buffer.read(cx).text_snapshot();
13001    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
13002
13003    let mut lines = chunks.lines();
13004    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
13005        return vec![];
13006    };
13007
13008    let scope = language.map(|language| language.default_scope());
13009    let classifier = CharClassifier::new(scope).for_completion(true);
13010    let mut last_word = line_at
13011        .chars()
13012        .rev()
13013        .take_while(|c| classifier.is_word(*c))
13014        .collect::<String>();
13015    last_word = last_word.chars().rev().collect();
13016    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13017    let to_lsp = |point: &text::Anchor| {
13018        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13019        point_to_lsp(end)
13020    };
13021    let lsp_end = to_lsp(&buffer_position);
13022    snippets
13023        .into_iter()
13024        .filter_map(|snippet| {
13025            let matching_prefix = snippet
13026                .prefix
13027                .iter()
13028                .find(|prefix| prefix.starts_with(&last_word))?;
13029            let start = as_offset - last_word.len();
13030            let start = snapshot.anchor_before(start);
13031            let range = start..buffer_position;
13032            let lsp_start = to_lsp(&start);
13033            let lsp_range = lsp::Range {
13034                start: lsp_start,
13035                end: lsp_end,
13036            };
13037            Some(Completion {
13038                old_range: range,
13039                new_text: snippet.body.clone(),
13040                label: CodeLabel {
13041                    text: matching_prefix.clone(),
13042                    runs: vec![],
13043                    filter_range: 0..matching_prefix.len(),
13044                },
13045                server_id: LanguageServerId(usize::MAX),
13046                documentation: snippet.description.clone().map(Documentation::SingleLine),
13047                lsp_completion: lsp::CompletionItem {
13048                    label: snippet.prefix.first().unwrap().clone(),
13049                    kind: Some(CompletionItemKind::SNIPPET),
13050                    label_details: snippet.description.as_ref().map(|description| {
13051                        lsp::CompletionItemLabelDetails {
13052                            detail: Some(description.clone()),
13053                            description: None,
13054                        }
13055                    }),
13056                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13057                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13058                        lsp::InsertReplaceEdit {
13059                            new_text: snippet.body.clone(),
13060                            insert: lsp_range,
13061                            replace: lsp_range,
13062                        },
13063                    )),
13064                    filter_text: Some(snippet.body.clone()),
13065                    sort_text: Some(char::MAX.to_string()),
13066                    ..Default::default()
13067                },
13068                confirm: None,
13069            })
13070        })
13071        .collect()
13072}
13073
13074impl CompletionProvider for Model<Project> {
13075    fn completions(
13076        &self,
13077        buffer: &Model<Buffer>,
13078        buffer_position: text::Anchor,
13079        options: CompletionContext,
13080        cx: &mut ViewContext<Editor>,
13081    ) -> Task<Result<Vec<Completion>>> {
13082        self.update(cx, |project, cx| {
13083            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13084            let project_completions = project.completions(buffer, buffer_position, options, cx);
13085            cx.background_executor().spawn(async move {
13086                let mut completions = project_completions.await?;
13087                //let snippets = snippets.into_iter().;
13088                completions.extend(snippets);
13089                Ok(completions)
13090            })
13091        })
13092    }
13093
13094    fn resolve_completions(
13095        &self,
13096        buffer: Model<Buffer>,
13097        completion_indices: Vec<usize>,
13098        completions: Arc<RwLock<Box<[Completion]>>>,
13099        cx: &mut ViewContext<Editor>,
13100    ) -> Task<Result<bool>> {
13101        self.update(cx, |project, cx| {
13102            project.resolve_completions(buffer, completion_indices, completions, cx)
13103        })
13104    }
13105
13106    fn apply_additional_edits_for_completion(
13107        &self,
13108        buffer: Model<Buffer>,
13109        completion: Completion,
13110        push_to_history: bool,
13111        cx: &mut ViewContext<Editor>,
13112    ) -> Task<Result<Option<language::Transaction>>> {
13113        self.update(cx, |project, cx| {
13114            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13115        })
13116    }
13117
13118    fn is_completion_trigger(
13119        &self,
13120        buffer: &Model<Buffer>,
13121        position: language::Anchor,
13122        text: &str,
13123        trigger_in_words: bool,
13124        cx: &mut ViewContext<Editor>,
13125    ) -> bool {
13126        if !EditorSettings::get_global(cx).show_completions_on_input {
13127            return false;
13128        }
13129
13130        let mut chars = text.chars();
13131        let char = if let Some(char) = chars.next() {
13132            char
13133        } else {
13134            return false;
13135        };
13136        if chars.next().is_some() {
13137            return false;
13138        }
13139
13140        let buffer = buffer.read(cx);
13141        let classifier = buffer
13142            .snapshot()
13143            .char_classifier_at(position)
13144            .for_completion(true);
13145        if trigger_in_words && classifier.is_word(char) {
13146            return true;
13147        }
13148
13149        buffer
13150            .completion_triggers()
13151            .iter()
13152            .any(|string| string == text)
13153    }
13154}
13155
13156fn inlay_hint_settings(
13157    location: Anchor,
13158    snapshot: &MultiBufferSnapshot,
13159    cx: &mut ViewContext<'_, Editor>,
13160) -> InlayHintSettings {
13161    let file = snapshot.file_at(location);
13162    let language = snapshot.language_at(location);
13163    let settings = all_language_settings(file, cx);
13164    settings
13165        .language(language.map(|l| l.name()).as_ref())
13166        .inlay_hints
13167}
13168
13169fn consume_contiguous_rows(
13170    contiguous_row_selections: &mut Vec<Selection<Point>>,
13171    selection: &Selection<Point>,
13172    display_map: &DisplaySnapshot,
13173    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13174) -> (MultiBufferRow, MultiBufferRow) {
13175    contiguous_row_selections.push(selection.clone());
13176    let start_row = MultiBufferRow(selection.start.row);
13177    let mut end_row = ending_row(selection, display_map);
13178
13179    while let Some(next_selection) = selections.peek() {
13180        if next_selection.start.row <= end_row.0 {
13181            end_row = ending_row(next_selection, display_map);
13182            contiguous_row_selections.push(selections.next().unwrap().clone());
13183        } else {
13184            break;
13185        }
13186    }
13187    (start_row, end_row)
13188}
13189
13190fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13191    if next_selection.end.column > 0 || next_selection.is_empty() {
13192        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13193    } else {
13194        MultiBufferRow(next_selection.end.row)
13195    }
13196}
13197
13198impl EditorSnapshot {
13199    pub fn remote_selections_in_range<'a>(
13200        &'a self,
13201        range: &'a Range<Anchor>,
13202        collaboration_hub: &dyn CollaborationHub,
13203        cx: &'a AppContext,
13204    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13205        let participant_names = collaboration_hub.user_names(cx);
13206        let participant_indices = collaboration_hub.user_participant_indices(cx);
13207        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13208        let collaborators_by_replica_id = collaborators_by_peer_id
13209            .iter()
13210            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13211            .collect::<HashMap<_, _>>();
13212        self.buffer_snapshot
13213            .selections_in_range(range, false)
13214            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13215                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13216                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13217                let user_name = participant_names.get(&collaborator.user_id).cloned();
13218                Some(RemoteSelection {
13219                    replica_id,
13220                    selection,
13221                    cursor_shape,
13222                    line_mode,
13223                    participant_index,
13224                    peer_id: collaborator.peer_id,
13225                    user_name,
13226                })
13227            })
13228    }
13229
13230    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13231        self.display_snapshot.buffer_snapshot.language_at(position)
13232    }
13233
13234    pub fn is_focused(&self) -> bool {
13235        self.is_focused
13236    }
13237
13238    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13239        self.placeholder_text.as_ref()
13240    }
13241
13242    pub fn scroll_position(&self) -> gpui::Point<f32> {
13243        self.scroll_anchor.scroll_position(&self.display_snapshot)
13244    }
13245
13246    fn gutter_dimensions(
13247        &self,
13248        font_id: FontId,
13249        font_size: Pixels,
13250        em_width: Pixels,
13251        em_advance: Pixels,
13252        max_line_number_width: Pixels,
13253        cx: &AppContext,
13254    ) -> GutterDimensions {
13255        if !self.show_gutter {
13256            return GutterDimensions::default();
13257        }
13258        let descent = cx.text_system().descent(font_id, font_size);
13259
13260        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13261            matches!(
13262                ProjectSettings::get_global(cx).git.git_gutter,
13263                Some(GitGutterSetting::TrackedFiles)
13264            )
13265        });
13266        let gutter_settings = EditorSettings::get_global(cx).gutter;
13267        let show_line_numbers = self
13268            .show_line_numbers
13269            .unwrap_or(gutter_settings.line_numbers);
13270        let line_gutter_width = if show_line_numbers {
13271            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13272            let min_width_for_number_on_gutter = em_advance * 4.0;
13273            max_line_number_width.max(min_width_for_number_on_gutter)
13274        } else {
13275            0.0.into()
13276        };
13277
13278        let show_code_actions = self
13279            .show_code_actions
13280            .unwrap_or(gutter_settings.code_actions);
13281
13282        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13283
13284        let git_blame_entries_width =
13285            self.git_blame_gutter_max_author_length
13286                .map(|max_author_length| {
13287                    // Length of the author name, but also space for the commit hash,
13288                    // the spacing and the timestamp.
13289                    let max_char_count = max_author_length
13290                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13291                        + 7 // length of commit sha
13292                        + 14 // length of max relative timestamp ("60 minutes ago")
13293                        + 4; // gaps and margins
13294
13295                    em_advance * max_char_count
13296                });
13297
13298        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13299        left_padding += if show_code_actions || show_runnables {
13300            em_width * 3.0
13301        } else if show_git_gutter && show_line_numbers {
13302            em_width * 2.0
13303        } else if show_git_gutter || show_line_numbers {
13304            em_width
13305        } else {
13306            px(0.)
13307        };
13308
13309        let right_padding = if gutter_settings.folds && show_line_numbers {
13310            em_width * 4.0
13311        } else if gutter_settings.folds {
13312            em_width * 3.0
13313        } else if show_line_numbers {
13314            em_width
13315        } else {
13316            px(0.)
13317        };
13318
13319        GutterDimensions {
13320            left_padding,
13321            right_padding,
13322            width: line_gutter_width + left_padding + right_padding,
13323            margin: -descent,
13324            git_blame_entries_width,
13325        }
13326    }
13327
13328    pub fn render_fold_toggle(
13329        &self,
13330        buffer_row: MultiBufferRow,
13331        row_contains_cursor: bool,
13332        editor: View<Editor>,
13333        cx: &mut WindowContext,
13334    ) -> Option<AnyElement> {
13335        let folded = self.is_line_folded(buffer_row);
13336
13337        if let Some(crease) = self
13338            .crease_snapshot
13339            .query_row(buffer_row, &self.buffer_snapshot)
13340        {
13341            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13342                if folded {
13343                    editor.update(cx, |editor, cx| {
13344                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13345                    });
13346                } else {
13347                    editor.update(cx, |editor, cx| {
13348                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13349                    });
13350                }
13351            });
13352
13353            Some((crease.render_toggle)(
13354                buffer_row,
13355                folded,
13356                toggle_callback,
13357                cx,
13358            ))
13359        } else if folded
13360            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13361        {
13362            Some(
13363                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13364                    .selected(folded)
13365                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13366                        if folded {
13367                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13368                        } else {
13369                            this.fold_at(&FoldAt { buffer_row }, cx);
13370                        }
13371                    }))
13372                    .into_any_element(),
13373            )
13374        } else {
13375            None
13376        }
13377    }
13378
13379    pub fn render_crease_trailer(
13380        &self,
13381        buffer_row: MultiBufferRow,
13382        cx: &mut WindowContext,
13383    ) -> Option<AnyElement> {
13384        let folded = self.is_line_folded(buffer_row);
13385        let crease = self
13386            .crease_snapshot
13387            .query_row(buffer_row, &self.buffer_snapshot)?;
13388        Some((crease.render_trailer)(buffer_row, folded, cx))
13389    }
13390}
13391
13392impl Deref for EditorSnapshot {
13393    type Target = DisplaySnapshot;
13394
13395    fn deref(&self) -> &Self::Target {
13396        &self.display_snapshot
13397    }
13398}
13399
13400#[derive(Clone, Debug, PartialEq, Eq)]
13401pub enum EditorEvent {
13402    InputIgnored {
13403        text: Arc<str>,
13404    },
13405    InputHandled {
13406        utf16_range_to_replace: Option<Range<isize>>,
13407        text: Arc<str>,
13408    },
13409    ExcerptsAdded {
13410        buffer: Model<Buffer>,
13411        predecessor: ExcerptId,
13412        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13413    },
13414    ExcerptsRemoved {
13415        ids: Vec<ExcerptId>,
13416    },
13417    ExcerptsEdited {
13418        ids: Vec<ExcerptId>,
13419    },
13420    ExcerptsExpanded {
13421        ids: Vec<ExcerptId>,
13422    },
13423    BufferEdited,
13424    Edited {
13425        transaction_id: clock::Lamport,
13426    },
13427    Reparsed(BufferId),
13428    Focused,
13429    FocusedIn,
13430    Blurred,
13431    DirtyChanged,
13432    Saved,
13433    TitleChanged,
13434    DiffBaseChanged,
13435    SelectionsChanged {
13436        local: bool,
13437    },
13438    ScrollPositionChanged {
13439        local: bool,
13440        autoscroll: bool,
13441    },
13442    Closed,
13443    TransactionUndone {
13444        transaction_id: clock::Lamport,
13445    },
13446    TransactionBegun {
13447        transaction_id: clock::Lamport,
13448    },
13449    CursorShapeChanged,
13450}
13451
13452impl EventEmitter<EditorEvent> for Editor {}
13453
13454impl FocusableView for Editor {
13455    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13456        self.focus_handle.clone()
13457    }
13458}
13459
13460impl Render for Editor {
13461    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13462        let settings = ThemeSettings::get_global(cx);
13463
13464        let text_style = match self.mode {
13465            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13466                color: cx.theme().colors().editor_foreground,
13467                font_family: settings.ui_font.family.clone(),
13468                font_features: settings.ui_font.features.clone(),
13469                font_fallbacks: settings.ui_font.fallbacks.clone(),
13470                font_size: rems(0.875).into(),
13471                font_weight: settings.ui_font.weight,
13472                line_height: relative(settings.buffer_line_height.value()),
13473                ..Default::default()
13474            },
13475            EditorMode::Full => TextStyle {
13476                color: cx.theme().colors().editor_foreground,
13477                font_family: settings.buffer_font.family.clone(),
13478                font_features: settings.buffer_font.features.clone(),
13479                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13480                font_size: settings.buffer_font_size(cx).into(),
13481                font_weight: settings.buffer_font.weight,
13482                line_height: relative(settings.buffer_line_height.value()),
13483                ..Default::default()
13484            },
13485        };
13486
13487        let background = match self.mode {
13488            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13489            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13490            EditorMode::Full => cx.theme().colors().editor_background,
13491        };
13492
13493        EditorElement::new(
13494            cx.view(),
13495            EditorStyle {
13496                background,
13497                local_player: cx.theme().players().local(),
13498                text: text_style,
13499                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13500                syntax: cx.theme().syntax().clone(),
13501                status: cx.theme().status().clone(),
13502                inlay_hints_style: make_inlay_hints_style(cx),
13503                suggestions_style: HighlightStyle {
13504                    color: Some(cx.theme().status().predictive),
13505                    ..HighlightStyle::default()
13506                },
13507                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13508            },
13509        )
13510    }
13511}
13512
13513impl ViewInputHandler for Editor {
13514    fn text_for_range(
13515        &mut self,
13516        range_utf16: Range<usize>,
13517        cx: &mut ViewContext<Self>,
13518    ) -> Option<String> {
13519        Some(
13520            self.buffer
13521                .read(cx)
13522                .read(cx)
13523                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13524                .collect(),
13525        )
13526    }
13527
13528    fn selected_text_range(
13529        &mut self,
13530        ignore_disabled_input: bool,
13531        cx: &mut ViewContext<Self>,
13532    ) -> Option<UTF16Selection> {
13533        // Prevent the IME menu from appearing when holding down an alphabetic key
13534        // while input is disabled.
13535        if !ignore_disabled_input && !self.input_enabled {
13536            return None;
13537        }
13538
13539        let selection = self.selections.newest::<OffsetUtf16>(cx);
13540        let range = selection.range();
13541
13542        Some(UTF16Selection {
13543            range: range.start.0..range.end.0,
13544            reversed: selection.reversed,
13545        })
13546    }
13547
13548    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13549        let snapshot = self.buffer.read(cx).read(cx);
13550        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13551        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13552    }
13553
13554    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13555        self.clear_highlights::<InputComposition>(cx);
13556        self.ime_transaction.take();
13557    }
13558
13559    fn replace_text_in_range(
13560        &mut self,
13561        range_utf16: Option<Range<usize>>,
13562        text: &str,
13563        cx: &mut ViewContext<Self>,
13564    ) {
13565        if !self.input_enabled {
13566            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13567            return;
13568        }
13569
13570        self.transact(cx, |this, cx| {
13571            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13572                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13573                Some(this.selection_replacement_ranges(range_utf16, cx))
13574            } else {
13575                this.marked_text_ranges(cx)
13576            };
13577
13578            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13579                let newest_selection_id = this.selections.newest_anchor().id;
13580                this.selections
13581                    .all::<OffsetUtf16>(cx)
13582                    .iter()
13583                    .zip(ranges_to_replace.iter())
13584                    .find_map(|(selection, range)| {
13585                        if selection.id == newest_selection_id {
13586                            Some(
13587                                (range.start.0 as isize - selection.head().0 as isize)
13588                                    ..(range.end.0 as isize - selection.head().0 as isize),
13589                            )
13590                        } else {
13591                            None
13592                        }
13593                    })
13594            });
13595
13596            cx.emit(EditorEvent::InputHandled {
13597                utf16_range_to_replace: range_to_replace,
13598                text: text.into(),
13599            });
13600
13601            if let Some(new_selected_ranges) = new_selected_ranges {
13602                this.change_selections(None, cx, |selections| {
13603                    selections.select_ranges(new_selected_ranges)
13604                });
13605                this.backspace(&Default::default(), cx);
13606            }
13607
13608            this.handle_input(text, cx);
13609        });
13610
13611        if let Some(transaction) = self.ime_transaction {
13612            self.buffer.update(cx, |buffer, cx| {
13613                buffer.group_until_transaction(transaction, cx);
13614            });
13615        }
13616
13617        self.unmark_text(cx);
13618    }
13619
13620    fn replace_and_mark_text_in_range(
13621        &mut self,
13622        range_utf16: Option<Range<usize>>,
13623        text: &str,
13624        new_selected_range_utf16: Option<Range<usize>>,
13625        cx: &mut ViewContext<Self>,
13626    ) {
13627        if !self.input_enabled {
13628            return;
13629        }
13630
13631        let transaction = self.transact(cx, |this, cx| {
13632            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13633                let snapshot = this.buffer.read(cx).read(cx);
13634                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13635                    for marked_range in &mut marked_ranges {
13636                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13637                        marked_range.start.0 += relative_range_utf16.start;
13638                        marked_range.start =
13639                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13640                        marked_range.end =
13641                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13642                    }
13643                }
13644                Some(marked_ranges)
13645            } else if let Some(range_utf16) = range_utf16 {
13646                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13647                Some(this.selection_replacement_ranges(range_utf16, cx))
13648            } else {
13649                None
13650            };
13651
13652            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13653                let newest_selection_id = this.selections.newest_anchor().id;
13654                this.selections
13655                    .all::<OffsetUtf16>(cx)
13656                    .iter()
13657                    .zip(ranges_to_replace.iter())
13658                    .find_map(|(selection, range)| {
13659                        if selection.id == newest_selection_id {
13660                            Some(
13661                                (range.start.0 as isize - selection.head().0 as isize)
13662                                    ..(range.end.0 as isize - selection.head().0 as isize),
13663                            )
13664                        } else {
13665                            None
13666                        }
13667                    })
13668            });
13669
13670            cx.emit(EditorEvent::InputHandled {
13671                utf16_range_to_replace: range_to_replace,
13672                text: text.into(),
13673            });
13674
13675            if let Some(ranges) = ranges_to_replace {
13676                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13677            }
13678
13679            let marked_ranges = {
13680                let snapshot = this.buffer.read(cx).read(cx);
13681                this.selections
13682                    .disjoint_anchors()
13683                    .iter()
13684                    .map(|selection| {
13685                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13686                    })
13687                    .collect::<Vec<_>>()
13688            };
13689
13690            if text.is_empty() {
13691                this.unmark_text(cx);
13692            } else {
13693                this.highlight_text::<InputComposition>(
13694                    marked_ranges.clone(),
13695                    HighlightStyle {
13696                        underline: Some(UnderlineStyle {
13697                            thickness: px(1.),
13698                            color: None,
13699                            wavy: false,
13700                        }),
13701                        ..Default::default()
13702                    },
13703                    cx,
13704                );
13705            }
13706
13707            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13708            let use_autoclose = this.use_autoclose;
13709            let use_auto_surround = this.use_auto_surround;
13710            this.set_use_autoclose(false);
13711            this.set_use_auto_surround(false);
13712            this.handle_input(text, cx);
13713            this.set_use_autoclose(use_autoclose);
13714            this.set_use_auto_surround(use_auto_surround);
13715
13716            if let Some(new_selected_range) = new_selected_range_utf16 {
13717                let snapshot = this.buffer.read(cx).read(cx);
13718                let new_selected_ranges = marked_ranges
13719                    .into_iter()
13720                    .map(|marked_range| {
13721                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13722                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13723                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13724                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13725                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13726                    })
13727                    .collect::<Vec<_>>();
13728
13729                drop(snapshot);
13730                this.change_selections(None, cx, |selections| {
13731                    selections.select_ranges(new_selected_ranges)
13732                });
13733            }
13734        });
13735
13736        self.ime_transaction = self.ime_transaction.or(transaction);
13737        if let Some(transaction) = self.ime_transaction {
13738            self.buffer.update(cx, |buffer, cx| {
13739                buffer.group_until_transaction(transaction, cx);
13740            });
13741        }
13742
13743        if self.text_highlights::<InputComposition>(cx).is_none() {
13744            self.ime_transaction.take();
13745        }
13746    }
13747
13748    fn bounds_for_range(
13749        &mut self,
13750        range_utf16: Range<usize>,
13751        element_bounds: gpui::Bounds<Pixels>,
13752        cx: &mut ViewContext<Self>,
13753    ) -> Option<gpui::Bounds<Pixels>> {
13754        let text_layout_details = self.text_layout_details(cx);
13755        let style = &text_layout_details.editor_style;
13756        let font_id = cx.text_system().resolve_font(&style.text.font());
13757        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13758        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13759
13760        let em_width = cx
13761            .text_system()
13762            .typographic_bounds(font_id, font_size, 'm')
13763            .unwrap()
13764            .size
13765            .width;
13766
13767        let snapshot = self.snapshot(cx);
13768        let scroll_position = snapshot.scroll_position();
13769        let scroll_left = scroll_position.x * em_width;
13770
13771        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13772        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13773            + self.gutter_dimensions.width;
13774        let y = line_height * (start.row().as_f32() - scroll_position.y);
13775
13776        Some(Bounds {
13777            origin: element_bounds.origin + point(x, y),
13778            size: size(em_width, line_height),
13779        })
13780    }
13781}
13782
13783trait SelectionExt {
13784    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13785    fn spanned_rows(
13786        &self,
13787        include_end_if_at_line_start: bool,
13788        map: &DisplaySnapshot,
13789    ) -> Range<MultiBufferRow>;
13790}
13791
13792impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13793    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13794        let start = self
13795            .start
13796            .to_point(&map.buffer_snapshot)
13797            .to_display_point(map);
13798        let end = self
13799            .end
13800            .to_point(&map.buffer_snapshot)
13801            .to_display_point(map);
13802        if self.reversed {
13803            end..start
13804        } else {
13805            start..end
13806        }
13807    }
13808
13809    fn spanned_rows(
13810        &self,
13811        include_end_if_at_line_start: bool,
13812        map: &DisplaySnapshot,
13813    ) -> Range<MultiBufferRow> {
13814        let start = self.start.to_point(&map.buffer_snapshot);
13815        let mut end = self.end.to_point(&map.buffer_snapshot);
13816        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13817            end.row -= 1;
13818        }
13819
13820        let buffer_start = map.prev_line_boundary(start).0;
13821        let buffer_end = map.next_line_boundary(end).0;
13822        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13823    }
13824}
13825
13826impl<T: InvalidationRegion> InvalidationStack<T> {
13827    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13828    where
13829        S: Clone + ToOffset,
13830    {
13831        while let Some(region) = self.last() {
13832            let all_selections_inside_invalidation_ranges =
13833                if selections.len() == region.ranges().len() {
13834                    selections
13835                        .iter()
13836                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13837                        .all(|(selection, invalidation_range)| {
13838                            let head = selection.head().to_offset(buffer);
13839                            invalidation_range.start <= head && invalidation_range.end >= head
13840                        })
13841                } else {
13842                    false
13843                };
13844
13845            if all_selections_inside_invalidation_ranges {
13846                break;
13847            } else {
13848                self.pop();
13849            }
13850        }
13851    }
13852}
13853
13854impl<T> Default for InvalidationStack<T> {
13855    fn default() -> Self {
13856        Self(Default::default())
13857    }
13858}
13859
13860impl<T> Deref for InvalidationStack<T> {
13861    type Target = Vec<T>;
13862
13863    fn deref(&self) -> &Self::Target {
13864        &self.0
13865    }
13866}
13867
13868impl<T> DerefMut for InvalidationStack<T> {
13869    fn deref_mut(&mut self) -> &mut Self::Target {
13870        &mut self.0
13871    }
13872}
13873
13874impl InvalidationRegion for SnippetState {
13875    fn ranges(&self) -> &[Range<Anchor>] {
13876        &self.ranges[self.active_index]
13877    }
13878}
13879
13880pub fn diagnostic_block_renderer(
13881    diagnostic: Diagnostic,
13882    max_message_rows: Option<u8>,
13883    allow_closing: bool,
13884    _is_valid: bool,
13885) -> RenderBlock {
13886    let (text_without_backticks, code_ranges) =
13887        highlight_diagnostic_message(&diagnostic, max_message_rows);
13888
13889    Box::new(move |cx: &mut BlockContext| {
13890        let group_id: SharedString = cx.block_id.to_string().into();
13891
13892        let mut text_style = cx.text_style().clone();
13893        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13894        let theme_settings = ThemeSettings::get_global(cx);
13895        text_style.font_family = theme_settings.buffer_font.family.clone();
13896        text_style.font_style = theme_settings.buffer_font.style;
13897        text_style.font_features = theme_settings.buffer_font.features.clone();
13898        text_style.font_weight = theme_settings.buffer_font.weight;
13899
13900        let multi_line_diagnostic = diagnostic.message.contains('\n');
13901
13902        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13903            if multi_line_diagnostic {
13904                v_flex()
13905            } else {
13906                h_flex()
13907            }
13908            .when(allow_closing, |div| {
13909                div.children(diagnostic.is_primary.then(|| {
13910                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13911                        .icon_color(Color::Muted)
13912                        .size(ButtonSize::Compact)
13913                        .style(ButtonStyle::Transparent)
13914                        .visible_on_hover(group_id.clone())
13915                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13916                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13917                }))
13918            })
13919            .child(
13920                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13921                    .icon_color(Color::Muted)
13922                    .size(ButtonSize::Compact)
13923                    .style(ButtonStyle::Transparent)
13924                    .visible_on_hover(group_id.clone())
13925                    .on_click({
13926                        let message = diagnostic.message.clone();
13927                        move |_click, cx| {
13928                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13929                        }
13930                    })
13931                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13932            )
13933        };
13934
13935        let icon_size = buttons(&diagnostic, cx.block_id)
13936            .into_any_element()
13937            .layout_as_root(AvailableSpace::min_size(), cx);
13938
13939        h_flex()
13940            .id(cx.block_id)
13941            .group(group_id.clone())
13942            .relative()
13943            .size_full()
13944            .pl(cx.gutter_dimensions.width)
13945            .w(cx.max_width + cx.gutter_dimensions.width)
13946            .child(
13947                div()
13948                    .flex()
13949                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13950                    .flex_shrink(),
13951            )
13952            .child(buttons(&diagnostic, cx.block_id))
13953            .child(div().flex().flex_shrink_0().child(
13954                StyledText::new(text_without_backticks.clone()).with_highlights(
13955                    &text_style,
13956                    code_ranges.iter().map(|range| {
13957                        (
13958                            range.clone(),
13959                            HighlightStyle {
13960                                font_weight: Some(FontWeight::BOLD),
13961                                ..Default::default()
13962                            },
13963                        )
13964                    }),
13965                ),
13966            ))
13967            .into_any_element()
13968    })
13969}
13970
13971pub fn highlight_diagnostic_message(
13972    diagnostic: &Diagnostic,
13973    mut max_message_rows: Option<u8>,
13974) -> (SharedString, Vec<Range<usize>>) {
13975    let mut text_without_backticks = String::new();
13976    let mut code_ranges = Vec::new();
13977
13978    if let Some(source) = &diagnostic.source {
13979        text_without_backticks.push_str(source);
13980        code_ranges.push(0..source.len());
13981        text_without_backticks.push_str(": ");
13982    }
13983
13984    let mut prev_offset = 0;
13985    let mut in_code_block = false;
13986    let has_row_limit = max_message_rows.is_some();
13987    let mut newline_indices = diagnostic
13988        .message
13989        .match_indices('\n')
13990        .filter(|_| has_row_limit)
13991        .map(|(ix, _)| ix)
13992        .fuse()
13993        .peekable();
13994
13995    for (quote_ix, _) in diagnostic
13996        .message
13997        .match_indices('`')
13998        .chain([(diagnostic.message.len(), "")])
13999    {
14000        let mut first_newline_ix = None;
14001        let mut last_newline_ix = None;
14002        while let Some(newline_ix) = newline_indices.peek() {
14003            if *newline_ix < quote_ix {
14004                if first_newline_ix.is_none() {
14005                    first_newline_ix = Some(*newline_ix);
14006                }
14007                last_newline_ix = Some(*newline_ix);
14008
14009                if let Some(rows_left) = &mut max_message_rows {
14010                    if *rows_left == 0 {
14011                        break;
14012                    } else {
14013                        *rows_left -= 1;
14014                    }
14015                }
14016                let _ = newline_indices.next();
14017            } else {
14018                break;
14019            }
14020        }
14021        let prev_len = text_without_backticks.len();
14022        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14023        text_without_backticks.push_str(new_text);
14024        if in_code_block {
14025            code_ranges.push(prev_len..text_without_backticks.len());
14026        }
14027        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14028        in_code_block = !in_code_block;
14029        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14030            text_without_backticks.push_str("...");
14031            break;
14032        }
14033    }
14034
14035    (text_without_backticks.into(), code_ranges)
14036}
14037
14038fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14039    match severity {
14040        DiagnosticSeverity::ERROR => colors.error,
14041        DiagnosticSeverity::WARNING => colors.warning,
14042        DiagnosticSeverity::INFORMATION => colors.info,
14043        DiagnosticSeverity::HINT => colors.info,
14044        _ => colors.ignored,
14045    }
14046}
14047
14048pub fn styled_runs_for_code_label<'a>(
14049    label: &'a CodeLabel,
14050    syntax_theme: &'a theme::SyntaxTheme,
14051) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14052    let fade_out = HighlightStyle {
14053        fade_out: Some(0.35),
14054        ..Default::default()
14055    };
14056
14057    let mut prev_end = label.filter_range.end;
14058    label
14059        .runs
14060        .iter()
14061        .enumerate()
14062        .flat_map(move |(ix, (range, highlight_id))| {
14063            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14064                style
14065            } else {
14066                return Default::default();
14067            };
14068            let mut muted_style = style;
14069            muted_style.highlight(fade_out);
14070
14071            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14072            if range.start >= label.filter_range.end {
14073                if range.start > prev_end {
14074                    runs.push((prev_end..range.start, fade_out));
14075                }
14076                runs.push((range.clone(), muted_style));
14077            } else if range.end <= label.filter_range.end {
14078                runs.push((range.clone(), style));
14079            } else {
14080                runs.push((range.start..label.filter_range.end, style));
14081                runs.push((label.filter_range.end..range.end, muted_style));
14082            }
14083            prev_end = cmp::max(prev_end, range.end);
14084
14085            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14086                runs.push((prev_end..label.text.len(), fade_out));
14087            }
14088
14089            runs
14090        })
14091}
14092
14093pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14094    let mut prev_index = 0;
14095    let mut prev_codepoint: Option<char> = None;
14096    text.char_indices()
14097        .chain([(text.len(), '\0')])
14098        .filter_map(move |(index, codepoint)| {
14099            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14100            let is_boundary = index == text.len()
14101                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14102                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14103            if is_boundary {
14104                let chunk = &text[prev_index..index];
14105                prev_index = index;
14106                Some(chunk)
14107            } else {
14108                None
14109            }
14110        })
14111}
14112
14113pub trait RangeToAnchorExt: Sized {
14114    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14115
14116    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14117        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14118        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14119    }
14120}
14121
14122impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14123    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14124        let start_offset = self.start.to_offset(snapshot);
14125        let end_offset = self.end.to_offset(snapshot);
14126        if start_offset == end_offset {
14127            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14128        } else {
14129            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14130        }
14131    }
14132}
14133
14134pub trait RowExt {
14135    fn as_f32(&self) -> f32;
14136
14137    fn next_row(&self) -> Self;
14138
14139    fn previous_row(&self) -> Self;
14140
14141    fn minus(&self, other: Self) -> u32;
14142}
14143
14144impl RowExt for DisplayRow {
14145    fn as_f32(&self) -> f32 {
14146        self.0 as f32
14147    }
14148
14149    fn next_row(&self) -> Self {
14150        Self(self.0 + 1)
14151    }
14152
14153    fn previous_row(&self) -> Self {
14154        Self(self.0.saturating_sub(1))
14155    }
14156
14157    fn minus(&self, other: Self) -> u32 {
14158        self.0 - other.0
14159    }
14160}
14161
14162impl RowExt for MultiBufferRow {
14163    fn as_f32(&self) -> f32 {
14164        self.0 as f32
14165    }
14166
14167    fn next_row(&self) -> Self {
14168        Self(self.0 + 1)
14169    }
14170
14171    fn previous_row(&self) -> Self {
14172        Self(self.0.saturating_sub(1))
14173    }
14174
14175    fn minus(&self, other: Self) -> u32 {
14176        self.0 - other.0
14177    }
14178}
14179
14180trait RowRangeExt {
14181    type Row;
14182
14183    fn len(&self) -> usize;
14184
14185    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14186}
14187
14188impl RowRangeExt for Range<MultiBufferRow> {
14189    type Row = MultiBufferRow;
14190
14191    fn len(&self) -> usize {
14192        (self.end.0 - self.start.0) as usize
14193    }
14194
14195    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14196        (self.start.0..self.end.0).map(MultiBufferRow)
14197    }
14198}
14199
14200impl RowRangeExt for Range<DisplayRow> {
14201    type Row = DisplayRow;
14202
14203    fn len(&self) -> usize {
14204        (self.end.0 - self.start.0) as usize
14205    }
14206
14207    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14208        (self.start.0..self.end.0).map(DisplayRow)
14209    }
14210}
14211
14212fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14213    if hunk.diff_base_byte_range.is_empty() {
14214        DiffHunkStatus::Added
14215    } else if hunk.row_range.is_empty() {
14216        DiffHunkStatus::Removed
14217    } else {
14218        DiffHunkStatus::Modified
14219    }
14220}
14221
14222/// If select range has more than one line, we
14223/// just point the cursor to range.start.
14224fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14225    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14226        range
14227    } else {
14228        range.start..range.start
14229    }
14230}