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                        div().min_w(px(220.)).max_w(px(540.)).child(
 1232                            ListItem::new(mat.candidate_id)
 1233                                .inset(true)
 1234                                .selected(item_ix == selected_item)
 1235                                .on_click(cx.listener(move |editor, _event, cx| {
 1236                                    cx.stop_propagation();
 1237                                    if let Some(task) = editor.confirm_completion(
 1238                                        &ConfirmCompletion {
 1239                                            item_ix: Some(item_ix),
 1240                                        },
 1241                                        cx,
 1242                                    ) {
 1243                                        task.detach_and_log_err(cx)
 1244                                    }
 1245                                }))
 1246                                .child(h_flex().overflow_hidden().child(completion_label))
 1247                                .end_slot::<Label>(documentation_label),
 1248                        )
 1249                    })
 1250                    .collect()
 1251            },
 1252        )
 1253        .occlude()
 1254        .max_h(max_height)
 1255        .track_scroll(self.scroll_handle.clone())
 1256        .with_width_from_item(widest_completion_ix)
 1257        .with_sizing_behavior(ListSizingBehavior::Infer);
 1258
 1259        Popover::new()
 1260            .child(list)
 1261            .when_some(multiline_docs, |popover, multiline_docs| {
 1262                popover.aside(multiline_docs)
 1263            })
 1264            .into_any_element()
 1265    }
 1266
 1267    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1268        let mut matches = if let Some(query) = query {
 1269            fuzzy::match_strings(
 1270                &self.match_candidates,
 1271                query,
 1272                query.chars().any(|c| c.is_uppercase()),
 1273                100,
 1274                &Default::default(),
 1275                executor,
 1276            )
 1277            .await
 1278        } else {
 1279            self.match_candidates
 1280                .iter()
 1281                .enumerate()
 1282                .map(|(candidate_id, candidate)| StringMatch {
 1283                    candidate_id,
 1284                    score: Default::default(),
 1285                    positions: Default::default(),
 1286                    string: candidate.string.clone(),
 1287                })
 1288                .collect()
 1289        };
 1290
 1291        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1292        if let Some(query) = query {
 1293            if let Some(query_start) = query.chars().next() {
 1294                matches.retain(|string_match| {
 1295                    split_words(&string_match.string).any(|word| {
 1296                        // Check that the first codepoint of the word as lowercase matches the first
 1297                        // codepoint of the query as lowercase
 1298                        word.chars()
 1299                            .flat_map(|codepoint| codepoint.to_lowercase())
 1300                            .zip(query_start.to_lowercase())
 1301                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1302                    })
 1303                });
 1304            }
 1305        }
 1306
 1307        let completions = self.completions.read();
 1308        if self.sort_completions {
 1309            matches.sort_unstable_by_key(|mat| {
 1310                // We do want to strike a balance here between what the language server tells us
 1311                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1312                // `Creat` and there is a local variable called `CreateComponent`).
 1313                // So what we do is: we bucket all matches into two buckets
 1314                // - Strong matches
 1315                // - Weak matches
 1316                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1317                // and the Weak matches are the rest.
 1318                //
 1319                // For the strong matches, we sort by the language-servers score first and for the weak
 1320                // matches, we prefer our fuzzy finder first.
 1321                //
 1322                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1323                // us into account when it's obviously a bad match.
 1324
 1325                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1326                enum MatchScore<'a> {
 1327                    Strong {
 1328                        sort_text: Option<&'a str>,
 1329                        score: Reverse<OrderedFloat<f64>>,
 1330                        sort_key: (usize, &'a str),
 1331                    },
 1332                    Weak {
 1333                        score: Reverse<OrderedFloat<f64>>,
 1334                        sort_text: Option<&'a str>,
 1335                        sort_key: (usize, &'a str),
 1336                    },
 1337                }
 1338
 1339                let completion = &completions[mat.candidate_id];
 1340                let sort_key = completion.sort_key();
 1341                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1342                let score = Reverse(OrderedFloat(mat.score));
 1343
 1344                if mat.score >= 0.2 {
 1345                    MatchScore::Strong {
 1346                        sort_text,
 1347                        score,
 1348                        sort_key,
 1349                    }
 1350                } else {
 1351                    MatchScore::Weak {
 1352                        score,
 1353                        sort_text,
 1354                        sort_key,
 1355                    }
 1356                }
 1357            });
 1358        }
 1359
 1360        for mat in &mut matches {
 1361            let completion = &completions[mat.candidate_id];
 1362            mat.string.clone_from(&completion.label.text);
 1363            for position in &mut mat.positions {
 1364                *position += completion.label.filter_range.start;
 1365            }
 1366        }
 1367        drop(completions);
 1368
 1369        self.matches = matches.into();
 1370        self.selected_item = 0;
 1371    }
 1372}
 1373
 1374struct AvailableCodeAction {
 1375    excerpt_id: ExcerptId,
 1376    action: CodeAction,
 1377    provider: Arc<dyn CodeActionProvider>,
 1378}
 1379
 1380#[derive(Clone)]
 1381struct CodeActionContents {
 1382    tasks: Option<Arc<ResolvedTasks>>,
 1383    actions: Option<Arc<[AvailableCodeAction]>>,
 1384}
 1385
 1386impl CodeActionContents {
 1387    fn len(&self) -> usize {
 1388        match (&self.tasks, &self.actions) {
 1389            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1390            (Some(tasks), None) => tasks.templates.len(),
 1391            (None, Some(actions)) => actions.len(),
 1392            (None, None) => 0,
 1393        }
 1394    }
 1395
 1396    fn is_empty(&self) -> bool {
 1397        match (&self.tasks, &self.actions) {
 1398            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1399            (Some(tasks), None) => tasks.templates.is_empty(),
 1400            (None, Some(actions)) => actions.is_empty(),
 1401            (None, None) => true,
 1402        }
 1403    }
 1404
 1405    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1406        self.tasks
 1407            .iter()
 1408            .flat_map(|tasks| {
 1409                tasks
 1410                    .templates
 1411                    .iter()
 1412                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1413            })
 1414            .chain(self.actions.iter().flat_map(|actions| {
 1415                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1416                    excerpt_id: available.excerpt_id,
 1417                    action: available.action.clone(),
 1418                    provider: available.provider.clone(),
 1419                })
 1420            }))
 1421    }
 1422    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1423        match (&self.tasks, &self.actions) {
 1424            (Some(tasks), Some(actions)) => {
 1425                if index < tasks.templates.len() {
 1426                    tasks
 1427                        .templates
 1428                        .get(index)
 1429                        .cloned()
 1430                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1431                } else {
 1432                    actions.get(index - tasks.templates.len()).map(|available| {
 1433                        CodeActionsItem::CodeAction {
 1434                            excerpt_id: available.excerpt_id,
 1435                            action: available.action.clone(),
 1436                            provider: available.provider.clone(),
 1437                        }
 1438                    })
 1439                }
 1440            }
 1441            (Some(tasks), None) => tasks
 1442                .templates
 1443                .get(index)
 1444                .cloned()
 1445                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1446            (None, Some(actions)) => {
 1447                actions
 1448                    .get(index)
 1449                    .map(|available| CodeActionsItem::CodeAction {
 1450                        excerpt_id: available.excerpt_id,
 1451                        action: available.action.clone(),
 1452                        provider: available.provider.clone(),
 1453                    })
 1454            }
 1455            (None, None) => None,
 1456        }
 1457    }
 1458}
 1459
 1460#[allow(clippy::large_enum_variant)]
 1461#[derive(Clone)]
 1462enum CodeActionsItem {
 1463    Task(TaskSourceKind, ResolvedTask),
 1464    CodeAction {
 1465        excerpt_id: ExcerptId,
 1466        action: CodeAction,
 1467        provider: Arc<dyn CodeActionProvider>,
 1468    },
 1469}
 1470
 1471impl CodeActionsItem {
 1472    fn as_task(&self) -> Option<&ResolvedTask> {
 1473        let Self::Task(_, task) = self else {
 1474            return None;
 1475        };
 1476        Some(task)
 1477    }
 1478    fn as_code_action(&self) -> Option<&CodeAction> {
 1479        let Self::CodeAction { action, .. } = self else {
 1480            return None;
 1481        };
 1482        Some(action)
 1483    }
 1484    fn label(&self) -> String {
 1485        match self {
 1486            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1487            Self::Task(_, task) => task.resolved_label.clone(),
 1488        }
 1489    }
 1490}
 1491
 1492struct CodeActionsMenu {
 1493    actions: CodeActionContents,
 1494    buffer: Model<Buffer>,
 1495    selected_item: usize,
 1496    scroll_handle: UniformListScrollHandle,
 1497    deployed_from_indicator: Option<DisplayRow>,
 1498}
 1499
 1500impl CodeActionsMenu {
 1501    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1502        self.selected_item = 0;
 1503        self.scroll_handle.scroll_to_item(self.selected_item);
 1504        cx.notify()
 1505    }
 1506
 1507    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1508        if self.selected_item > 0 {
 1509            self.selected_item -= 1;
 1510        } else {
 1511            self.selected_item = self.actions.len() - 1;
 1512        }
 1513        self.scroll_handle.scroll_to_item(self.selected_item);
 1514        cx.notify();
 1515    }
 1516
 1517    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1518        if self.selected_item + 1 < self.actions.len() {
 1519            self.selected_item += 1;
 1520        } else {
 1521            self.selected_item = 0;
 1522        }
 1523        self.scroll_handle.scroll_to_item(self.selected_item);
 1524        cx.notify();
 1525    }
 1526
 1527    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1528        self.selected_item = self.actions.len() - 1;
 1529        self.scroll_handle.scroll_to_item(self.selected_item);
 1530        cx.notify()
 1531    }
 1532
 1533    fn visible(&self) -> bool {
 1534        !self.actions.is_empty()
 1535    }
 1536
 1537    fn render(
 1538        &self,
 1539        cursor_position: DisplayPoint,
 1540        _style: &EditorStyle,
 1541        max_height: Pixels,
 1542        cx: &mut ViewContext<Editor>,
 1543    ) -> (ContextMenuOrigin, AnyElement) {
 1544        let actions = self.actions.clone();
 1545        let selected_item = self.selected_item;
 1546        let element = uniform_list(
 1547            cx.view().clone(),
 1548            "code_actions_menu",
 1549            self.actions.len(),
 1550            move |_this, range, cx| {
 1551                actions
 1552                    .iter()
 1553                    .skip(range.start)
 1554                    .take(range.end - range.start)
 1555                    .enumerate()
 1556                    .map(|(ix, action)| {
 1557                        let item_ix = range.start + ix;
 1558                        let selected = selected_item == item_ix;
 1559                        let colors = cx.theme().colors();
 1560                        div()
 1561                            .px_1()
 1562                            .rounded_md()
 1563                            .text_color(colors.text)
 1564                            .when(selected, |style| {
 1565                                style
 1566                                    .bg(colors.element_active)
 1567                                    .text_color(colors.text_accent)
 1568                            })
 1569                            .hover(|style| {
 1570                                style
 1571                                    .bg(colors.element_hover)
 1572                                    .text_color(colors.text_accent)
 1573                            })
 1574                            .whitespace_nowrap()
 1575                            .when_some(action.as_code_action(), |this, action| {
 1576                                this.on_mouse_down(
 1577                                    MouseButton::Left,
 1578                                    cx.listener(move |editor, _, cx| {
 1579                                        cx.stop_propagation();
 1580                                        if let Some(task) = editor.confirm_code_action(
 1581                                            &ConfirmCodeAction {
 1582                                                item_ix: Some(item_ix),
 1583                                            },
 1584                                            cx,
 1585                                        ) {
 1586                                            task.detach_and_log_err(cx)
 1587                                        }
 1588                                    }),
 1589                                )
 1590                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1591                                .child(SharedString::from(action.lsp_action.title.clone()))
 1592                            })
 1593                            .when_some(action.as_task(), |this, task| {
 1594                                this.on_mouse_down(
 1595                                    MouseButton::Left,
 1596                                    cx.listener(move |editor, _, cx| {
 1597                                        cx.stop_propagation();
 1598                                        if let Some(task) = editor.confirm_code_action(
 1599                                            &ConfirmCodeAction {
 1600                                                item_ix: Some(item_ix),
 1601                                            },
 1602                                            cx,
 1603                                        ) {
 1604                                            task.detach_and_log_err(cx)
 1605                                        }
 1606                                    }),
 1607                                )
 1608                                .child(SharedString::from(task.resolved_label.clone()))
 1609                            })
 1610                    })
 1611                    .collect()
 1612            },
 1613        )
 1614        .elevation_1(cx)
 1615        .p_1()
 1616        .max_h(max_height)
 1617        .occlude()
 1618        .track_scroll(self.scroll_handle.clone())
 1619        .with_width_from_item(
 1620            self.actions
 1621                .iter()
 1622                .enumerate()
 1623                .max_by_key(|(_, action)| match action {
 1624                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1625                    CodeActionsItem::CodeAction { action, .. } => {
 1626                        action.lsp_action.title.chars().count()
 1627                    }
 1628                })
 1629                .map(|(ix, _)| ix),
 1630        )
 1631        .with_sizing_behavior(ListSizingBehavior::Infer)
 1632        .into_any_element();
 1633
 1634        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1635            ContextMenuOrigin::GutterIndicator(row)
 1636        } else {
 1637            ContextMenuOrigin::EditorPoint(cursor_position)
 1638        };
 1639
 1640        (cursor_position, element)
 1641    }
 1642}
 1643
 1644#[derive(Debug)]
 1645struct ActiveDiagnosticGroup {
 1646    primary_range: Range<Anchor>,
 1647    primary_message: String,
 1648    group_id: usize,
 1649    blocks: HashMap<CustomBlockId, Diagnostic>,
 1650    is_valid: bool,
 1651}
 1652
 1653#[derive(Serialize, Deserialize, Clone, Debug)]
 1654pub struct ClipboardSelection {
 1655    pub len: usize,
 1656    pub is_entire_line: bool,
 1657    pub first_line_indent: u32,
 1658}
 1659
 1660#[derive(Debug)]
 1661pub(crate) struct NavigationData {
 1662    cursor_anchor: Anchor,
 1663    cursor_position: Point,
 1664    scroll_anchor: ScrollAnchor,
 1665    scroll_top_row: u32,
 1666}
 1667
 1668#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1669enum GotoDefinitionKind {
 1670    Symbol,
 1671    Declaration,
 1672    Type,
 1673    Implementation,
 1674}
 1675
 1676#[derive(Debug, Clone)]
 1677enum InlayHintRefreshReason {
 1678    Toggle(bool),
 1679    SettingsChange(InlayHintSettings),
 1680    NewLinesShown,
 1681    BufferEdited(HashSet<Arc<Language>>),
 1682    RefreshRequested,
 1683    ExcerptsRemoved(Vec<ExcerptId>),
 1684}
 1685
 1686impl InlayHintRefreshReason {
 1687    fn description(&self) -> &'static str {
 1688        match self {
 1689            Self::Toggle(_) => "toggle",
 1690            Self::SettingsChange(_) => "settings change",
 1691            Self::NewLinesShown => "new lines shown",
 1692            Self::BufferEdited(_) => "buffer edited",
 1693            Self::RefreshRequested => "refresh requested",
 1694            Self::ExcerptsRemoved(_) => "excerpts removed",
 1695        }
 1696    }
 1697}
 1698
 1699pub(crate) struct FocusedBlock {
 1700    id: BlockId,
 1701    focus_handle: WeakFocusHandle,
 1702}
 1703
 1704impl Editor {
 1705    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1706        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1707        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1708        Self::new(
 1709            EditorMode::SingleLine { auto_width: false },
 1710            buffer,
 1711            None,
 1712            false,
 1713            cx,
 1714        )
 1715    }
 1716
 1717    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1718        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1719        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1720        Self::new(EditorMode::Full, buffer, None, false, cx)
 1721    }
 1722
 1723    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1724        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1725        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1726        Self::new(
 1727            EditorMode::SingleLine { auto_width: true },
 1728            buffer,
 1729            None,
 1730            false,
 1731            cx,
 1732        )
 1733    }
 1734
 1735    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1736        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1737        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1738        Self::new(
 1739            EditorMode::AutoHeight { max_lines },
 1740            buffer,
 1741            None,
 1742            false,
 1743            cx,
 1744        )
 1745    }
 1746
 1747    pub fn for_buffer(
 1748        buffer: Model<Buffer>,
 1749        project: Option<Model<Project>>,
 1750        cx: &mut ViewContext<Self>,
 1751    ) -> Self {
 1752        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1753        Self::new(EditorMode::Full, buffer, project, false, cx)
 1754    }
 1755
 1756    pub fn for_multibuffer(
 1757        buffer: Model<MultiBuffer>,
 1758        project: Option<Model<Project>>,
 1759        show_excerpt_controls: bool,
 1760        cx: &mut ViewContext<Self>,
 1761    ) -> Self {
 1762        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1763    }
 1764
 1765    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1766        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1767        let mut clone = Self::new(
 1768            self.mode,
 1769            self.buffer.clone(),
 1770            self.project.clone(),
 1771            show_excerpt_controls,
 1772            cx,
 1773        );
 1774        self.display_map.update(cx, |display_map, cx| {
 1775            let snapshot = display_map.snapshot(cx);
 1776            clone.display_map.update(cx, |display_map, cx| {
 1777                display_map.set_state(&snapshot, cx);
 1778            });
 1779        });
 1780        clone.selections.clone_state(&self.selections);
 1781        clone.scroll_manager.clone_state(&self.scroll_manager);
 1782        clone.searchable = self.searchable;
 1783        clone
 1784    }
 1785
 1786    pub fn new(
 1787        mode: EditorMode,
 1788        buffer: Model<MultiBuffer>,
 1789        project: Option<Model<Project>>,
 1790        show_excerpt_controls: bool,
 1791        cx: &mut ViewContext<Self>,
 1792    ) -> Self {
 1793        let style = cx.text_style();
 1794        let font_size = style.font_size.to_pixels(cx.rem_size());
 1795        let editor = cx.view().downgrade();
 1796        let fold_placeholder = FoldPlaceholder {
 1797            constrain_width: true,
 1798            render: Arc::new(move |fold_id, fold_range, cx| {
 1799                let editor = editor.clone();
 1800                div()
 1801                    .id(fold_id)
 1802                    .bg(cx.theme().colors().ghost_element_background)
 1803                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1804                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1805                    .rounded_sm()
 1806                    .size_full()
 1807                    .cursor_pointer()
 1808                    .child("")
 1809                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1810                    .on_click(move |_, cx| {
 1811                        editor
 1812                            .update(cx, |editor, cx| {
 1813                                editor.unfold_ranges(
 1814                                    [fold_range.start..fold_range.end],
 1815                                    true,
 1816                                    false,
 1817                                    cx,
 1818                                );
 1819                                cx.stop_propagation();
 1820                            })
 1821                            .ok();
 1822                    })
 1823                    .into_any()
 1824            }),
 1825            merge_adjacent: true,
 1826        };
 1827        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1828        let display_map = cx.new_model(|cx| {
 1829            DisplayMap::new(
 1830                buffer.clone(),
 1831                style.font(),
 1832                font_size,
 1833                None,
 1834                show_excerpt_controls,
 1835                file_header_size,
 1836                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1837                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1838                fold_placeholder,
 1839                cx,
 1840            )
 1841        });
 1842
 1843        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1844
 1845        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1846
 1847        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1848            .then(|| language_settings::SoftWrap::None);
 1849
 1850        let mut project_subscriptions = Vec::new();
 1851        if mode == EditorMode::Full {
 1852            if let Some(project) = project.as_ref() {
 1853                if buffer.read(cx).is_singleton() {
 1854                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1855                        cx.emit(EditorEvent::TitleChanged);
 1856                    }));
 1857                }
 1858                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1859                    if let project::Event::RefreshInlayHints = event {
 1860                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1861                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1862                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1863                            let focus_handle = editor.focus_handle(cx);
 1864                            if focus_handle.is_focused(cx) {
 1865                                let snapshot = buffer.read(cx).snapshot();
 1866                                for (range, snippet) in snippet_edits {
 1867                                    let editor_range =
 1868                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1869                                    editor
 1870                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1871                                        .ok();
 1872                                }
 1873                            }
 1874                        }
 1875                    }
 1876                }));
 1877                let task_inventory = project.read(cx).task_inventory().clone();
 1878                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1879                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1880                }));
 1881            }
 1882        }
 1883
 1884        let inlay_hint_settings = inlay_hint_settings(
 1885            selections.newest_anchor().head(),
 1886            &buffer.read(cx).snapshot(cx),
 1887            cx,
 1888        );
 1889        let focus_handle = cx.focus_handle();
 1890        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1891        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1892            .detach();
 1893        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1894            .detach();
 1895        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1896
 1897        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1898            Some(false)
 1899        } else {
 1900            None
 1901        };
 1902
 1903        let mut code_action_providers = Vec::new();
 1904        if let Some(project) = project.clone() {
 1905            code_action_providers.push(Arc::new(project) as Arc<_>);
 1906        }
 1907
 1908        let mut this = Self {
 1909            focus_handle,
 1910            show_cursor_when_unfocused: false,
 1911            last_focused_descendant: None,
 1912            buffer: buffer.clone(),
 1913            display_map: display_map.clone(),
 1914            selections,
 1915            scroll_manager: ScrollManager::new(cx),
 1916            columnar_selection_tail: None,
 1917            add_selections_state: None,
 1918            select_next_state: None,
 1919            select_prev_state: None,
 1920            selection_history: Default::default(),
 1921            autoclose_regions: Default::default(),
 1922            snippet_stack: Default::default(),
 1923            select_larger_syntax_node_stack: Vec::new(),
 1924            ime_transaction: Default::default(),
 1925            active_diagnostics: None,
 1926            soft_wrap_mode_override,
 1927            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1928            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1929            project,
 1930            blink_manager: blink_manager.clone(),
 1931            show_local_selections: true,
 1932            mode,
 1933            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1934            show_gutter: mode == EditorMode::Full,
 1935            show_line_numbers: None,
 1936            use_relative_line_numbers: None,
 1937            show_git_diff_gutter: None,
 1938            show_code_actions: None,
 1939            show_runnables: None,
 1940            show_wrap_guides: None,
 1941            show_indent_guides,
 1942            placeholder_text: None,
 1943            highlight_order: 0,
 1944            highlighted_rows: HashMap::default(),
 1945            background_highlights: Default::default(),
 1946            gutter_highlights: TreeMap::default(),
 1947            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1948            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1949            nav_history: None,
 1950            context_menu: RwLock::new(None),
 1951            mouse_context_menu: None,
 1952            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1953            completion_tasks: Default::default(),
 1954            signature_help_state: SignatureHelpState::default(),
 1955            auto_signature_help: None,
 1956            find_all_references_task_sources: Vec::new(),
 1957            next_completion_id: 0,
 1958            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1959            next_inlay_id: 0,
 1960            code_action_providers,
 1961            available_code_actions: Default::default(),
 1962            code_actions_task: Default::default(),
 1963            document_highlights_task: Default::default(),
 1964            linked_editing_range_task: Default::default(),
 1965            pending_rename: Default::default(),
 1966            searchable: true,
 1967            cursor_shape: EditorSettings::get_global(cx)
 1968                .cursor_shape
 1969                .unwrap_or_default(),
 1970            current_line_highlight: None,
 1971            autoindent_mode: Some(AutoindentMode::EachLine),
 1972            collapse_matches: false,
 1973            workspace: None,
 1974            input_enabled: true,
 1975            use_modal_editing: mode == EditorMode::Full,
 1976            read_only: false,
 1977            use_autoclose: true,
 1978            use_auto_surround: true,
 1979            auto_replace_emoji_shortcode: false,
 1980            leader_peer_id: None,
 1981            remote_id: None,
 1982            hover_state: Default::default(),
 1983            hovered_link_state: Default::default(),
 1984            inline_completion_provider: None,
 1985            active_inline_completion: None,
 1986            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1987            expanded_hunks: ExpandedHunks::default(),
 1988            gutter_hovered: false,
 1989            pixel_position_of_newest_cursor: None,
 1990            last_bounds: None,
 1991            expect_bounds_change: None,
 1992            gutter_dimensions: GutterDimensions::default(),
 1993            style: None,
 1994            show_cursor_names: false,
 1995            hovered_cursors: Default::default(),
 1996            next_editor_action_id: EditorActionId::default(),
 1997            editor_actions: Rc::default(),
 1998            show_inline_completions_override: None,
 1999            enable_inline_completions: true,
 2000            custom_context_menu: None,
 2001            show_git_blame_gutter: false,
 2002            show_git_blame_inline: false,
 2003            show_selection_menu: None,
 2004            show_git_blame_inline_delay_task: None,
 2005            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2006            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2007                .session
 2008                .restore_unsaved_buffers,
 2009            blame: None,
 2010            blame_subscription: None,
 2011            file_header_size,
 2012            tasks: Default::default(),
 2013            _subscriptions: vec![
 2014                cx.observe(&buffer, Self::on_buffer_changed),
 2015                cx.subscribe(&buffer, Self::on_buffer_event),
 2016                cx.observe(&display_map, Self::on_display_map_changed),
 2017                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2018                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2019                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2020                cx.observe_window_activation(|editor, cx| {
 2021                    let active = cx.is_window_active();
 2022                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2023                        if active {
 2024                            blink_manager.enable(cx);
 2025                        } else {
 2026                            blink_manager.disable(cx);
 2027                        }
 2028                    });
 2029                }),
 2030            ],
 2031            tasks_update_task: None,
 2032            linked_edit_ranges: Default::default(),
 2033            previous_search_ranges: None,
 2034            breadcrumb_header: None,
 2035            focused_block: None,
 2036            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2037            addons: HashMap::default(),
 2038            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2039        };
 2040        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2041        this._subscriptions.extend(project_subscriptions);
 2042
 2043        this.end_selection(cx);
 2044        this.scroll_manager.show_scrollbar(cx);
 2045
 2046        if mode == EditorMode::Full {
 2047            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2048            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2049
 2050            if this.git_blame_inline_enabled {
 2051                this.git_blame_inline_enabled = true;
 2052                this.start_git_blame_inline(false, cx);
 2053            }
 2054        }
 2055
 2056        this.report_editor_event("open", None, cx);
 2057        this
 2058    }
 2059
 2060    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2061        self.mouse_context_menu
 2062            .as_ref()
 2063            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2064    }
 2065
 2066    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2067        let mut key_context = KeyContext::new_with_defaults();
 2068        key_context.add("Editor");
 2069        let mode = match self.mode {
 2070            EditorMode::SingleLine { .. } => "single_line",
 2071            EditorMode::AutoHeight { .. } => "auto_height",
 2072            EditorMode::Full => "full",
 2073        };
 2074
 2075        if EditorSettings::jupyter_enabled(cx) {
 2076            key_context.add("jupyter");
 2077        }
 2078
 2079        key_context.set("mode", mode);
 2080        if self.pending_rename.is_some() {
 2081            key_context.add("renaming");
 2082        }
 2083        if self.context_menu_visible() {
 2084            match self.context_menu.read().as_ref() {
 2085                Some(ContextMenu::Completions(_)) => {
 2086                    key_context.add("menu");
 2087                    key_context.add("showing_completions")
 2088                }
 2089                Some(ContextMenu::CodeActions(_)) => {
 2090                    key_context.add("menu");
 2091                    key_context.add("showing_code_actions")
 2092                }
 2093                None => {}
 2094            }
 2095        }
 2096
 2097        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2098        if !self.focus_handle(cx).contains_focused(cx)
 2099            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2100        {
 2101            for addon in self.addons.values() {
 2102                addon.extend_key_context(&mut key_context, cx)
 2103            }
 2104        }
 2105
 2106        if let Some(extension) = self
 2107            .buffer
 2108            .read(cx)
 2109            .as_singleton()
 2110            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2111        {
 2112            key_context.set("extension", extension.to_string());
 2113        }
 2114
 2115        if self.has_active_inline_completion(cx) {
 2116            key_context.add("copilot_suggestion");
 2117            key_context.add("inline_completion");
 2118        }
 2119
 2120        key_context
 2121    }
 2122
 2123    pub fn new_file(
 2124        workspace: &mut Workspace,
 2125        _: &workspace::NewFile,
 2126        cx: &mut ViewContext<Workspace>,
 2127    ) {
 2128        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2129            "Failed to create buffer",
 2130            cx,
 2131            |e, _| match e.error_code() {
 2132                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2133                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2134                e.error_tag("required").unwrap_or("the latest version")
 2135            )),
 2136                _ => None,
 2137            },
 2138        );
 2139    }
 2140
 2141    pub fn new_in_workspace(
 2142        workspace: &mut Workspace,
 2143        cx: &mut ViewContext<Workspace>,
 2144    ) -> Task<Result<View<Editor>>> {
 2145        let project = workspace.project().clone();
 2146        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2147
 2148        cx.spawn(|workspace, mut cx| async move {
 2149            let buffer = create.await?;
 2150            workspace.update(&mut cx, |workspace, cx| {
 2151                let editor =
 2152                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2153                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2154                editor
 2155            })
 2156        })
 2157    }
 2158
 2159    fn new_file_vertical(
 2160        workspace: &mut Workspace,
 2161        _: &workspace::NewFileSplitVertical,
 2162        cx: &mut ViewContext<Workspace>,
 2163    ) {
 2164        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2165    }
 2166
 2167    fn new_file_horizontal(
 2168        workspace: &mut Workspace,
 2169        _: &workspace::NewFileSplitHorizontal,
 2170        cx: &mut ViewContext<Workspace>,
 2171    ) {
 2172        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2173    }
 2174
 2175    fn new_file_in_direction(
 2176        workspace: &mut Workspace,
 2177        direction: SplitDirection,
 2178        cx: &mut ViewContext<Workspace>,
 2179    ) {
 2180        let project = workspace.project().clone();
 2181        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2182
 2183        cx.spawn(|workspace, mut cx| async move {
 2184            let buffer = create.await?;
 2185            workspace.update(&mut cx, move |workspace, cx| {
 2186                workspace.split_item(
 2187                    direction,
 2188                    Box::new(
 2189                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2190                    ),
 2191                    cx,
 2192                )
 2193            })?;
 2194            anyhow::Ok(())
 2195        })
 2196        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2197            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2198                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2199                e.error_tag("required").unwrap_or("the latest version")
 2200            )),
 2201            _ => None,
 2202        });
 2203    }
 2204
 2205    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2206        self.leader_peer_id
 2207    }
 2208
 2209    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2210        &self.buffer
 2211    }
 2212
 2213    pub fn workspace(&self) -> Option<View<Workspace>> {
 2214        self.workspace.as_ref()?.0.upgrade()
 2215    }
 2216
 2217    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2218        self.buffer().read(cx).title(cx)
 2219    }
 2220
 2221    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2222        let git_blame_gutter_max_author_length = self
 2223            .render_git_blame_gutter(cx)
 2224            .then(|| {
 2225                if let Some(blame) = self.blame.as_ref() {
 2226                    let max_author_length =
 2227                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2228                    Some(max_author_length)
 2229                } else {
 2230                    None
 2231                }
 2232            })
 2233            .flatten();
 2234
 2235        EditorSnapshot {
 2236            mode: self.mode,
 2237            show_gutter: self.show_gutter,
 2238            show_line_numbers: self.show_line_numbers,
 2239            show_git_diff_gutter: self.show_git_diff_gutter,
 2240            show_code_actions: self.show_code_actions,
 2241            show_runnables: self.show_runnables,
 2242            git_blame_gutter_max_author_length,
 2243            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2244            scroll_anchor: self.scroll_manager.anchor(),
 2245            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2246            placeholder_text: self.placeholder_text.clone(),
 2247            is_focused: self.focus_handle.is_focused(cx),
 2248            current_line_highlight: self
 2249                .current_line_highlight
 2250                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2251            gutter_hovered: self.gutter_hovered,
 2252        }
 2253    }
 2254
 2255    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2256        self.buffer.read(cx).language_at(point, cx)
 2257    }
 2258
 2259    pub fn file_at<T: ToOffset>(
 2260        &self,
 2261        point: T,
 2262        cx: &AppContext,
 2263    ) -> Option<Arc<dyn language::File>> {
 2264        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2265    }
 2266
 2267    pub fn active_excerpt(
 2268        &self,
 2269        cx: &AppContext,
 2270    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2271        self.buffer
 2272            .read(cx)
 2273            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2274    }
 2275
 2276    pub fn mode(&self) -> EditorMode {
 2277        self.mode
 2278    }
 2279
 2280    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2281        self.collaboration_hub.as_deref()
 2282    }
 2283
 2284    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2285        self.collaboration_hub = Some(hub);
 2286    }
 2287
 2288    pub fn set_custom_context_menu(
 2289        &mut self,
 2290        f: impl 'static
 2291            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2292    ) {
 2293        self.custom_context_menu = Some(Box::new(f))
 2294    }
 2295
 2296    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2297        self.completion_provider = Some(provider);
 2298    }
 2299
 2300    pub fn set_inline_completion_provider<T>(
 2301        &mut self,
 2302        provider: Option<Model<T>>,
 2303        cx: &mut ViewContext<Self>,
 2304    ) where
 2305        T: InlineCompletionProvider,
 2306    {
 2307        self.inline_completion_provider =
 2308            provider.map(|provider| RegisteredInlineCompletionProvider {
 2309                _subscription: cx.observe(&provider, |this, _, cx| {
 2310                    if this.focus_handle.is_focused(cx) {
 2311                        this.update_visible_inline_completion(cx);
 2312                    }
 2313                }),
 2314                provider: Arc::new(provider),
 2315            });
 2316        self.refresh_inline_completion(false, false, cx);
 2317    }
 2318
 2319    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2320        self.placeholder_text.as_deref()
 2321    }
 2322
 2323    pub fn set_placeholder_text(
 2324        &mut self,
 2325        placeholder_text: impl Into<Arc<str>>,
 2326        cx: &mut ViewContext<Self>,
 2327    ) {
 2328        let placeholder_text = Some(placeholder_text.into());
 2329        if self.placeholder_text != placeholder_text {
 2330            self.placeholder_text = placeholder_text;
 2331            cx.notify();
 2332        }
 2333    }
 2334
 2335    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2336        self.cursor_shape = cursor_shape;
 2337
 2338        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2339        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2340
 2341        cx.notify();
 2342    }
 2343
 2344    pub fn set_current_line_highlight(
 2345        &mut self,
 2346        current_line_highlight: Option<CurrentLineHighlight>,
 2347    ) {
 2348        self.current_line_highlight = current_line_highlight;
 2349    }
 2350
 2351    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2352        self.collapse_matches = collapse_matches;
 2353    }
 2354
 2355    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2356        if self.collapse_matches {
 2357            return range.start..range.start;
 2358        }
 2359        range.clone()
 2360    }
 2361
 2362    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2363        if self.display_map.read(cx).clip_at_line_ends != clip {
 2364            self.display_map
 2365                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2366        }
 2367    }
 2368
 2369    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2370        self.input_enabled = input_enabled;
 2371    }
 2372
 2373    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2374        self.enable_inline_completions = enabled;
 2375    }
 2376
 2377    pub fn set_autoindent(&mut self, autoindent: bool) {
 2378        if autoindent {
 2379            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2380        } else {
 2381            self.autoindent_mode = None;
 2382        }
 2383    }
 2384
 2385    pub fn read_only(&self, cx: &AppContext) -> bool {
 2386        self.read_only || self.buffer.read(cx).read_only()
 2387    }
 2388
 2389    pub fn set_read_only(&mut self, read_only: bool) {
 2390        self.read_only = read_only;
 2391    }
 2392
 2393    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2394        self.use_autoclose = autoclose;
 2395    }
 2396
 2397    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2398        self.use_auto_surround = auto_surround;
 2399    }
 2400
 2401    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2402        self.auto_replace_emoji_shortcode = auto_replace;
 2403    }
 2404
 2405    pub fn toggle_inline_completions(
 2406        &mut self,
 2407        _: &ToggleInlineCompletions,
 2408        cx: &mut ViewContext<Self>,
 2409    ) {
 2410        if self.show_inline_completions_override.is_some() {
 2411            self.set_show_inline_completions(None, cx);
 2412        } else {
 2413            let cursor = self.selections.newest_anchor().head();
 2414            if let Some((buffer, cursor_buffer_position)) =
 2415                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2416            {
 2417                let show_inline_completions =
 2418                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2419                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2420            }
 2421        }
 2422    }
 2423
 2424    pub fn set_show_inline_completions(
 2425        &mut self,
 2426        show_inline_completions: Option<bool>,
 2427        cx: &mut ViewContext<Self>,
 2428    ) {
 2429        self.show_inline_completions_override = show_inline_completions;
 2430        self.refresh_inline_completion(false, true, cx);
 2431    }
 2432
 2433    fn should_show_inline_completions(
 2434        &self,
 2435        buffer: &Model<Buffer>,
 2436        buffer_position: language::Anchor,
 2437        cx: &AppContext,
 2438    ) -> bool {
 2439        if let Some(provider) = self.inline_completion_provider() {
 2440            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2441                show_inline_completions
 2442            } else {
 2443                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2444            }
 2445        } else {
 2446            false
 2447        }
 2448    }
 2449
 2450    pub fn set_use_modal_editing(&mut self, to: bool) {
 2451        self.use_modal_editing = to;
 2452    }
 2453
 2454    pub fn use_modal_editing(&self) -> bool {
 2455        self.use_modal_editing
 2456    }
 2457
 2458    fn selections_did_change(
 2459        &mut self,
 2460        local: bool,
 2461        old_cursor_position: &Anchor,
 2462        show_completions: bool,
 2463        cx: &mut ViewContext<Self>,
 2464    ) {
 2465        cx.invalidate_character_coordinates();
 2466
 2467        // Copy selections to primary selection buffer
 2468        #[cfg(target_os = "linux")]
 2469        if local {
 2470            let selections = self.selections.all::<usize>(cx);
 2471            let buffer_handle = self.buffer.read(cx).read(cx);
 2472
 2473            let mut text = String::new();
 2474            for (index, selection) in selections.iter().enumerate() {
 2475                let text_for_selection = buffer_handle
 2476                    .text_for_range(selection.start..selection.end)
 2477                    .collect::<String>();
 2478
 2479                text.push_str(&text_for_selection);
 2480                if index != selections.len() - 1 {
 2481                    text.push('\n');
 2482                }
 2483            }
 2484
 2485            if !text.is_empty() {
 2486                cx.write_to_primary(ClipboardItem::new_string(text));
 2487            }
 2488        }
 2489
 2490        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2491            self.buffer.update(cx, |buffer, cx| {
 2492                buffer.set_active_selections(
 2493                    &self.selections.disjoint_anchors(),
 2494                    self.selections.line_mode,
 2495                    self.cursor_shape,
 2496                    cx,
 2497                )
 2498            });
 2499        }
 2500        let display_map = self
 2501            .display_map
 2502            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2503        let buffer = &display_map.buffer_snapshot;
 2504        self.add_selections_state = None;
 2505        self.select_next_state = None;
 2506        self.select_prev_state = None;
 2507        self.select_larger_syntax_node_stack.clear();
 2508        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2509        self.snippet_stack
 2510            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2511        self.take_rename(false, cx);
 2512
 2513        let new_cursor_position = self.selections.newest_anchor().head();
 2514
 2515        self.push_to_nav_history(
 2516            *old_cursor_position,
 2517            Some(new_cursor_position.to_point(buffer)),
 2518            cx,
 2519        );
 2520
 2521        if local {
 2522            let new_cursor_position = self.selections.newest_anchor().head();
 2523            let mut context_menu = self.context_menu.write();
 2524            let completion_menu = match context_menu.as_ref() {
 2525                Some(ContextMenu::Completions(menu)) => Some(menu),
 2526
 2527                _ => {
 2528                    *context_menu = None;
 2529                    None
 2530                }
 2531            };
 2532
 2533            if let Some(completion_menu) = completion_menu {
 2534                let cursor_position = new_cursor_position.to_offset(buffer);
 2535                let (word_range, kind) =
 2536                    buffer.surrounding_word(completion_menu.initial_position, true);
 2537                if kind == Some(CharKind::Word)
 2538                    && word_range.to_inclusive().contains(&cursor_position)
 2539                {
 2540                    let mut completion_menu = completion_menu.clone();
 2541                    drop(context_menu);
 2542
 2543                    let query = Self::completion_query(buffer, cursor_position);
 2544                    cx.spawn(move |this, mut cx| async move {
 2545                        completion_menu
 2546                            .filter(query.as_deref(), cx.background_executor().clone())
 2547                            .await;
 2548
 2549                        this.update(&mut cx, |this, cx| {
 2550                            let mut context_menu = this.context_menu.write();
 2551                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2552                                return;
 2553                            };
 2554
 2555                            if menu.id > completion_menu.id {
 2556                                return;
 2557                            }
 2558
 2559                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2560                            drop(context_menu);
 2561                            cx.notify();
 2562                        })
 2563                    })
 2564                    .detach();
 2565
 2566                    if show_completions {
 2567                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2568                    }
 2569                } else {
 2570                    drop(context_menu);
 2571                    self.hide_context_menu(cx);
 2572                }
 2573            } else {
 2574                drop(context_menu);
 2575            }
 2576
 2577            hide_hover(self, cx);
 2578
 2579            if old_cursor_position.to_display_point(&display_map).row()
 2580                != new_cursor_position.to_display_point(&display_map).row()
 2581            {
 2582                self.available_code_actions.take();
 2583            }
 2584            self.refresh_code_actions(cx);
 2585            self.refresh_document_highlights(cx);
 2586            refresh_matching_bracket_highlights(self, cx);
 2587            self.discard_inline_completion(false, cx);
 2588            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2589            if self.git_blame_inline_enabled {
 2590                self.start_inline_blame_timer(cx);
 2591            }
 2592        }
 2593
 2594        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2595        cx.emit(EditorEvent::SelectionsChanged { local });
 2596
 2597        if self.selections.disjoint_anchors().len() == 1 {
 2598            cx.emit(SearchEvent::ActiveMatchChanged)
 2599        }
 2600        cx.notify();
 2601    }
 2602
 2603    pub fn change_selections<R>(
 2604        &mut self,
 2605        autoscroll: Option<Autoscroll>,
 2606        cx: &mut ViewContext<Self>,
 2607        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2608    ) -> R {
 2609        self.change_selections_inner(autoscroll, true, cx, change)
 2610    }
 2611
 2612    pub fn change_selections_inner<R>(
 2613        &mut self,
 2614        autoscroll: Option<Autoscroll>,
 2615        request_completions: bool,
 2616        cx: &mut ViewContext<Self>,
 2617        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2618    ) -> R {
 2619        let old_cursor_position = self.selections.newest_anchor().head();
 2620        self.push_to_selection_history();
 2621
 2622        let (changed, result) = self.selections.change_with(cx, change);
 2623
 2624        if changed {
 2625            if let Some(autoscroll) = autoscroll {
 2626                self.request_autoscroll(autoscroll, cx);
 2627            }
 2628            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2629
 2630            if self.should_open_signature_help_automatically(
 2631                &old_cursor_position,
 2632                self.signature_help_state.backspace_pressed(),
 2633                cx,
 2634            ) {
 2635                self.show_signature_help(&ShowSignatureHelp, cx);
 2636            }
 2637            self.signature_help_state.set_backspace_pressed(false);
 2638        }
 2639
 2640        result
 2641    }
 2642
 2643    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2644    where
 2645        I: IntoIterator<Item = (Range<S>, T)>,
 2646        S: ToOffset,
 2647        T: Into<Arc<str>>,
 2648    {
 2649        if self.read_only(cx) {
 2650            return;
 2651        }
 2652
 2653        self.buffer
 2654            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2655    }
 2656
 2657    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2658    where
 2659        I: IntoIterator<Item = (Range<S>, T)>,
 2660        S: ToOffset,
 2661        T: Into<Arc<str>>,
 2662    {
 2663        if self.read_only(cx) {
 2664            return;
 2665        }
 2666
 2667        self.buffer.update(cx, |buffer, cx| {
 2668            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2669        });
 2670    }
 2671
 2672    pub fn edit_with_block_indent<I, S, T>(
 2673        &mut self,
 2674        edits: I,
 2675        original_indent_columns: Vec<u32>,
 2676        cx: &mut ViewContext<Self>,
 2677    ) where
 2678        I: IntoIterator<Item = (Range<S>, T)>,
 2679        S: ToOffset,
 2680        T: Into<Arc<str>>,
 2681    {
 2682        if self.read_only(cx) {
 2683            return;
 2684        }
 2685
 2686        self.buffer.update(cx, |buffer, cx| {
 2687            buffer.edit(
 2688                edits,
 2689                Some(AutoindentMode::Block {
 2690                    original_indent_columns,
 2691                }),
 2692                cx,
 2693            )
 2694        });
 2695    }
 2696
 2697    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2698        self.hide_context_menu(cx);
 2699
 2700        match phase {
 2701            SelectPhase::Begin {
 2702                position,
 2703                add,
 2704                click_count,
 2705            } => self.begin_selection(position, add, click_count, cx),
 2706            SelectPhase::BeginColumnar {
 2707                position,
 2708                goal_column,
 2709                reset,
 2710            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2711            SelectPhase::Extend {
 2712                position,
 2713                click_count,
 2714            } => self.extend_selection(position, click_count, cx),
 2715            SelectPhase::Update {
 2716                position,
 2717                goal_column,
 2718                scroll_delta,
 2719            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2720            SelectPhase::End => self.end_selection(cx),
 2721        }
 2722    }
 2723
 2724    fn extend_selection(
 2725        &mut self,
 2726        position: DisplayPoint,
 2727        click_count: usize,
 2728        cx: &mut ViewContext<Self>,
 2729    ) {
 2730        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2731        let tail = self.selections.newest::<usize>(cx).tail();
 2732        self.begin_selection(position, false, click_count, cx);
 2733
 2734        let position = position.to_offset(&display_map, Bias::Left);
 2735        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2736
 2737        let mut pending_selection = self
 2738            .selections
 2739            .pending_anchor()
 2740            .expect("extend_selection not called with pending selection");
 2741        if position >= tail {
 2742            pending_selection.start = tail_anchor;
 2743        } else {
 2744            pending_selection.end = tail_anchor;
 2745            pending_selection.reversed = true;
 2746        }
 2747
 2748        let mut pending_mode = self.selections.pending_mode().unwrap();
 2749        match &mut pending_mode {
 2750            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2751            _ => {}
 2752        }
 2753
 2754        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2755            s.set_pending(pending_selection, pending_mode)
 2756        });
 2757    }
 2758
 2759    fn begin_selection(
 2760        &mut self,
 2761        position: DisplayPoint,
 2762        add: bool,
 2763        click_count: usize,
 2764        cx: &mut ViewContext<Self>,
 2765    ) {
 2766        if !self.focus_handle.is_focused(cx) {
 2767            self.last_focused_descendant = None;
 2768            cx.focus(&self.focus_handle);
 2769        }
 2770
 2771        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2772        let buffer = &display_map.buffer_snapshot;
 2773        let newest_selection = self.selections.newest_anchor().clone();
 2774        let position = display_map.clip_point(position, Bias::Left);
 2775
 2776        let start;
 2777        let end;
 2778        let mode;
 2779        let auto_scroll;
 2780        match click_count {
 2781            1 => {
 2782                start = buffer.anchor_before(position.to_point(&display_map));
 2783                end = start;
 2784                mode = SelectMode::Character;
 2785                auto_scroll = true;
 2786            }
 2787            2 => {
 2788                let range = movement::surrounding_word(&display_map, position);
 2789                start = buffer.anchor_before(range.start.to_point(&display_map));
 2790                end = buffer.anchor_before(range.end.to_point(&display_map));
 2791                mode = SelectMode::Word(start..end);
 2792                auto_scroll = true;
 2793            }
 2794            3 => {
 2795                let position = display_map
 2796                    .clip_point(position, Bias::Left)
 2797                    .to_point(&display_map);
 2798                let line_start = display_map.prev_line_boundary(position).0;
 2799                let next_line_start = buffer.clip_point(
 2800                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2801                    Bias::Left,
 2802                );
 2803                start = buffer.anchor_before(line_start);
 2804                end = buffer.anchor_before(next_line_start);
 2805                mode = SelectMode::Line(start..end);
 2806                auto_scroll = true;
 2807            }
 2808            _ => {
 2809                start = buffer.anchor_before(0);
 2810                end = buffer.anchor_before(buffer.len());
 2811                mode = SelectMode::All;
 2812                auto_scroll = false;
 2813            }
 2814        }
 2815
 2816        let point_to_delete: Option<usize> = {
 2817            let selected_points: Vec<Selection<Point>> =
 2818                self.selections.disjoint_in_range(start..end, cx);
 2819
 2820            if !add || click_count > 1 {
 2821                None
 2822            } else if !selected_points.is_empty() {
 2823                Some(selected_points[0].id)
 2824            } else {
 2825                let clicked_point_already_selected =
 2826                    self.selections.disjoint.iter().find(|selection| {
 2827                        selection.start.to_point(buffer) == start.to_point(buffer)
 2828                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2829                    });
 2830
 2831                clicked_point_already_selected.map(|selection| selection.id)
 2832            }
 2833        };
 2834
 2835        let selections_count = self.selections.count();
 2836
 2837        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2838            if let Some(point_to_delete) = point_to_delete {
 2839                s.delete(point_to_delete);
 2840
 2841                if selections_count == 1 {
 2842                    s.set_pending_anchor_range(start..end, mode);
 2843                }
 2844            } else {
 2845                if !add {
 2846                    s.clear_disjoint();
 2847                } else if click_count > 1 {
 2848                    s.delete(newest_selection.id)
 2849                }
 2850
 2851                s.set_pending_anchor_range(start..end, mode);
 2852            }
 2853        });
 2854    }
 2855
 2856    fn begin_columnar_selection(
 2857        &mut self,
 2858        position: DisplayPoint,
 2859        goal_column: u32,
 2860        reset: bool,
 2861        cx: &mut ViewContext<Self>,
 2862    ) {
 2863        if !self.focus_handle.is_focused(cx) {
 2864            self.last_focused_descendant = None;
 2865            cx.focus(&self.focus_handle);
 2866        }
 2867
 2868        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2869
 2870        if reset {
 2871            let pointer_position = display_map
 2872                .buffer_snapshot
 2873                .anchor_before(position.to_point(&display_map));
 2874
 2875            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2876                s.clear_disjoint();
 2877                s.set_pending_anchor_range(
 2878                    pointer_position..pointer_position,
 2879                    SelectMode::Character,
 2880                );
 2881            });
 2882        }
 2883
 2884        let tail = self.selections.newest::<Point>(cx).tail();
 2885        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2886
 2887        if !reset {
 2888            self.select_columns(
 2889                tail.to_display_point(&display_map),
 2890                position,
 2891                goal_column,
 2892                &display_map,
 2893                cx,
 2894            );
 2895        }
 2896    }
 2897
 2898    fn update_selection(
 2899        &mut self,
 2900        position: DisplayPoint,
 2901        goal_column: u32,
 2902        scroll_delta: gpui::Point<f32>,
 2903        cx: &mut ViewContext<Self>,
 2904    ) {
 2905        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2906
 2907        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2908            let tail = tail.to_display_point(&display_map);
 2909            self.select_columns(tail, position, goal_column, &display_map, cx);
 2910        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2911            let buffer = self.buffer.read(cx).snapshot(cx);
 2912            let head;
 2913            let tail;
 2914            let mode = self.selections.pending_mode().unwrap();
 2915            match &mode {
 2916                SelectMode::Character => {
 2917                    head = position.to_point(&display_map);
 2918                    tail = pending.tail().to_point(&buffer);
 2919                }
 2920                SelectMode::Word(original_range) => {
 2921                    let original_display_range = original_range.start.to_display_point(&display_map)
 2922                        ..original_range.end.to_display_point(&display_map);
 2923                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2924                        ..original_display_range.end.to_point(&display_map);
 2925                    if movement::is_inside_word(&display_map, position)
 2926                        || original_display_range.contains(&position)
 2927                    {
 2928                        let word_range = movement::surrounding_word(&display_map, position);
 2929                        if word_range.start < original_display_range.start {
 2930                            head = word_range.start.to_point(&display_map);
 2931                        } else {
 2932                            head = word_range.end.to_point(&display_map);
 2933                        }
 2934                    } else {
 2935                        head = position.to_point(&display_map);
 2936                    }
 2937
 2938                    if head <= original_buffer_range.start {
 2939                        tail = original_buffer_range.end;
 2940                    } else {
 2941                        tail = original_buffer_range.start;
 2942                    }
 2943                }
 2944                SelectMode::Line(original_range) => {
 2945                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2946
 2947                    let position = display_map
 2948                        .clip_point(position, Bias::Left)
 2949                        .to_point(&display_map);
 2950                    let line_start = display_map.prev_line_boundary(position).0;
 2951                    let next_line_start = buffer.clip_point(
 2952                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2953                        Bias::Left,
 2954                    );
 2955
 2956                    if line_start < original_range.start {
 2957                        head = line_start
 2958                    } else {
 2959                        head = next_line_start
 2960                    }
 2961
 2962                    if head <= original_range.start {
 2963                        tail = original_range.end;
 2964                    } else {
 2965                        tail = original_range.start;
 2966                    }
 2967                }
 2968                SelectMode::All => {
 2969                    return;
 2970                }
 2971            };
 2972
 2973            if head < tail {
 2974                pending.start = buffer.anchor_before(head);
 2975                pending.end = buffer.anchor_before(tail);
 2976                pending.reversed = true;
 2977            } else {
 2978                pending.start = buffer.anchor_before(tail);
 2979                pending.end = buffer.anchor_before(head);
 2980                pending.reversed = false;
 2981            }
 2982
 2983            self.change_selections(None, cx, |s| {
 2984                s.set_pending(pending, mode);
 2985            });
 2986        } else {
 2987            log::error!("update_selection dispatched with no pending selection");
 2988            return;
 2989        }
 2990
 2991        self.apply_scroll_delta(scroll_delta, cx);
 2992        cx.notify();
 2993    }
 2994
 2995    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2996        self.columnar_selection_tail.take();
 2997        if self.selections.pending_anchor().is_some() {
 2998            let selections = self.selections.all::<usize>(cx);
 2999            self.change_selections(None, cx, |s| {
 3000                s.select(selections);
 3001                s.clear_pending();
 3002            });
 3003        }
 3004    }
 3005
 3006    fn select_columns(
 3007        &mut self,
 3008        tail: DisplayPoint,
 3009        head: DisplayPoint,
 3010        goal_column: u32,
 3011        display_map: &DisplaySnapshot,
 3012        cx: &mut ViewContext<Self>,
 3013    ) {
 3014        let start_row = cmp::min(tail.row(), head.row());
 3015        let end_row = cmp::max(tail.row(), head.row());
 3016        let start_column = cmp::min(tail.column(), goal_column);
 3017        let end_column = cmp::max(tail.column(), goal_column);
 3018        let reversed = start_column < tail.column();
 3019
 3020        let selection_ranges = (start_row.0..=end_row.0)
 3021            .map(DisplayRow)
 3022            .filter_map(|row| {
 3023                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3024                    let start = display_map
 3025                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3026                        .to_point(display_map);
 3027                    let end = display_map
 3028                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3029                        .to_point(display_map);
 3030                    if reversed {
 3031                        Some(end..start)
 3032                    } else {
 3033                        Some(start..end)
 3034                    }
 3035                } else {
 3036                    None
 3037                }
 3038            })
 3039            .collect::<Vec<_>>();
 3040
 3041        self.change_selections(None, cx, |s| {
 3042            s.select_ranges(selection_ranges);
 3043        });
 3044        cx.notify();
 3045    }
 3046
 3047    pub fn has_pending_nonempty_selection(&self) -> bool {
 3048        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3049            Some(Selection { start, end, .. }) => start != end,
 3050            None => false,
 3051        };
 3052
 3053        pending_nonempty_selection
 3054            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3055    }
 3056
 3057    pub fn has_pending_selection(&self) -> bool {
 3058        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3059    }
 3060
 3061    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3062        if self.clear_expanded_diff_hunks(cx) {
 3063            cx.notify();
 3064            return;
 3065        }
 3066        if self.dismiss_menus_and_popups(true, cx) {
 3067            return;
 3068        }
 3069
 3070        if self.mode == EditorMode::Full
 3071            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3072        {
 3073            return;
 3074        }
 3075
 3076        cx.propagate();
 3077    }
 3078
 3079    pub fn dismiss_menus_and_popups(
 3080        &mut self,
 3081        should_report_inline_completion_event: bool,
 3082        cx: &mut ViewContext<Self>,
 3083    ) -> bool {
 3084        if self.take_rename(false, cx).is_some() {
 3085            return true;
 3086        }
 3087
 3088        if hide_hover(self, cx) {
 3089            return true;
 3090        }
 3091
 3092        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3093            return true;
 3094        }
 3095
 3096        if self.hide_context_menu(cx).is_some() {
 3097            return true;
 3098        }
 3099
 3100        if self.mouse_context_menu.take().is_some() {
 3101            return true;
 3102        }
 3103
 3104        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3105            return true;
 3106        }
 3107
 3108        if self.snippet_stack.pop().is_some() {
 3109            return true;
 3110        }
 3111
 3112        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3113            self.dismiss_diagnostics(cx);
 3114            return true;
 3115        }
 3116
 3117        false
 3118    }
 3119
 3120    fn linked_editing_ranges_for(
 3121        &self,
 3122        selection: Range<text::Anchor>,
 3123        cx: &AppContext,
 3124    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3125        if self.linked_edit_ranges.is_empty() {
 3126            return None;
 3127        }
 3128        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3129            selection.end.buffer_id.and_then(|end_buffer_id| {
 3130                if selection.start.buffer_id != Some(end_buffer_id) {
 3131                    return None;
 3132                }
 3133                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3134                let snapshot = buffer.read(cx).snapshot();
 3135                self.linked_edit_ranges
 3136                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3137                    .map(|ranges| (ranges, snapshot, buffer))
 3138            })?;
 3139        use text::ToOffset as TO;
 3140        // find offset from the start of current range to current cursor position
 3141        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3142
 3143        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3144        let start_difference = start_offset - start_byte_offset;
 3145        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3146        let end_difference = end_offset - start_byte_offset;
 3147        // Current range has associated linked ranges.
 3148        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3149        for range in linked_ranges.iter() {
 3150            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3151            let end_offset = start_offset + end_difference;
 3152            let start_offset = start_offset + start_difference;
 3153            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3154                continue;
 3155            }
 3156            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3157                if s.start.buffer_id != selection.start.buffer_id
 3158                    || s.end.buffer_id != selection.end.buffer_id
 3159                {
 3160                    return false;
 3161                }
 3162                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3163                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3164            }) {
 3165                continue;
 3166            }
 3167            let start = buffer_snapshot.anchor_after(start_offset);
 3168            let end = buffer_snapshot.anchor_after(end_offset);
 3169            linked_edits
 3170                .entry(buffer.clone())
 3171                .or_default()
 3172                .push(start..end);
 3173        }
 3174        Some(linked_edits)
 3175    }
 3176
 3177    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3178        let text: Arc<str> = text.into();
 3179
 3180        if self.read_only(cx) {
 3181            return;
 3182        }
 3183
 3184        let selections = self.selections.all_adjusted(cx);
 3185        let mut bracket_inserted = false;
 3186        let mut edits = Vec::new();
 3187        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3188        let mut new_selections = Vec::with_capacity(selections.len());
 3189        let mut new_autoclose_regions = Vec::new();
 3190        let snapshot = self.buffer.read(cx).read(cx);
 3191
 3192        for (selection, autoclose_region) in
 3193            self.selections_with_autoclose_regions(selections, &snapshot)
 3194        {
 3195            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3196                // Determine if the inserted text matches the opening or closing
 3197                // bracket of any of this language's bracket pairs.
 3198                let mut bracket_pair = None;
 3199                let mut is_bracket_pair_start = false;
 3200                let mut is_bracket_pair_end = false;
 3201                if !text.is_empty() {
 3202                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3203                    //  and they are removing the character that triggered IME popup.
 3204                    for (pair, enabled) in scope.brackets() {
 3205                        if !pair.close && !pair.surround {
 3206                            continue;
 3207                        }
 3208
 3209                        if enabled && pair.start.ends_with(text.as_ref()) {
 3210                            bracket_pair = Some(pair.clone());
 3211                            is_bracket_pair_start = true;
 3212                            break;
 3213                        }
 3214                        if pair.end.as_str() == text.as_ref() {
 3215                            bracket_pair = Some(pair.clone());
 3216                            is_bracket_pair_end = true;
 3217                            break;
 3218                        }
 3219                    }
 3220                }
 3221
 3222                if let Some(bracket_pair) = bracket_pair {
 3223                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3224                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3225                    let auto_surround =
 3226                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3227                    if selection.is_empty() {
 3228                        if is_bracket_pair_start {
 3229                            let prefix_len = bracket_pair.start.len() - text.len();
 3230
 3231                            // If the inserted text is a suffix of an opening bracket and the
 3232                            // selection is preceded by the rest of the opening bracket, then
 3233                            // insert the closing bracket.
 3234                            let following_text_allows_autoclose = snapshot
 3235                                .chars_at(selection.start)
 3236                                .next()
 3237                                .map_or(true, |c| scope.should_autoclose_before(c));
 3238                            let preceding_text_matches_prefix = prefix_len == 0
 3239                                || (selection.start.column >= (prefix_len as u32)
 3240                                    && snapshot.contains_str_at(
 3241                                        Point::new(
 3242                                            selection.start.row,
 3243                                            selection.start.column - (prefix_len as u32),
 3244                                        ),
 3245                                        &bracket_pair.start[..prefix_len],
 3246                                    ));
 3247
 3248                            if autoclose
 3249                                && bracket_pair.close
 3250                                && following_text_allows_autoclose
 3251                                && preceding_text_matches_prefix
 3252                            {
 3253                                let anchor = snapshot.anchor_before(selection.end);
 3254                                new_selections.push((selection.map(|_| anchor), text.len()));
 3255                                new_autoclose_regions.push((
 3256                                    anchor,
 3257                                    text.len(),
 3258                                    selection.id,
 3259                                    bracket_pair.clone(),
 3260                                ));
 3261                                edits.push((
 3262                                    selection.range(),
 3263                                    format!("{}{}", text, bracket_pair.end).into(),
 3264                                ));
 3265                                bracket_inserted = true;
 3266                                continue;
 3267                            }
 3268                        }
 3269
 3270                        if let Some(region) = autoclose_region {
 3271                            // If the selection is followed by an auto-inserted closing bracket,
 3272                            // then don't insert that closing bracket again; just move the selection
 3273                            // past the closing bracket.
 3274                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3275                                && text.as_ref() == region.pair.end.as_str();
 3276                            if should_skip {
 3277                                let anchor = snapshot.anchor_after(selection.end);
 3278                                new_selections
 3279                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3280                                continue;
 3281                            }
 3282                        }
 3283
 3284                        let always_treat_brackets_as_autoclosed = snapshot
 3285                            .settings_at(selection.start, cx)
 3286                            .always_treat_brackets_as_autoclosed;
 3287                        if always_treat_brackets_as_autoclosed
 3288                            && is_bracket_pair_end
 3289                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3290                        {
 3291                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3292                            // and the inserted text is a closing bracket and the selection is followed
 3293                            // by the closing bracket then move the selection past the closing bracket.
 3294                            let anchor = snapshot.anchor_after(selection.end);
 3295                            new_selections.push((selection.map(|_| anchor), text.len()));
 3296                            continue;
 3297                        }
 3298                    }
 3299                    // If an opening bracket is 1 character long and is typed while
 3300                    // text is selected, then surround that text with the bracket pair.
 3301                    else if auto_surround
 3302                        && bracket_pair.surround
 3303                        && is_bracket_pair_start
 3304                        && bracket_pair.start.chars().count() == 1
 3305                    {
 3306                        edits.push((selection.start..selection.start, text.clone()));
 3307                        edits.push((
 3308                            selection.end..selection.end,
 3309                            bracket_pair.end.as_str().into(),
 3310                        ));
 3311                        bracket_inserted = true;
 3312                        new_selections.push((
 3313                            Selection {
 3314                                id: selection.id,
 3315                                start: snapshot.anchor_after(selection.start),
 3316                                end: snapshot.anchor_before(selection.end),
 3317                                reversed: selection.reversed,
 3318                                goal: selection.goal,
 3319                            },
 3320                            0,
 3321                        ));
 3322                        continue;
 3323                    }
 3324                }
 3325            }
 3326
 3327            if self.auto_replace_emoji_shortcode
 3328                && selection.is_empty()
 3329                && text.as_ref().ends_with(':')
 3330            {
 3331                if let Some(possible_emoji_short_code) =
 3332                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3333                {
 3334                    if !possible_emoji_short_code.is_empty() {
 3335                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3336                            let emoji_shortcode_start = Point::new(
 3337                                selection.start.row,
 3338                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3339                            );
 3340
 3341                            // Remove shortcode from buffer
 3342                            edits.push((
 3343                                emoji_shortcode_start..selection.start,
 3344                                "".to_string().into(),
 3345                            ));
 3346                            new_selections.push((
 3347                                Selection {
 3348                                    id: selection.id,
 3349                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3350                                    end: snapshot.anchor_before(selection.start),
 3351                                    reversed: selection.reversed,
 3352                                    goal: selection.goal,
 3353                                },
 3354                                0,
 3355                            ));
 3356
 3357                            // Insert emoji
 3358                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3359                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3360                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3361
 3362                            continue;
 3363                        }
 3364                    }
 3365                }
 3366            }
 3367
 3368            // If not handling any auto-close operation, then just replace the selected
 3369            // text with the given input and move the selection to the end of the
 3370            // newly inserted text.
 3371            let anchor = snapshot.anchor_after(selection.end);
 3372            if !self.linked_edit_ranges.is_empty() {
 3373                let start_anchor = snapshot.anchor_before(selection.start);
 3374
 3375                let is_word_char = text.chars().next().map_or(true, |char| {
 3376                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3377                    classifier.is_word(char)
 3378                });
 3379
 3380                if is_word_char {
 3381                    if let Some(ranges) = self
 3382                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3383                    {
 3384                        for (buffer, edits) in ranges {
 3385                            linked_edits
 3386                                .entry(buffer.clone())
 3387                                .or_default()
 3388                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3389                        }
 3390                    }
 3391                }
 3392            }
 3393
 3394            new_selections.push((selection.map(|_| anchor), 0));
 3395            edits.push((selection.start..selection.end, text.clone()));
 3396        }
 3397
 3398        drop(snapshot);
 3399
 3400        self.transact(cx, |this, cx| {
 3401            this.buffer.update(cx, |buffer, cx| {
 3402                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3403            });
 3404            for (buffer, edits) in linked_edits {
 3405                buffer.update(cx, |buffer, cx| {
 3406                    let snapshot = buffer.snapshot();
 3407                    let edits = edits
 3408                        .into_iter()
 3409                        .map(|(range, text)| {
 3410                            use text::ToPoint as TP;
 3411                            let end_point = TP::to_point(&range.end, &snapshot);
 3412                            let start_point = TP::to_point(&range.start, &snapshot);
 3413                            (start_point..end_point, text)
 3414                        })
 3415                        .sorted_by_key(|(range, _)| range.start)
 3416                        .collect::<Vec<_>>();
 3417                    buffer.edit(edits, None, cx);
 3418                })
 3419            }
 3420            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3421            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3422            let snapshot = this.buffer.read(cx).read(cx);
 3423            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3424                .zip(new_selection_deltas)
 3425                .map(|(selection, delta)| Selection {
 3426                    id: selection.id,
 3427                    start: selection.start + delta,
 3428                    end: selection.end + delta,
 3429                    reversed: selection.reversed,
 3430                    goal: SelectionGoal::None,
 3431                })
 3432                .collect::<Vec<_>>();
 3433
 3434            let mut i = 0;
 3435            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3436                let position = position.to_offset(&snapshot) + delta;
 3437                let start = snapshot.anchor_before(position);
 3438                let end = snapshot.anchor_after(position);
 3439                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3440                    match existing_state.range.start.cmp(&start, &snapshot) {
 3441                        Ordering::Less => i += 1,
 3442                        Ordering::Greater => break,
 3443                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3444                            Ordering::Less => i += 1,
 3445                            Ordering::Equal => break,
 3446                            Ordering::Greater => break,
 3447                        },
 3448                    }
 3449                }
 3450                this.autoclose_regions.insert(
 3451                    i,
 3452                    AutocloseRegion {
 3453                        selection_id,
 3454                        range: start..end,
 3455                        pair,
 3456                    },
 3457                );
 3458            }
 3459
 3460            drop(snapshot);
 3461            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3462            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3463                s.select(new_selections)
 3464            });
 3465
 3466            if !bracket_inserted {
 3467                if let Some(on_type_format_task) =
 3468                    this.trigger_on_type_formatting(text.to_string(), cx)
 3469                {
 3470                    on_type_format_task.detach_and_log_err(cx);
 3471                }
 3472            }
 3473
 3474            let editor_settings = EditorSettings::get_global(cx);
 3475            if bracket_inserted
 3476                && (editor_settings.auto_signature_help
 3477                    || editor_settings.show_signature_help_after_edits)
 3478            {
 3479                this.show_signature_help(&ShowSignatureHelp, cx);
 3480            }
 3481
 3482            let trigger_in_words = !had_active_inline_completion;
 3483            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3484            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3485            this.refresh_inline_completion(true, false, cx);
 3486        });
 3487    }
 3488
 3489    fn find_possible_emoji_shortcode_at_position(
 3490        snapshot: &MultiBufferSnapshot,
 3491        position: Point,
 3492    ) -> Option<String> {
 3493        let mut chars = Vec::new();
 3494        let mut found_colon = false;
 3495        for char in snapshot.reversed_chars_at(position).take(100) {
 3496            // Found a possible emoji shortcode in the middle of the buffer
 3497            if found_colon {
 3498                if char.is_whitespace() {
 3499                    chars.reverse();
 3500                    return Some(chars.iter().collect());
 3501                }
 3502                // If the previous character is not a whitespace, we are in the middle of a word
 3503                // and we only want to complete the shortcode if the word is made up of other emojis
 3504                let mut containing_word = String::new();
 3505                for ch in snapshot
 3506                    .reversed_chars_at(position)
 3507                    .skip(chars.len() + 1)
 3508                    .take(100)
 3509                {
 3510                    if ch.is_whitespace() {
 3511                        break;
 3512                    }
 3513                    containing_word.push(ch);
 3514                }
 3515                let containing_word = containing_word.chars().rev().collect::<String>();
 3516                if util::word_consists_of_emojis(containing_word.as_str()) {
 3517                    chars.reverse();
 3518                    return Some(chars.iter().collect());
 3519                }
 3520            }
 3521
 3522            if char.is_whitespace() || !char.is_ascii() {
 3523                return None;
 3524            }
 3525            if char == ':' {
 3526                found_colon = true;
 3527            } else {
 3528                chars.push(char);
 3529            }
 3530        }
 3531        // Found a possible emoji shortcode at the beginning of the buffer
 3532        chars.reverse();
 3533        Some(chars.iter().collect())
 3534    }
 3535
 3536    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3537        self.transact(cx, |this, cx| {
 3538            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3539                let selections = this.selections.all::<usize>(cx);
 3540                let multi_buffer = this.buffer.read(cx);
 3541                let buffer = multi_buffer.snapshot(cx);
 3542                selections
 3543                    .iter()
 3544                    .map(|selection| {
 3545                        let start_point = selection.start.to_point(&buffer);
 3546                        let mut indent =
 3547                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3548                        indent.len = cmp::min(indent.len, start_point.column);
 3549                        let start = selection.start;
 3550                        let end = selection.end;
 3551                        let selection_is_empty = start == end;
 3552                        let language_scope = buffer.language_scope_at(start);
 3553                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3554                            &language_scope
 3555                        {
 3556                            let leading_whitespace_len = buffer
 3557                                .reversed_chars_at(start)
 3558                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3559                                .map(|c| c.len_utf8())
 3560                                .sum::<usize>();
 3561
 3562                            let trailing_whitespace_len = buffer
 3563                                .chars_at(end)
 3564                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3565                                .map(|c| c.len_utf8())
 3566                                .sum::<usize>();
 3567
 3568                            let insert_extra_newline =
 3569                                language.brackets().any(|(pair, enabled)| {
 3570                                    let pair_start = pair.start.trim_end();
 3571                                    let pair_end = pair.end.trim_start();
 3572
 3573                                    enabled
 3574                                        && pair.newline
 3575                                        && buffer.contains_str_at(
 3576                                            end + trailing_whitespace_len,
 3577                                            pair_end,
 3578                                        )
 3579                                        && buffer.contains_str_at(
 3580                                            (start - leading_whitespace_len)
 3581                                                .saturating_sub(pair_start.len()),
 3582                                            pair_start,
 3583                                        )
 3584                                });
 3585
 3586                            // Comment extension on newline is allowed only for cursor selections
 3587                            let comment_delimiter = maybe!({
 3588                                if !selection_is_empty {
 3589                                    return None;
 3590                                }
 3591
 3592                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3593                                    return None;
 3594                                }
 3595
 3596                                let delimiters = language.line_comment_prefixes();
 3597                                let max_len_of_delimiter =
 3598                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3599                                let (snapshot, range) =
 3600                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3601
 3602                                let mut index_of_first_non_whitespace = 0;
 3603                                let comment_candidate = snapshot
 3604                                    .chars_for_range(range)
 3605                                    .skip_while(|c| {
 3606                                        let should_skip = c.is_whitespace();
 3607                                        if should_skip {
 3608                                            index_of_first_non_whitespace += 1;
 3609                                        }
 3610                                        should_skip
 3611                                    })
 3612                                    .take(max_len_of_delimiter)
 3613                                    .collect::<String>();
 3614                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3615                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3616                                })?;
 3617                                let cursor_is_placed_after_comment_marker =
 3618                                    index_of_first_non_whitespace + comment_prefix.len()
 3619                                        <= start_point.column as usize;
 3620                                if cursor_is_placed_after_comment_marker {
 3621                                    Some(comment_prefix.clone())
 3622                                } else {
 3623                                    None
 3624                                }
 3625                            });
 3626                            (comment_delimiter, insert_extra_newline)
 3627                        } else {
 3628                            (None, false)
 3629                        };
 3630
 3631                        let capacity_for_delimiter = comment_delimiter
 3632                            .as_deref()
 3633                            .map(str::len)
 3634                            .unwrap_or_default();
 3635                        let mut new_text =
 3636                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3637                        new_text.push('\n');
 3638                        new_text.extend(indent.chars());
 3639                        if let Some(delimiter) = &comment_delimiter {
 3640                            new_text.push_str(delimiter);
 3641                        }
 3642                        if insert_extra_newline {
 3643                            new_text = new_text.repeat(2);
 3644                        }
 3645
 3646                        let anchor = buffer.anchor_after(end);
 3647                        let new_selection = selection.map(|_| anchor);
 3648                        (
 3649                            (start..end, new_text),
 3650                            (insert_extra_newline, new_selection),
 3651                        )
 3652                    })
 3653                    .unzip()
 3654            };
 3655
 3656            this.edit_with_autoindent(edits, cx);
 3657            let buffer = this.buffer.read(cx).snapshot(cx);
 3658            let new_selections = selection_fixup_info
 3659                .into_iter()
 3660                .map(|(extra_newline_inserted, new_selection)| {
 3661                    let mut cursor = new_selection.end.to_point(&buffer);
 3662                    if extra_newline_inserted {
 3663                        cursor.row -= 1;
 3664                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3665                    }
 3666                    new_selection.map(|_| cursor)
 3667                })
 3668                .collect();
 3669
 3670            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3671            this.refresh_inline_completion(true, false, cx);
 3672        });
 3673    }
 3674
 3675    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3676        let buffer = self.buffer.read(cx);
 3677        let snapshot = buffer.snapshot(cx);
 3678
 3679        let mut edits = Vec::new();
 3680        let mut rows = Vec::new();
 3681
 3682        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3683            let cursor = selection.head();
 3684            let row = cursor.row;
 3685
 3686            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3687
 3688            let newline = "\n".to_string();
 3689            edits.push((start_of_line..start_of_line, newline));
 3690
 3691            rows.push(row + rows_inserted as u32);
 3692        }
 3693
 3694        self.transact(cx, |editor, cx| {
 3695            editor.edit(edits, cx);
 3696
 3697            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3698                let mut index = 0;
 3699                s.move_cursors_with(|map, _, _| {
 3700                    let row = rows[index];
 3701                    index += 1;
 3702
 3703                    let point = Point::new(row, 0);
 3704                    let boundary = map.next_line_boundary(point).1;
 3705                    let clipped = map.clip_point(boundary, Bias::Left);
 3706
 3707                    (clipped, SelectionGoal::None)
 3708                });
 3709            });
 3710
 3711            let mut indent_edits = Vec::new();
 3712            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3713            for row in rows {
 3714                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3715                for (row, indent) in indents {
 3716                    if indent.len == 0 {
 3717                        continue;
 3718                    }
 3719
 3720                    let text = match indent.kind {
 3721                        IndentKind::Space => " ".repeat(indent.len as usize),
 3722                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3723                    };
 3724                    let point = Point::new(row.0, 0);
 3725                    indent_edits.push((point..point, text));
 3726                }
 3727            }
 3728            editor.edit(indent_edits, cx);
 3729        });
 3730    }
 3731
 3732    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3733        let buffer = self.buffer.read(cx);
 3734        let snapshot = buffer.snapshot(cx);
 3735
 3736        let mut edits = Vec::new();
 3737        let mut rows = Vec::new();
 3738        let mut rows_inserted = 0;
 3739
 3740        for selection in self.selections.all_adjusted(cx) {
 3741            let cursor = selection.head();
 3742            let row = cursor.row;
 3743
 3744            let point = Point::new(row + 1, 0);
 3745            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3746
 3747            let newline = "\n".to_string();
 3748            edits.push((start_of_line..start_of_line, newline));
 3749
 3750            rows_inserted += 1;
 3751            rows.push(row + rows_inserted);
 3752        }
 3753
 3754        self.transact(cx, |editor, cx| {
 3755            editor.edit(edits, cx);
 3756
 3757            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3758                let mut index = 0;
 3759                s.move_cursors_with(|map, _, _| {
 3760                    let row = rows[index];
 3761                    index += 1;
 3762
 3763                    let point = Point::new(row, 0);
 3764                    let boundary = map.next_line_boundary(point).1;
 3765                    let clipped = map.clip_point(boundary, Bias::Left);
 3766
 3767                    (clipped, SelectionGoal::None)
 3768                });
 3769            });
 3770
 3771            let mut indent_edits = Vec::new();
 3772            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3773            for row in rows {
 3774                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3775                for (row, indent) in indents {
 3776                    if indent.len == 0 {
 3777                        continue;
 3778                    }
 3779
 3780                    let text = match indent.kind {
 3781                        IndentKind::Space => " ".repeat(indent.len as usize),
 3782                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3783                    };
 3784                    let point = Point::new(row.0, 0);
 3785                    indent_edits.push((point..point, text));
 3786                }
 3787            }
 3788            editor.edit(indent_edits, cx);
 3789        });
 3790    }
 3791
 3792    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3793        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3794            original_indent_columns: Vec::new(),
 3795        });
 3796        self.insert_with_autoindent_mode(text, autoindent, cx);
 3797    }
 3798
 3799    fn insert_with_autoindent_mode(
 3800        &mut self,
 3801        text: &str,
 3802        autoindent_mode: Option<AutoindentMode>,
 3803        cx: &mut ViewContext<Self>,
 3804    ) {
 3805        if self.read_only(cx) {
 3806            return;
 3807        }
 3808
 3809        let text: Arc<str> = text.into();
 3810        self.transact(cx, |this, cx| {
 3811            let old_selections = this.selections.all_adjusted(cx);
 3812            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3813                let anchors = {
 3814                    let snapshot = buffer.read(cx);
 3815                    old_selections
 3816                        .iter()
 3817                        .map(|s| {
 3818                            let anchor = snapshot.anchor_after(s.head());
 3819                            s.map(|_| anchor)
 3820                        })
 3821                        .collect::<Vec<_>>()
 3822                };
 3823                buffer.edit(
 3824                    old_selections
 3825                        .iter()
 3826                        .map(|s| (s.start..s.end, text.clone())),
 3827                    autoindent_mode,
 3828                    cx,
 3829                );
 3830                anchors
 3831            });
 3832
 3833            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3834                s.select_anchors(selection_anchors);
 3835            })
 3836        });
 3837    }
 3838
 3839    fn trigger_completion_on_input(
 3840        &mut self,
 3841        text: &str,
 3842        trigger_in_words: bool,
 3843        cx: &mut ViewContext<Self>,
 3844    ) {
 3845        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3846            self.show_completions(
 3847                &ShowCompletions {
 3848                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3849                },
 3850                cx,
 3851            );
 3852        } else {
 3853            self.hide_context_menu(cx);
 3854        }
 3855    }
 3856
 3857    fn is_completion_trigger(
 3858        &self,
 3859        text: &str,
 3860        trigger_in_words: bool,
 3861        cx: &mut ViewContext<Self>,
 3862    ) -> bool {
 3863        let position = self.selections.newest_anchor().head();
 3864        let multibuffer = self.buffer.read(cx);
 3865        let Some(buffer) = position
 3866            .buffer_id
 3867            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3868        else {
 3869            return false;
 3870        };
 3871
 3872        if let Some(completion_provider) = &self.completion_provider {
 3873            completion_provider.is_completion_trigger(
 3874                &buffer,
 3875                position.text_anchor,
 3876                text,
 3877                trigger_in_words,
 3878                cx,
 3879            )
 3880        } else {
 3881            false
 3882        }
 3883    }
 3884
 3885    /// If any empty selections is touching the start of its innermost containing autoclose
 3886    /// region, expand it to select the brackets.
 3887    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3888        let selections = self.selections.all::<usize>(cx);
 3889        let buffer = self.buffer.read(cx).read(cx);
 3890        let new_selections = self
 3891            .selections_with_autoclose_regions(selections, &buffer)
 3892            .map(|(mut selection, region)| {
 3893                if !selection.is_empty() {
 3894                    return selection;
 3895                }
 3896
 3897                if let Some(region) = region {
 3898                    let mut range = region.range.to_offset(&buffer);
 3899                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3900                        range.start -= region.pair.start.len();
 3901                        if buffer.contains_str_at(range.start, &region.pair.start)
 3902                            && buffer.contains_str_at(range.end, &region.pair.end)
 3903                        {
 3904                            range.end += region.pair.end.len();
 3905                            selection.start = range.start;
 3906                            selection.end = range.end;
 3907
 3908                            return selection;
 3909                        }
 3910                    }
 3911                }
 3912
 3913                let always_treat_brackets_as_autoclosed = buffer
 3914                    .settings_at(selection.start, cx)
 3915                    .always_treat_brackets_as_autoclosed;
 3916
 3917                if !always_treat_brackets_as_autoclosed {
 3918                    return selection;
 3919                }
 3920
 3921                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3922                    for (pair, enabled) in scope.brackets() {
 3923                        if !enabled || !pair.close {
 3924                            continue;
 3925                        }
 3926
 3927                        if buffer.contains_str_at(selection.start, &pair.end) {
 3928                            let pair_start_len = pair.start.len();
 3929                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3930                            {
 3931                                selection.start -= pair_start_len;
 3932                                selection.end += pair.end.len();
 3933
 3934                                return selection;
 3935                            }
 3936                        }
 3937                    }
 3938                }
 3939
 3940                selection
 3941            })
 3942            .collect();
 3943
 3944        drop(buffer);
 3945        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3946    }
 3947
 3948    /// Iterate the given selections, and for each one, find the smallest surrounding
 3949    /// autoclose region. This uses the ordering of the selections and the autoclose
 3950    /// regions to avoid repeated comparisons.
 3951    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3952        &'a self,
 3953        selections: impl IntoIterator<Item = Selection<D>>,
 3954        buffer: &'a MultiBufferSnapshot,
 3955    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3956        let mut i = 0;
 3957        let mut regions = self.autoclose_regions.as_slice();
 3958        selections.into_iter().map(move |selection| {
 3959            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3960
 3961            let mut enclosing = None;
 3962            while let Some(pair_state) = regions.get(i) {
 3963                if pair_state.range.end.to_offset(buffer) < range.start {
 3964                    regions = &regions[i + 1..];
 3965                    i = 0;
 3966                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3967                    break;
 3968                } else {
 3969                    if pair_state.selection_id == selection.id {
 3970                        enclosing = Some(pair_state);
 3971                    }
 3972                    i += 1;
 3973                }
 3974            }
 3975
 3976            (selection.clone(), enclosing)
 3977        })
 3978    }
 3979
 3980    /// Remove any autoclose regions that no longer contain their selection.
 3981    fn invalidate_autoclose_regions(
 3982        &mut self,
 3983        mut selections: &[Selection<Anchor>],
 3984        buffer: &MultiBufferSnapshot,
 3985    ) {
 3986        self.autoclose_regions.retain(|state| {
 3987            let mut i = 0;
 3988            while let Some(selection) = selections.get(i) {
 3989                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3990                    selections = &selections[1..];
 3991                    continue;
 3992                }
 3993                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3994                    break;
 3995                }
 3996                if selection.id == state.selection_id {
 3997                    return true;
 3998                } else {
 3999                    i += 1;
 4000                }
 4001            }
 4002            false
 4003        });
 4004    }
 4005
 4006    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4007        let offset = position.to_offset(buffer);
 4008        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4009        if offset > word_range.start && kind == Some(CharKind::Word) {
 4010            Some(
 4011                buffer
 4012                    .text_for_range(word_range.start..offset)
 4013                    .collect::<String>(),
 4014            )
 4015        } else {
 4016            None
 4017        }
 4018    }
 4019
 4020    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4021        self.refresh_inlay_hints(
 4022            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4023            cx,
 4024        );
 4025    }
 4026
 4027    pub fn inlay_hints_enabled(&self) -> bool {
 4028        self.inlay_hint_cache.enabled
 4029    }
 4030
 4031    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4032        if self.project.is_none() || self.mode != EditorMode::Full {
 4033            return;
 4034        }
 4035
 4036        let reason_description = reason.description();
 4037        let ignore_debounce = matches!(
 4038            reason,
 4039            InlayHintRefreshReason::SettingsChange(_)
 4040                | InlayHintRefreshReason::Toggle(_)
 4041                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4042        );
 4043        let (invalidate_cache, required_languages) = match reason {
 4044            InlayHintRefreshReason::Toggle(enabled) => {
 4045                self.inlay_hint_cache.enabled = enabled;
 4046                if enabled {
 4047                    (InvalidationStrategy::RefreshRequested, None)
 4048                } else {
 4049                    self.inlay_hint_cache.clear();
 4050                    self.splice_inlays(
 4051                        self.visible_inlay_hints(cx)
 4052                            .iter()
 4053                            .map(|inlay| inlay.id)
 4054                            .collect(),
 4055                        Vec::new(),
 4056                        cx,
 4057                    );
 4058                    return;
 4059                }
 4060            }
 4061            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4062                match self.inlay_hint_cache.update_settings(
 4063                    &self.buffer,
 4064                    new_settings,
 4065                    self.visible_inlay_hints(cx),
 4066                    cx,
 4067                ) {
 4068                    ControlFlow::Break(Some(InlaySplice {
 4069                        to_remove,
 4070                        to_insert,
 4071                    })) => {
 4072                        self.splice_inlays(to_remove, to_insert, cx);
 4073                        return;
 4074                    }
 4075                    ControlFlow::Break(None) => return,
 4076                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4077                }
 4078            }
 4079            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4080                if let Some(InlaySplice {
 4081                    to_remove,
 4082                    to_insert,
 4083                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4084                {
 4085                    self.splice_inlays(to_remove, to_insert, cx);
 4086                }
 4087                return;
 4088            }
 4089            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4090            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4091                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4092            }
 4093            InlayHintRefreshReason::RefreshRequested => {
 4094                (InvalidationStrategy::RefreshRequested, None)
 4095            }
 4096        };
 4097
 4098        if let Some(InlaySplice {
 4099            to_remove,
 4100            to_insert,
 4101        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4102            reason_description,
 4103            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4104            invalidate_cache,
 4105            ignore_debounce,
 4106            cx,
 4107        ) {
 4108            self.splice_inlays(to_remove, to_insert, cx);
 4109        }
 4110    }
 4111
 4112    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4113        self.display_map
 4114            .read(cx)
 4115            .current_inlays()
 4116            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4117            .cloned()
 4118            .collect()
 4119    }
 4120
 4121    pub fn excerpts_for_inlay_hints_query(
 4122        &self,
 4123        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4124        cx: &mut ViewContext<Editor>,
 4125    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4126        let Some(project) = self.project.as_ref() else {
 4127            return HashMap::default();
 4128        };
 4129        let project = project.read(cx);
 4130        let multi_buffer = self.buffer().read(cx);
 4131        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4132        let multi_buffer_visible_start = self
 4133            .scroll_manager
 4134            .anchor()
 4135            .anchor
 4136            .to_point(&multi_buffer_snapshot);
 4137        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4138            multi_buffer_visible_start
 4139                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4140            Bias::Left,
 4141        );
 4142        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4143        multi_buffer
 4144            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4145            .into_iter()
 4146            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4147            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4148                let buffer = buffer_handle.read(cx);
 4149                let buffer_file = project::File::from_dyn(buffer.file())?;
 4150                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4151                let worktree_entry = buffer_worktree
 4152                    .read(cx)
 4153                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4154                if worktree_entry.is_ignored {
 4155                    return None;
 4156                }
 4157
 4158                let language = buffer.language()?;
 4159                if let Some(restrict_to_languages) = restrict_to_languages {
 4160                    if !restrict_to_languages.contains(language) {
 4161                        return None;
 4162                    }
 4163                }
 4164                Some((
 4165                    excerpt_id,
 4166                    (
 4167                        buffer_handle,
 4168                        buffer.version().clone(),
 4169                        excerpt_visible_range,
 4170                    ),
 4171                ))
 4172            })
 4173            .collect()
 4174    }
 4175
 4176    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4177        TextLayoutDetails {
 4178            text_system: cx.text_system().clone(),
 4179            editor_style: self.style.clone().unwrap(),
 4180            rem_size: cx.rem_size(),
 4181            scroll_anchor: self.scroll_manager.anchor(),
 4182            visible_rows: self.visible_line_count(),
 4183            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4184        }
 4185    }
 4186
 4187    fn splice_inlays(
 4188        &self,
 4189        to_remove: Vec<InlayId>,
 4190        to_insert: Vec<Inlay>,
 4191        cx: &mut ViewContext<Self>,
 4192    ) {
 4193        self.display_map.update(cx, |display_map, cx| {
 4194            display_map.splice_inlays(to_remove, to_insert, cx);
 4195        });
 4196        cx.notify();
 4197    }
 4198
 4199    fn trigger_on_type_formatting(
 4200        &self,
 4201        input: String,
 4202        cx: &mut ViewContext<Self>,
 4203    ) -> Option<Task<Result<()>>> {
 4204        if input.len() != 1 {
 4205            return None;
 4206        }
 4207
 4208        let project = self.project.as_ref()?;
 4209        let position = self.selections.newest_anchor().head();
 4210        let (buffer, buffer_position) = self
 4211            .buffer
 4212            .read(cx)
 4213            .text_anchor_for_position(position, cx)?;
 4214
 4215        let settings = language_settings::language_settings(
 4216            buffer.read(cx).language_at(buffer_position).as_ref(),
 4217            buffer.read(cx).file(),
 4218            cx,
 4219        );
 4220        if !settings.use_on_type_format {
 4221            return None;
 4222        }
 4223
 4224        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4225        // hence we do LSP request & edit on host side only — add formats to host's history.
 4226        let push_to_lsp_host_history = true;
 4227        // If this is not the host, append its history with new edits.
 4228        let push_to_client_history = project.read(cx).is_via_collab();
 4229
 4230        let on_type_formatting = project.update(cx, |project, cx| {
 4231            project.on_type_format(
 4232                buffer.clone(),
 4233                buffer_position,
 4234                input,
 4235                push_to_lsp_host_history,
 4236                cx,
 4237            )
 4238        });
 4239        Some(cx.spawn(|editor, mut cx| async move {
 4240            if let Some(transaction) = on_type_formatting.await? {
 4241                if push_to_client_history {
 4242                    buffer
 4243                        .update(&mut cx, |buffer, _| {
 4244                            buffer.push_transaction(transaction, Instant::now());
 4245                        })
 4246                        .ok();
 4247                }
 4248                editor.update(&mut cx, |editor, cx| {
 4249                    editor.refresh_document_highlights(cx);
 4250                })?;
 4251            }
 4252            Ok(())
 4253        }))
 4254    }
 4255
 4256    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4257        if self.pending_rename.is_some() {
 4258            return;
 4259        }
 4260
 4261        let Some(provider) = self.completion_provider.as_ref() else {
 4262            return;
 4263        };
 4264
 4265        let position = self.selections.newest_anchor().head();
 4266        let (buffer, buffer_position) =
 4267            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4268                output
 4269            } else {
 4270                return;
 4271            };
 4272
 4273        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4274        let is_followup_invoke = {
 4275            let context_menu_state = self.context_menu.read();
 4276            matches!(
 4277                context_menu_state.deref(),
 4278                Some(ContextMenu::Completions(_))
 4279            )
 4280        };
 4281        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4282            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4283            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4284                CompletionTriggerKind::TRIGGER_CHARACTER
 4285            }
 4286
 4287            _ => CompletionTriggerKind::INVOKED,
 4288        };
 4289        let completion_context = CompletionContext {
 4290            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4291                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4292                    Some(String::from(trigger))
 4293                } else {
 4294                    None
 4295                }
 4296            }),
 4297            trigger_kind,
 4298        };
 4299        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4300        let sort_completions = provider.sort_completions();
 4301
 4302        let id = post_inc(&mut self.next_completion_id);
 4303        let task = cx.spawn(|this, mut cx| {
 4304            async move {
 4305                this.update(&mut cx, |this, _| {
 4306                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4307                })?;
 4308                let completions = completions.await.log_err();
 4309                let menu = if let Some(completions) = completions {
 4310                    let mut menu = CompletionsMenu {
 4311                        id,
 4312                        sort_completions,
 4313                        initial_position: position,
 4314                        match_candidates: completions
 4315                            .iter()
 4316                            .enumerate()
 4317                            .map(|(id, completion)| {
 4318                                StringMatchCandidate::new(
 4319                                    id,
 4320                                    completion.label.text[completion.label.filter_range.clone()]
 4321                                        .into(),
 4322                                )
 4323                            })
 4324                            .collect(),
 4325                        buffer: buffer.clone(),
 4326                        completions: Arc::new(RwLock::new(completions.into())),
 4327                        matches: Vec::new().into(),
 4328                        selected_item: 0,
 4329                        scroll_handle: UniformListScrollHandle::new(),
 4330                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4331                            DebouncedDelay::new(),
 4332                        )),
 4333                    };
 4334                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4335                        .await;
 4336
 4337                    if menu.matches.is_empty() {
 4338                        None
 4339                    } else {
 4340                        this.update(&mut cx, |editor, cx| {
 4341                            let completions = menu.completions.clone();
 4342                            let matches = menu.matches.clone();
 4343
 4344                            let delay_ms = EditorSettings::get_global(cx)
 4345                                .completion_documentation_secondary_query_debounce;
 4346                            let delay = Duration::from_millis(delay_ms);
 4347                            editor
 4348                                .completion_documentation_pre_resolve_debounce
 4349                                .fire_new(delay, cx, |editor, cx| {
 4350                                    CompletionsMenu::pre_resolve_completion_documentation(
 4351                                        buffer,
 4352                                        completions,
 4353                                        matches,
 4354                                        editor,
 4355                                        cx,
 4356                                    )
 4357                                });
 4358                        })
 4359                        .ok();
 4360                        Some(menu)
 4361                    }
 4362                } else {
 4363                    None
 4364                };
 4365
 4366                this.update(&mut cx, |this, cx| {
 4367                    let mut context_menu = this.context_menu.write();
 4368                    match context_menu.as_ref() {
 4369                        None => {}
 4370
 4371                        Some(ContextMenu::Completions(prev_menu)) => {
 4372                            if prev_menu.id > id {
 4373                                return;
 4374                            }
 4375                        }
 4376
 4377                        _ => return,
 4378                    }
 4379
 4380                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4381                        let menu = menu.unwrap();
 4382                        *context_menu = Some(ContextMenu::Completions(menu));
 4383                        drop(context_menu);
 4384                        this.discard_inline_completion(false, cx);
 4385                        cx.notify();
 4386                    } else if this.completion_tasks.len() <= 1 {
 4387                        // If there are no more completion tasks and the last menu was
 4388                        // empty, we should hide it. If it was already hidden, we should
 4389                        // also show the copilot completion when available.
 4390                        drop(context_menu);
 4391                        if this.hide_context_menu(cx).is_none() {
 4392                            this.update_visible_inline_completion(cx);
 4393                        }
 4394                    }
 4395                })?;
 4396
 4397                Ok::<_, anyhow::Error>(())
 4398            }
 4399            .log_err()
 4400        });
 4401
 4402        self.completion_tasks.push((id, task));
 4403    }
 4404
 4405    pub fn confirm_completion(
 4406        &mut self,
 4407        action: &ConfirmCompletion,
 4408        cx: &mut ViewContext<Self>,
 4409    ) -> Option<Task<Result<()>>> {
 4410        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4411    }
 4412
 4413    pub fn compose_completion(
 4414        &mut self,
 4415        action: &ComposeCompletion,
 4416        cx: &mut ViewContext<Self>,
 4417    ) -> Option<Task<Result<()>>> {
 4418        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4419    }
 4420
 4421    fn do_completion(
 4422        &mut self,
 4423        item_ix: Option<usize>,
 4424        intent: CompletionIntent,
 4425        cx: &mut ViewContext<Self>,
 4426    ) -> Option<Task<anyhow::Result<()>>> {
 4427        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4428            menu
 4429        } else {
 4430            return None;
 4431        };
 4432
 4433        let mut resolve_task_store = completions_menu
 4434            .selected_completion_documentation_resolve_debounce
 4435            .lock();
 4436        let selected_completion_resolve = resolve_task_store.start_now();
 4437        let menu_pre_resolve = self
 4438            .completion_documentation_pre_resolve_debounce
 4439            .start_now();
 4440        drop(resolve_task_store);
 4441
 4442        Some(cx.spawn(|editor, mut cx| async move {
 4443            match (selected_completion_resolve, menu_pre_resolve) {
 4444                (None, None) => {}
 4445                (Some(resolve), None) | (None, Some(resolve)) => resolve.await,
 4446                (Some(resolve_1), Some(resolve_2)) => {
 4447                    futures::join!(resolve_1, resolve_2);
 4448                }
 4449            }
 4450            if let Some(apply_edits_task) = editor.update(&mut cx, |editor, cx| {
 4451                editor.apply_resolved_completion(completions_menu, item_ix, intent, cx)
 4452            })? {
 4453                apply_edits_task.await?;
 4454            }
 4455            Ok(())
 4456        }))
 4457    }
 4458
 4459    fn apply_resolved_completion(
 4460        &mut self,
 4461        completions_menu: CompletionsMenu,
 4462        item_ix: Option<usize>,
 4463        intent: CompletionIntent,
 4464        cx: &mut ViewContext<'_, Editor>,
 4465    ) -> Option<Task<anyhow::Result<Option<language::Transaction>>>> {
 4466        use language::ToOffset as _;
 4467
 4468        let mat = completions_menu
 4469            .matches
 4470            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4471        let buffer_handle = completions_menu.buffer;
 4472        let completions = completions_menu.completions.read();
 4473        let completion = completions.get(mat.candidate_id)?;
 4474        cx.stop_propagation();
 4475
 4476        let snippet;
 4477        let text;
 4478
 4479        if completion.is_snippet() {
 4480            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4481            text = snippet.as_ref().unwrap().text.clone();
 4482        } else {
 4483            snippet = None;
 4484            text = completion.new_text.clone();
 4485        };
 4486        let selections = self.selections.all::<usize>(cx);
 4487        let buffer = buffer_handle.read(cx);
 4488        let old_range = completion.old_range.to_offset(buffer);
 4489        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4490
 4491        let newest_selection = self.selections.newest_anchor();
 4492        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4493            return None;
 4494        }
 4495
 4496        let lookbehind = newest_selection
 4497            .start
 4498            .text_anchor
 4499            .to_offset(buffer)
 4500            .saturating_sub(old_range.start);
 4501        let lookahead = old_range
 4502            .end
 4503            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4504        let mut common_prefix_len = old_text
 4505            .bytes()
 4506            .zip(text.bytes())
 4507            .take_while(|(a, b)| a == b)
 4508            .count();
 4509
 4510        let snapshot = self.buffer.read(cx).snapshot(cx);
 4511        let mut range_to_replace: Option<Range<isize>> = None;
 4512        let mut ranges = Vec::new();
 4513        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4514        for selection in &selections {
 4515            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4516                let start = selection.start.saturating_sub(lookbehind);
 4517                let end = selection.end + lookahead;
 4518                if selection.id == newest_selection.id {
 4519                    range_to_replace = Some(
 4520                        ((start + common_prefix_len) as isize - selection.start as isize)
 4521                            ..(end as isize - selection.start as isize),
 4522                    );
 4523                }
 4524                ranges.push(start + common_prefix_len..end);
 4525            } else {
 4526                common_prefix_len = 0;
 4527                ranges.clear();
 4528                ranges.extend(selections.iter().map(|s| {
 4529                    if s.id == newest_selection.id {
 4530                        range_to_replace = Some(
 4531                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4532                                - selection.start as isize
 4533                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4534                                    - selection.start as isize,
 4535                        );
 4536                        old_range.clone()
 4537                    } else {
 4538                        s.start..s.end
 4539                    }
 4540                }));
 4541                break;
 4542            }
 4543            if !self.linked_edit_ranges.is_empty() {
 4544                let start_anchor = snapshot.anchor_before(selection.head());
 4545                let end_anchor = snapshot.anchor_after(selection.tail());
 4546                if let Some(ranges) = self
 4547                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4548                {
 4549                    for (buffer, edits) in ranges {
 4550                        linked_edits.entry(buffer.clone()).or_default().extend(
 4551                            edits
 4552                                .into_iter()
 4553                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4554                        );
 4555                    }
 4556                }
 4557            }
 4558        }
 4559        let text = &text[common_prefix_len..];
 4560
 4561        cx.emit(EditorEvent::InputHandled {
 4562            utf16_range_to_replace: range_to_replace,
 4563            text: text.into(),
 4564        });
 4565
 4566        self.transact(cx, |this, cx| {
 4567            if let Some(mut snippet) = snippet {
 4568                snippet.text = text.to_string();
 4569                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4570                    tabstop.start -= common_prefix_len as isize;
 4571                    tabstop.end -= common_prefix_len as isize;
 4572                }
 4573
 4574                this.insert_snippet(&ranges, snippet, cx).log_err();
 4575            } else {
 4576                this.buffer.update(cx, |buffer, cx| {
 4577                    buffer.edit(
 4578                        ranges.iter().map(|range| (range.clone(), text)),
 4579                        this.autoindent_mode.clone(),
 4580                        cx,
 4581                    );
 4582                });
 4583            }
 4584            for (buffer, edits) in linked_edits {
 4585                buffer.update(cx, |buffer, cx| {
 4586                    let snapshot = buffer.snapshot();
 4587                    let edits = edits
 4588                        .into_iter()
 4589                        .map(|(range, text)| {
 4590                            use text::ToPoint as TP;
 4591                            let end_point = TP::to_point(&range.end, &snapshot);
 4592                            let start_point = TP::to_point(&range.start, &snapshot);
 4593                            (start_point..end_point, text)
 4594                        })
 4595                        .sorted_by_key(|(range, _)| range.start)
 4596                        .collect::<Vec<_>>();
 4597                    buffer.edit(edits, None, cx);
 4598                })
 4599            }
 4600
 4601            this.refresh_inline_completion(true, false, cx);
 4602        });
 4603
 4604        let show_new_completions_on_confirm = completion
 4605            .confirm
 4606            .as_ref()
 4607            .map_or(false, |confirm| confirm(intent, cx));
 4608        if show_new_completions_on_confirm {
 4609            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4610        }
 4611
 4612        let provider = self.completion_provider.as_ref()?;
 4613        let apply_edits = provider.apply_additional_edits_for_completion(
 4614            buffer_handle,
 4615            completion.clone(),
 4616            true,
 4617            cx,
 4618        );
 4619
 4620        let editor_settings = EditorSettings::get_global(cx);
 4621        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4622            // After the code completion is finished, users often want to know what signatures are needed.
 4623            // so we should automatically call signature_help
 4624            self.show_signature_help(&ShowSignatureHelp, cx);
 4625        }
 4626        Some(apply_edits)
 4627    }
 4628
 4629    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4630        let mut context_menu = self.context_menu.write();
 4631        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4632            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4633                // Toggle if we're selecting the same one
 4634                *context_menu = None;
 4635                cx.notify();
 4636                return;
 4637            } else {
 4638                // Otherwise, clear it and start a new one
 4639                *context_menu = None;
 4640                cx.notify();
 4641            }
 4642        }
 4643        drop(context_menu);
 4644        let snapshot = self.snapshot(cx);
 4645        let deployed_from_indicator = action.deployed_from_indicator;
 4646        let mut task = self.code_actions_task.take();
 4647        let action = action.clone();
 4648        cx.spawn(|editor, mut cx| async move {
 4649            while let Some(prev_task) = task {
 4650                prev_task.await.log_err();
 4651                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4652            }
 4653
 4654            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4655                if editor.focus_handle.is_focused(cx) {
 4656                    let multibuffer_point = action
 4657                        .deployed_from_indicator
 4658                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4659                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4660                    let (buffer, buffer_row) = snapshot
 4661                        .buffer_snapshot
 4662                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4663                        .and_then(|(buffer_snapshot, range)| {
 4664                            editor
 4665                                .buffer
 4666                                .read(cx)
 4667                                .buffer(buffer_snapshot.remote_id())
 4668                                .map(|buffer| (buffer, range.start.row))
 4669                        })?;
 4670                    let (_, code_actions) = editor
 4671                        .available_code_actions
 4672                        .clone()
 4673                        .and_then(|(location, code_actions)| {
 4674                            let snapshot = location.buffer.read(cx).snapshot();
 4675                            let point_range = location.range.to_point(&snapshot);
 4676                            let point_range = point_range.start.row..=point_range.end.row;
 4677                            if point_range.contains(&buffer_row) {
 4678                                Some((location, code_actions))
 4679                            } else {
 4680                                None
 4681                            }
 4682                        })
 4683                        .unzip();
 4684                    let buffer_id = buffer.read(cx).remote_id();
 4685                    let tasks = editor
 4686                        .tasks
 4687                        .get(&(buffer_id, buffer_row))
 4688                        .map(|t| Arc::new(t.to_owned()));
 4689                    if tasks.is_none() && code_actions.is_none() {
 4690                        return None;
 4691                    }
 4692
 4693                    editor.completion_tasks.clear();
 4694                    editor.discard_inline_completion(false, cx);
 4695                    let task_context =
 4696                        tasks
 4697                            .as_ref()
 4698                            .zip(editor.project.clone())
 4699                            .map(|(tasks, project)| {
 4700                                let position = Point::new(buffer_row, tasks.column);
 4701                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4702                                let location = Location {
 4703                                    buffer: buffer.clone(),
 4704                                    range: range_start..range_start,
 4705                                };
 4706                                // Fill in the environmental variables from the tree-sitter captures
 4707                                let mut captured_task_variables = TaskVariables::default();
 4708                                for (capture_name, value) in tasks.extra_variables.clone() {
 4709                                    captured_task_variables.insert(
 4710                                        task::VariableName::Custom(capture_name.into()),
 4711                                        value.clone(),
 4712                                    );
 4713                                }
 4714                                project.update(cx, |project, cx| {
 4715                                    project.task_context_for_location(
 4716                                        captured_task_variables,
 4717                                        location,
 4718                                        cx,
 4719                                    )
 4720                                })
 4721                            });
 4722
 4723                    Some(cx.spawn(|editor, mut cx| async move {
 4724                        let task_context = match task_context {
 4725                            Some(task_context) => task_context.await,
 4726                            None => None,
 4727                        };
 4728                        let resolved_tasks =
 4729                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4730                                Arc::new(ResolvedTasks {
 4731                                    templates: tasks
 4732                                        .templates
 4733                                        .iter()
 4734                                        .filter_map(|(kind, template)| {
 4735                                            template
 4736                                                .resolve_task(&kind.to_id_base(), &task_context)
 4737                                                .map(|task| (kind.clone(), task))
 4738                                        })
 4739                                        .collect(),
 4740                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4741                                        multibuffer_point.row,
 4742                                        tasks.column,
 4743                                    )),
 4744                                })
 4745                            });
 4746                        let spawn_straight_away = resolved_tasks
 4747                            .as_ref()
 4748                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4749                            && code_actions
 4750                                .as_ref()
 4751                                .map_or(true, |actions| actions.is_empty());
 4752                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4753                            *editor.context_menu.write() =
 4754                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4755                                    buffer,
 4756                                    actions: CodeActionContents {
 4757                                        tasks: resolved_tasks,
 4758                                        actions: code_actions,
 4759                                    },
 4760                                    selected_item: Default::default(),
 4761                                    scroll_handle: UniformListScrollHandle::default(),
 4762                                    deployed_from_indicator,
 4763                                }));
 4764                            if spawn_straight_away {
 4765                                if let Some(task) = editor.confirm_code_action(
 4766                                    &ConfirmCodeAction { item_ix: Some(0) },
 4767                                    cx,
 4768                                ) {
 4769                                    cx.notify();
 4770                                    return task;
 4771                                }
 4772                            }
 4773                            cx.notify();
 4774                            Task::ready(Ok(()))
 4775                        }) {
 4776                            task.await
 4777                        } else {
 4778                            Ok(())
 4779                        }
 4780                    }))
 4781                } else {
 4782                    Some(Task::ready(Ok(())))
 4783                }
 4784            })?;
 4785            if let Some(task) = spawned_test_task {
 4786                task.await?;
 4787            }
 4788
 4789            Ok::<_, anyhow::Error>(())
 4790        })
 4791        .detach_and_log_err(cx);
 4792    }
 4793
 4794    pub fn confirm_code_action(
 4795        &mut self,
 4796        action: &ConfirmCodeAction,
 4797        cx: &mut ViewContext<Self>,
 4798    ) -> Option<Task<Result<()>>> {
 4799        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4800            menu
 4801        } else {
 4802            return None;
 4803        };
 4804        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4805        let action = actions_menu.actions.get(action_ix)?;
 4806        let title = action.label();
 4807        let buffer = actions_menu.buffer;
 4808        let workspace = self.workspace()?;
 4809
 4810        match action {
 4811            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4812                workspace.update(cx, |workspace, cx| {
 4813                    workspace::tasks::schedule_resolved_task(
 4814                        workspace,
 4815                        task_source_kind,
 4816                        resolved_task,
 4817                        false,
 4818                        cx,
 4819                    );
 4820
 4821                    Some(Task::ready(Ok(())))
 4822                })
 4823            }
 4824            CodeActionsItem::CodeAction {
 4825                excerpt_id,
 4826                action,
 4827                provider,
 4828            } => {
 4829                let apply_code_action =
 4830                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4831                let workspace = workspace.downgrade();
 4832                Some(cx.spawn(|editor, cx| async move {
 4833                    let project_transaction = apply_code_action.await?;
 4834                    Self::open_project_transaction(
 4835                        &editor,
 4836                        workspace,
 4837                        project_transaction,
 4838                        title,
 4839                        cx,
 4840                    )
 4841                    .await
 4842                }))
 4843            }
 4844        }
 4845    }
 4846
 4847    pub async fn open_project_transaction(
 4848        this: &WeakView<Editor>,
 4849        workspace: WeakView<Workspace>,
 4850        transaction: ProjectTransaction,
 4851        title: String,
 4852        mut cx: AsyncWindowContext,
 4853    ) -> Result<()> {
 4854        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4855        cx.update(|cx| {
 4856            entries.sort_unstable_by_key(|(buffer, _)| {
 4857                buffer.read(cx).file().map(|f| f.path().clone())
 4858            });
 4859        })?;
 4860
 4861        // If the project transaction's edits are all contained within this editor, then
 4862        // avoid opening a new editor to display them.
 4863
 4864        if let Some((buffer, transaction)) = entries.first() {
 4865            if entries.len() == 1 {
 4866                let excerpt = this.update(&mut cx, |editor, cx| {
 4867                    editor
 4868                        .buffer()
 4869                        .read(cx)
 4870                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4871                })?;
 4872                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4873                    if excerpted_buffer == *buffer {
 4874                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4875                            let excerpt_range = excerpt_range.to_offset(buffer);
 4876                            buffer
 4877                                .edited_ranges_for_transaction::<usize>(transaction)
 4878                                .all(|range| {
 4879                                    excerpt_range.start <= range.start
 4880                                        && excerpt_range.end >= range.end
 4881                                })
 4882                        })?;
 4883
 4884                        if all_edits_within_excerpt {
 4885                            return Ok(());
 4886                        }
 4887                    }
 4888                }
 4889            }
 4890        } else {
 4891            return Ok(());
 4892        }
 4893
 4894        let mut ranges_to_highlight = Vec::new();
 4895        let excerpt_buffer = cx.new_model(|cx| {
 4896            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4897            for (buffer_handle, transaction) in &entries {
 4898                let buffer = buffer_handle.read(cx);
 4899                ranges_to_highlight.extend(
 4900                    multibuffer.push_excerpts_with_context_lines(
 4901                        buffer_handle.clone(),
 4902                        buffer
 4903                            .edited_ranges_for_transaction::<usize>(transaction)
 4904                            .collect(),
 4905                        DEFAULT_MULTIBUFFER_CONTEXT,
 4906                        cx,
 4907                    ),
 4908                );
 4909            }
 4910            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4911            multibuffer
 4912        })?;
 4913
 4914        workspace.update(&mut cx, |workspace, cx| {
 4915            let project = workspace.project().clone();
 4916            let editor =
 4917                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4918            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4919            editor.update(cx, |editor, cx| {
 4920                editor.highlight_background::<Self>(
 4921                    &ranges_to_highlight,
 4922                    |theme| theme.editor_highlighted_line_background,
 4923                    cx,
 4924                );
 4925            });
 4926        })?;
 4927
 4928        Ok(())
 4929    }
 4930
 4931    pub fn push_code_action_provider(
 4932        &mut self,
 4933        provider: Arc<dyn CodeActionProvider>,
 4934        cx: &mut ViewContext<Self>,
 4935    ) {
 4936        self.code_action_providers.push(provider);
 4937        self.refresh_code_actions(cx);
 4938    }
 4939
 4940    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4941        let buffer = self.buffer.read(cx);
 4942        let newest_selection = self.selections.newest_anchor().clone();
 4943        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4944        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4945        if start_buffer != end_buffer {
 4946            return None;
 4947        }
 4948
 4949        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4950            cx.background_executor()
 4951                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4952                .await;
 4953
 4954            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4955                let providers = this.code_action_providers.clone();
 4956                let tasks = this
 4957                    .code_action_providers
 4958                    .iter()
 4959                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4960                    .collect::<Vec<_>>();
 4961                (providers, tasks)
 4962            })?;
 4963
 4964            let mut actions = Vec::new();
 4965            for (provider, provider_actions) in
 4966                providers.into_iter().zip(future::join_all(tasks).await)
 4967            {
 4968                if let Some(provider_actions) = provider_actions.log_err() {
 4969                    actions.extend(provider_actions.into_iter().map(|action| {
 4970                        AvailableCodeAction {
 4971                            excerpt_id: newest_selection.start.excerpt_id,
 4972                            action,
 4973                            provider: provider.clone(),
 4974                        }
 4975                    }));
 4976                }
 4977            }
 4978
 4979            this.update(&mut cx, |this, cx| {
 4980                this.available_code_actions = if actions.is_empty() {
 4981                    None
 4982                } else {
 4983                    Some((
 4984                        Location {
 4985                            buffer: start_buffer,
 4986                            range: start..end,
 4987                        },
 4988                        actions.into(),
 4989                    ))
 4990                };
 4991                cx.notify();
 4992            })
 4993        }));
 4994        None
 4995    }
 4996
 4997    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4998        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4999            self.show_git_blame_inline = false;
 5000
 5001            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5002                cx.background_executor().timer(delay).await;
 5003
 5004                this.update(&mut cx, |this, cx| {
 5005                    this.show_git_blame_inline = true;
 5006                    cx.notify();
 5007                })
 5008                .log_err();
 5009            }));
 5010        }
 5011    }
 5012
 5013    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5014        if self.pending_rename.is_some() {
 5015            return None;
 5016        }
 5017
 5018        let project = self.project.clone()?;
 5019        let buffer = self.buffer.read(cx);
 5020        let newest_selection = self.selections.newest_anchor().clone();
 5021        let cursor_position = newest_selection.head();
 5022        let (cursor_buffer, cursor_buffer_position) =
 5023            buffer.text_anchor_for_position(cursor_position, cx)?;
 5024        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5025        if cursor_buffer != tail_buffer {
 5026            return None;
 5027        }
 5028
 5029        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5030            cx.background_executor()
 5031                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5032                .await;
 5033
 5034            let highlights = if let Some(highlights) = project
 5035                .update(&mut cx, |project, cx| {
 5036                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5037                })
 5038                .log_err()
 5039            {
 5040                highlights.await.log_err()
 5041            } else {
 5042                None
 5043            };
 5044
 5045            if let Some(highlights) = highlights {
 5046                this.update(&mut cx, |this, cx| {
 5047                    if this.pending_rename.is_some() {
 5048                        return;
 5049                    }
 5050
 5051                    let buffer_id = cursor_position.buffer_id;
 5052                    let buffer = this.buffer.read(cx);
 5053                    if !buffer
 5054                        .text_anchor_for_position(cursor_position, cx)
 5055                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5056                    {
 5057                        return;
 5058                    }
 5059
 5060                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5061                    let mut write_ranges = Vec::new();
 5062                    let mut read_ranges = Vec::new();
 5063                    for highlight in highlights {
 5064                        for (excerpt_id, excerpt_range) in
 5065                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5066                        {
 5067                            let start = highlight
 5068                                .range
 5069                                .start
 5070                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5071                            let end = highlight
 5072                                .range
 5073                                .end
 5074                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5075                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5076                                continue;
 5077                            }
 5078
 5079                            let range = Anchor {
 5080                                buffer_id,
 5081                                excerpt_id,
 5082                                text_anchor: start,
 5083                            }..Anchor {
 5084                                buffer_id,
 5085                                excerpt_id,
 5086                                text_anchor: end,
 5087                            };
 5088                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5089                                write_ranges.push(range);
 5090                            } else {
 5091                                read_ranges.push(range);
 5092                            }
 5093                        }
 5094                    }
 5095
 5096                    this.highlight_background::<DocumentHighlightRead>(
 5097                        &read_ranges,
 5098                        |theme| theme.editor_document_highlight_read_background,
 5099                        cx,
 5100                    );
 5101                    this.highlight_background::<DocumentHighlightWrite>(
 5102                        &write_ranges,
 5103                        |theme| theme.editor_document_highlight_write_background,
 5104                        cx,
 5105                    );
 5106                    cx.notify();
 5107                })
 5108                .log_err();
 5109            }
 5110        }));
 5111        None
 5112    }
 5113
 5114    pub fn refresh_inline_completion(
 5115        &mut self,
 5116        debounce: bool,
 5117        user_requested: bool,
 5118        cx: &mut ViewContext<Self>,
 5119    ) -> Option<()> {
 5120        let provider = self.inline_completion_provider()?;
 5121        let cursor = self.selections.newest_anchor().head();
 5122        let (buffer, cursor_buffer_position) =
 5123            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5124
 5125        if !user_requested
 5126            && (!self.enable_inline_completions
 5127                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5128        {
 5129            self.discard_inline_completion(false, cx);
 5130            return None;
 5131        }
 5132
 5133        self.update_visible_inline_completion(cx);
 5134        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5135        Some(())
 5136    }
 5137
 5138    fn cycle_inline_completion(
 5139        &mut self,
 5140        direction: Direction,
 5141        cx: &mut ViewContext<Self>,
 5142    ) -> Option<()> {
 5143        let provider = self.inline_completion_provider()?;
 5144        let cursor = self.selections.newest_anchor().head();
 5145        let (buffer, cursor_buffer_position) =
 5146            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5147        if !self.enable_inline_completions
 5148            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5149        {
 5150            return None;
 5151        }
 5152
 5153        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5154        self.update_visible_inline_completion(cx);
 5155
 5156        Some(())
 5157    }
 5158
 5159    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5160        if !self.has_active_inline_completion(cx) {
 5161            self.refresh_inline_completion(false, true, cx);
 5162            return;
 5163        }
 5164
 5165        self.update_visible_inline_completion(cx);
 5166    }
 5167
 5168    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5169        self.show_cursor_names(cx);
 5170    }
 5171
 5172    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5173        self.show_cursor_names = true;
 5174        cx.notify();
 5175        cx.spawn(|this, mut cx| async move {
 5176            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5177            this.update(&mut cx, |this, cx| {
 5178                this.show_cursor_names = false;
 5179                cx.notify()
 5180            })
 5181            .ok()
 5182        })
 5183        .detach();
 5184    }
 5185
 5186    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5187        if self.has_active_inline_completion(cx) {
 5188            self.cycle_inline_completion(Direction::Next, cx);
 5189        } else {
 5190            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5191            if is_copilot_disabled {
 5192                cx.propagate();
 5193            }
 5194        }
 5195    }
 5196
 5197    pub fn previous_inline_completion(
 5198        &mut self,
 5199        _: &PreviousInlineCompletion,
 5200        cx: &mut ViewContext<Self>,
 5201    ) {
 5202        if self.has_active_inline_completion(cx) {
 5203            self.cycle_inline_completion(Direction::Prev, cx);
 5204        } else {
 5205            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5206            if is_copilot_disabled {
 5207                cx.propagate();
 5208            }
 5209        }
 5210    }
 5211
 5212    pub fn accept_inline_completion(
 5213        &mut self,
 5214        _: &AcceptInlineCompletion,
 5215        cx: &mut ViewContext<Self>,
 5216    ) {
 5217        let Some(completion) = self.take_active_inline_completion(cx) else {
 5218            return;
 5219        };
 5220        if let Some(provider) = self.inline_completion_provider() {
 5221            provider.accept(cx);
 5222        }
 5223
 5224        cx.emit(EditorEvent::InputHandled {
 5225            utf16_range_to_replace: None,
 5226            text: completion.text.to_string().into(),
 5227        });
 5228
 5229        if let Some(range) = completion.delete_range {
 5230            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5231        }
 5232        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5233        self.refresh_inline_completion(true, true, cx);
 5234        cx.notify();
 5235    }
 5236
 5237    pub fn accept_partial_inline_completion(
 5238        &mut self,
 5239        _: &AcceptPartialInlineCompletion,
 5240        cx: &mut ViewContext<Self>,
 5241    ) {
 5242        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5243            if let Some(completion) = self.take_active_inline_completion(cx) {
 5244                let mut partial_completion = completion
 5245                    .text
 5246                    .chars()
 5247                    .by_ref()
 5248                    .take_while(|c| c.is_alphabetic())
 5249                    .collect::<String>();
 5250                if partial_completion.is_empty() {
 5251                    partial_completion = completion
 5252                        .text
 5253                        .chars()
 5254                        .by_ref()
 5255                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5256                        .collect::<String>();
 5257                }
 5258
 5259                cx.emit(EditorEvent::InputHandled {
 5260                    utf16_range_to_replace: None,
 5261                    text: partial_completion.clone().into(),
 5262                });
 5263
 5264                if let Some(range) = completion.delete_range {
 5265                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5266                }
 5267                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5268
 5269                self.refresh_inline_completion(true, true, cx);
 5270                cx.notify();
 5271            }
 5272        }
 5273    }
 5274
 5275    fn discard_inline_completion(
 5276        &mut self,
 5277        should_report_inline_completion_event: bool,
 5278        cx: &mut ViewContext<Self>,
 5279    ) -> bool {
 5280        if let Some(provider) = self.inline_completion_provider() {
 5281            provider.discard(should_report_inline_completion_event, cx);
 5282        }
 5283
 5284        self.take_active_inline_completion(cx).is_some()
 5285    }
 5286
 5287    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5288        if let Some(completion) = self.active_inline_completion.as_ref() {
 5289            let buffer = self.buffer.read(cx).read(cx);
 5290            completion.position.is_valid(&buffer)
 5291        } else {
 5292            false
 5293        }
 5294    }
 5295
 5296    fn take_active_inline_completion(
 5297        &mut self,
 5298        cx: &mut ViewContext<Self>,
 5299    ) -> Option<CompletionState> {
 5300        let completion = self.active_inline_completion.take()?;
 5301        let render_inlay_ids = completion.render_inlay_ids.clone();
 5302        self.display_map.update(cx, |map, cx| {
 5303            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5304        });
 5305        let buffer = self.buffer.read(cx).read(cx);
 5306
 5307        if completion.position.is_valid(&buffer) {
 5308            Some(completion)
 5309        } else {
 5310            None
 5311        }
 5312    }
 5313
 5314    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5315        let selection = self.selections.newest_anchor();
 5316        let cursor = selection.head();
 5317
 5318        let excerpt_id = cursor.excerpt_id;
 5319
 5320        if self.context_menu.read().is_none()
 5321            && self.completion_tasks.is_empty()
 5322            && selection.start == selection.end
 5323        {
 5324            if let Some(provider) = self.inline_completion_provider() {
 5325                if let Some((buffer, cursor_buffer_position)) =
 5326                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5327                {
 5328                    if let Some(proposal) =
 5329                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5330                    {
 5331                        let mut to_remove = Vec::new();
 5332                        if let Some(completion) = self.active_inline_completion.take() {
 5333                            to_remove.extend(completion.render_inlay_ids.iter());
 5334                        }
 5335
 5336                        let to_add = proposal
 5337                            .inlays
 5338                            .iter()
 5339                            .filter_map(|inlay| {
 5340                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5341                                let id = post_inc(&mut self.next_inlay_id);
 5342                                match inlay {
 5343                                    InlayProposal::Hint(position, hint) => {
 5344                                        let position =
 5345                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5346                                        Some(Inlay::hint(id, position, hint))
 5347                                    }
 5348                                    InlayProposal::Suggestion(position, text) => {
 5349                                        let position =
 5350                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5351                                        Some(Inlay::suggestion(id, position, text.clone()))
 5352                                    }
 5353                                }
 5354                            })
 5355                            .collect_vec();
 5356
 5357                        self.active_inline_completion = Some(CompletionState {
 5358                            position: cursor,
 5359                            text: proposal.text,
 5360                            delete_range: proposal.delete_range.and_then(|range| {
 5361                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5362                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5363                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5364                                Some(start?..end?)
 5365                            }),
 5366                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5367                        });
 5368
 5369                        self.display_map
 5370                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5371
 5372                        cx.notify();
 5373                        return;
 5374                    }
 5375                }
 5376            }
 5377        }
 5378
 5379        self.discard_inline_completion(false, cx);
 5380    }
 5381
 5382    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5383        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5384    }
 5385
 5386    fn render_code_actions_indicator(
 5387        &self,
 5388        _style: &EditorStyle,
 5389        row: DisplayRow,
 5390        is_active: bool,
 5391        cx: &mut ViewContext<Self>,
 5392    ) -> Option<IconButton> {
 5393        if self.available_code_actions.is_some() {
 5394            Some(
 5395                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5396                    .shape(ui::IconButtonShape::Square)
 5397                    .icon_size(IconSize::XSmall)
 5398                    .icon_color(Color::Muted)
 5399                    .selected(is_active)
 5400                    .tooltip({
 5401                        let focus_handle = self.focus_handle.clone();
 5402                        move |cx| {
 5403                            Tooltip::for_action_in(
 5404                                "Toggle Code Actions",
 5405                                &ToggleCodeActions {
 5406                                    deployed_from_indicator: None,
 5407                                },
 5408                                &focus_handle,
 5409                                cx,
 5410                            )
 5411                        }
 5412                    })
 5413                    .on_click(cx.listener(move |editor, _e, cx| {
 5414                        editor.focus(cx);
 5415                        editor.toggle_code_actions(
 5416                            &ToggleCodeActions {
 5417                                deployed_from_indicator: Some(row),
 5418                            },
 5419                            cx,
 5420                        );
 5421                    })),
 5422            )
 5423        } else {
 5424            None
 5425        }
 5426    }
 5427
 5428    fn clear_tasks(&mut self) {
 5429        self.tasks.clear()
 5430    }
 5431
 5432    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5433        if self.tasks.insert(key, value).is_some() {
 5434            // This case should hopefully be rare, but just in case...
 5435            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5436        }
 5437    }
 5438
 5439    fn render_run_indicator(
 5440        &self,
 5441        _style: &EditorStyle,
 5442        is_active: bool,
 5443        row: DisplayRow,
 5444        cx: &mut ViewContext<Self>,
 5445    ) -> IconButton {
 5446        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5447            .shape(ui::IconButtonShape::Square)
 5448            .icon_size(IconSize::XSmall)
 5449            .icon_color(Color::Muted)
 5450            .selected(is_active)
 5451            .on_click(cx.listener(move |editor, _e, cx| {
 5452                editor.focus(cx);
 5453                editor.toggle_code_actions(
 5454                    &ToggleCodeActions {
 5455                        deployed_from_indicator: Some(row),
 5456                    },
 5457                    cx,
 5458                );
 5459            }))
 5460    }
 5461
 5462    pub fn context_menu_visible(&self) -> bool {
 5463        self.context_menu
 5464            .read()
 5465            .as_ref()
 5466            .map_or(false, |menu| menu.visible())
 5467    }
 5468
 5469    fn render_context_menu(
 5470        &self,
 5471        cursor_position: DisplayPoint,
 5472        style: &EditorStyle,
 5473        max_height: Pixels,
 5474        cx: &mut ViewContext<Editor>,
 5475    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5476        self.context_menu.read().as_ref().map(|menu| {
 5477            menu.render(
 5478                cursor_position,
 5479                style,
 5480                max_height,
 5481                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5482                cx,
 5483            )
 5484        })
 5485    }
 5486
 5487    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5488        cx.notify();
 5489        self.completion_tasks.clear();
 5490        let context_menu = self.context_menu.write().take();
 5491        if context_menu.is_some() {
 5492            self.update_visible_inline_completion(cx);
 5493        }
 5494        context_menu
 5495    }
 5496
 5497    pub fn insert_snippet(
 5498        &mut self,
 5499        insertion_ranges: &[Range<usize>],
 5500        snippet: Snippet,
 5501        cx: &mut ViewContext<Self>,
 5502    ) -> Result<()> {
 5503        struct Tabstop<T> {
 5504            is_end_tabstop: bool,
 5505            ranges: Vec<Range<T>>,
 5506        }
 5507
 5508        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5509            let snippet_text: Arc<str> = snippet.text.clone().into();
 5510            buffer.edit(
 5511                insertion_ranges
 5512                    .iter()
 5513                    .cloned()
 5514                    .map(|range| (range, snippet_text.clone())),
 5515                Some(AutoindentMode::EachLine),
 5516                cx,
 5517            );
 5518
 5519            let snapshot = &*buffer.read(cx);
 5520            let snippet = &snippet;
 5521            snippet
 5522                .tabstops
 5523                .iter()
 5524                .map(|tabstop| {
 5525                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5526                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5527                    });
 5528                    let mut tabstop_ranges = tabstop
 5529                        .iter()
 5530                        .flat_map(|tabstop_range| {
 5531                            let mut delta = 0_isize;
 5532                            insertion_ranges.iter().map(move |insertion_range| {
 5533                                let insertion_start = insertion_range.start as isize + delta;
 5534                                delta +=
 5535                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5536
 5537                                let start = ((insertion_start + tabstop_range.start) as usize)
 5538                                    .min(snapshot.len());
 5539                                let end = ((insertion_start + tabstop_range.end) as usize)
 5540                                    .min(snapshot.len());
 5541                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5542                            })
 5543                        })
 5544                        .collect::<Vec<_>>();
 5545                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5546
 5547                    Tabstop {
 5548                        is_end_tabstop,
 5549                        ranges: tabstop_ranges,
 5550                    }
 5551                })
 5552                .collect::<Vec<_>>()
 5553        });
 5554        if let Some(tabstop) = tabstops.first() {
 5555            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5556                s.select_ranges(tabstop.ranges.iter().cloned());
 5557            });
 5558
 5559            // If we're already at the last tabstop and it's at the end of the snippet,
 5560            // we're done, we don't need to keep the state around.
 5561            if !tabstop.is_end_tabstop {
 5562                let ranges = tabstops
 5563                    .into_iter()
 5564                    .map(|tabstop| tabstop.ranges)
 5565                    .collect::<Vec<_>>();
 5566                self.snippet_stack.push(SnippetState {
 5567                    active_index: 0,
 5568                    ranges,
 5569                });
 5570            }
 5571
 5572            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5573            if self.autoclose_regions.is_empty() {
 5574                let snapshot = self.buffer.read(cx).snapshot(cx);
 5575                for selection in &mut self.selections.all::<Point>(cx) {
 5576                    let selection_head = selection.head();
 5577                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5578                        continue;
 5579                    };
 5580
 5581                    let mut bracket_pair = None;
 5582                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5583                    let prev_chars = snapshot
 5584                        .reversed_chars_at(selection_head)
 5585                        .collect::<String>();
 5586                    for (pair, enabled) in scope.brackets() {
 5587                        if enabled
 5588                            && pair.close
 5589                            && prev_chars.starts_with(pair.start.as_str())
 5590                            && next_chars.starts_with(pair.end.as_str())
 5591                        {
 5592                            bracket_pair = Some(pair.clone());
 5593                            break;
 5594                        }
 5595                    }
 5596                    if let Some(pair) = bracket_pair {
 5597                        let start = snapshot.anchor_after(selection_head);
 5598                        let end = snapshot.anchor_after(selection_head);
 5599                        self.autoclose_regions.push(AutocloseRegion {
 5600                            selection_id: selection.id,
 5601                            range: start..end,
 5602                            pair,
 5603                        });
 5604                    }
 5605                }
 5606            }
 5607        }
 5608        Ok(())
 5609    }
 5610
 5611    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5612        self.move_to_snippet_tabstop(Bias::Right, cx)
 5613    }
 5614
 5615    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5616        self.move_to_snippet_tabstop(Bias::Left, cx)
 5617    }
 5618
 5619    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5620        if let Some(mut snippet) = self.snippet_stack.pop() {
 5621            match bias {
 5622                Bias::Left => {
 5623                    if snippet.active_index > 0 {
 5624                        snippet.active_index -= 1;
 5625                    } else {
 5626                        self.snippet_stack.push(snippet);
 5627                        return false;
 5628                    }
 5629                }
 5630                Bias::Right => {
 5631                    if snippet.active_index + 1 < snippet.ranges.len() {
 5632                        snippet.active_index += 1;
 5633                    } else {
 5634                        self.snippet_stack.push(snippet);
 5635                        return false;
 5636                    }
 5637                }
 5638            }
 5639            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5640                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5641                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5642                });
 5643                // If snippet state is not at the last tabstop, push it back on the stack
 5644                if snippet.active_index + 1 < snippet.ranges.len() {
 5645                    self.snippet_stack.push(snippet);
 5646                }
 5647                return true;
 5648            }
 5649        }
 5650
 5651        false
 5652    }
 5653
 5654    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5655        self.transact(cx, |this, cx| {
 5656            this.select_all(&SelectAll, cx);
 5657            this.insert("", cx);
 5658        });
 5659    }
 5660
 5661    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5662        self.transact(cx, |this, cx| {
 5663            this.select_autoclose_pair(cx);
 5664            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5665            if !this.linked_edit_ranges.is_empty() {
 5666                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5667                let snapshot = this.buffer.read(cx).snapshot(cx);
 5668
 5669                for selection in selections.iter() {
 5670                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5671                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5672                    if selection_start.buffer_id != selection_end.buffer_id {
 5673                        continue;
 5674                    }
 5675                    if let Some(ranges) =
 5676                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5677                    {
 5678                        for (buffer, entries) in ranges {
 5679                            linked_ranges.entry(buffer).or_default().extend(entries);
 5680                        }
 5681                    }
 5682                }
 5683            }
 5684
 5685            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5686            if !this.selections.line_mode {
 5687                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5688                for selection in &mut selections {
 5689                    if selection.is_empty() {
 5690                        let old_head = selection.head();
 5691                        let mut new_head =
 5692                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5693                                .to_point(&display_map);
 5694                        if let Some((buffer, line_buffer_range)) = display_map
 5695                            .buffer_snapshot
 5696                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5697                        {
 5698                            let indent_size =
 5699                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5700                            let indent_len = match indent_size.kind {
 5701                                IndentKind::Space => {
 5702                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5703                                }
 5704                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5705                            };
 5706                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5707                                let indent_len = indent_len.get();
 5708                                new_head = cmp::min(
 5709                                    new_head,
 5710                                    MultiBufferPoint::new(
 5711                                        old_head.row,
 5712                                        ((old_head.column - 1) / indent_len) * indent_len,
 5713                                    ),
 5714                                );
 5715                            }
 5716                        }
 5717
 5718                        selection.set_head(new_head, SelectionGoal::None);
 5719                    }
 5720                }
 5721            }
 5722
 5723            this.signature_help_state.set_backspace_pressed(true);
 5724            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5725            this.insert("", cx);
 5726            let empty_str: Arc<str> = Arc::from("");
 5727            for (buffer, edits) in linked_ranges {
 5728                let snapshot = buffer.read(cx).snapshot();
 5729                use text::ToPoint as TP;
 5730
 5731                let edits = edits
 5732                    .into_iter()
 5733                    .map(|range| {
 5734                        let end_point = TP::to_point(&range.end, &snapshot);
 5735                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5736
 5737                        if end_point == start_point {
 5738                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5739                                .saturating_sub(1);
 5740                            start_point = TP::to_point(&offset, &snapshot);
 5741                        };
 5742
 5743                        (start_point..end_point, empty_str.clone())
 5744                    })
 5745                    .sorted_by_key(|(range, _)| range.start)
 5746                    .collect::<Vec<_>>();
 5747                buffer.update(cx, |this, cx| {
 5748                    this.edit(edits, None, cx);
 5749                })
 5750            }
 5751            this.refresh_inline_completion(true, false, cx);
 5752            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5753        });
 5754    }
 5755
 5756    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5757        self.transact(cx, |this, cx| {
 5758            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5759                let line_mode = s.line_mode;
 5760                s.move_with(|map, selection| {
 5761                    if selection.is_empty() && !line_mode {
 5762                        let cursor = movement::right(map, selection.head());
 5763                        selection.end = cursor;
 5764                        selection.reversed = true;
 5765                        selection.goal = SelectionGoal::None;
 5766                    }
 5767                })
 5768            });
 5769            this.insert("", cx);
 5770            this.refresh_inline_completion(true, false, cx);
 5771        });
 5772    }
 5773
 5774    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5775        if self.move_to_prev_snippet_tabstop(cx) {
 5776            return;
 5777        }
 5778
 5779        self.outdent(&Outdent, cx);
 5780    }
 5781
 5782    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5783        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5784            return;
 5785        }
 5786
 5787        let mut selections = self.selections.all_adjusted(cx);
 5788        let buffer = self.buffer.read(cx);
 5789        let snapshot = buffer.snapshot(cx);
 5790        let rows_iter = selections.iter().map(|s| s.head().row);
 5791        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5792
 5793        let mut edits = Vec::new();
 5794        let mut prev_edited_row = 0;
 5795        let mut row_delta = 0;
 5796        for selection in &mut selections {
 5797            if selection.start.row != prev_edited_row {
 5798                row_delta = 0;
 5799            }
 5800            prev_edited_row = selection.end.row;
 5801
 5802            // If the selection is non-empty, then increase the indentation of the selected lines.
 5803            if !selection.is_empty() {
 5804                row_delta =
 5805                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5806                continue;
 5807            }
 5808
 5809            // If the selection is empty and the cursor is in the leading whitespace before the
 5810            // suggested indentation, then auto-indent the line.
 5811            let cursor = selection.head();
 5812            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5813            if let Some(suggested_indent) =
 5814                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5815            {
 5816                if cursor.column < suggested_indent.len
 5817                    && cursor.column <= current_indent.len
 5818                    && current_indent.len <= suggested_indent.len
 5819                {
 5820                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5821                    selection.end = selection.start;
 5822                    if row_delta == 0 {
 5823                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5824                            cursor.row,
 5825                            current_indent,
 5826                            suggested_indent,
 5827                        ));
 5828                        row_delta = suggested_indent.len - current_indent.len;
 5829                    }
 5830                    continue;
 5831                }
 5832            }
 5833
 5834            // Otherwise, insert a hard or soft tab.
 5835            let settings = buffer.settings_at(cursor, cx);
 5836            let tab_size = if settings.hard_tabs {
 5837                IndentSize::tab()
 5838            } else {
 5839                let tab_size = settings.tab_size.get();
 5840                let char_column = snapshot
 5841                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5842                    .flat_map(str::chars)
 5843                    .count()
 5844                    + row_delta as usize;
 5845                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5846                IndentSize::spaces(chars_to_next_tab_stop)
 5847            };
 5848            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5849            selection.end = selection.start;
 5850            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5851            row_delta += tab_size.len;
 5852        }
 5853
 5854        self.transact(cx, |this, cx| {
 5855            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5856            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5857            this.refresh_inline_completion(true, false, cx);
 5858        });
 5859    }
 5860
 5861    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5862        if self.read_only(cx) {
 5863            return;
 5864        }
 5865        let mut selections = self.selections.all::<Point>(cx);
 5866        let mut prev_edited_row = 0;
 5867        let mut row_delta = 0;
 5868        let mut edits = Vec::new();
 5869        let buffer = self.buffer.read(cx);
 5870        let snapshot = buffer.snapshot(cx);
 5871        for selection in &mut selections {
 5872            if selection.start.row != prev_edited_row {
 5873                row_delta = 0;
 5874            }
 5875            prev_edited_row = selection.end.row;
 5876
 5877            row_delta =
 5878                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5879        }
 5880
 5881        self.transact(cx, |this, cx| {
 5882            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5883            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5884        });
 5885    }
 5886
 5887    fn indent_selection(
 5888        buffer: &MultiBuffer,
 5889        snapshot: &MultiBufferSnapshot,
 5890        selection: &mut Selection<Point>,
 5891        edits: &mut Vec<(Range<Point>, String)>,
 5892        delta_for_start_row: u32,
 5893        cx: &AppContext,
 5894    ) -> u32 {
 5895        let settings = buffer.settings_at(selection.start, cx);
 5896        let tab_size = settings.tab_size.get();
 5897        let indent_kind = if settings.hard_tabs {
 5898            IndentKind::Tab
 5899        } else {
 5900            IndentKind::Space
 5901        };
 5902        let mut start_row = selection.start.row;
 5903        let mut end_row = selection.end.row + 1;
 5904
 5905        // If a selection ends at the beginning of a line, don't indent
 5906        // that last line.
 5907        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5908            end_row -= 1;
 5909        }
 5910
 5911        // Avoid re-indenting a row that has already been indented by a
 5912        // previous selection, but still update this selection's column
 5913        // to reflect that indentation.
 5914        if delta_for_start_row > 0 {
 5915            start_row += 1;
 5916            selection.start.column += delta_for_start_row;
 5917            if selection.end.row == selection.start.row {
 5918                selection.end.column += delta_for_start_row;
 5919            }
 5920        }
 5921
 5922        let mut delta_for_end_row = 0;
 5923        let has_multiple_rows = start_row + 1 != end_row;
 5924        for row in start_row..end_row {
 5925            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5926            let indent_delta = match (current_indent.kind, indent_kind) {
 5927                (IndentKind::Space, IndentKind::Space) => {
 5928                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5929                    IndentSize::spaces(columns_to_next_tab_stop)
 5930                }
 5931                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5932                (_, IndentKind::Tab) => IndentSize::tab(),
 5933            };
 5934
 5935            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5936                0
 5937            } else {
 5938                selection.start.column
 5939            };
 5940            let row_start = Point::new(row, start);
 5941            edits.push((
 5942                row_start..row_start,
 5943                indent_delta.chars().collect::<String>(),
 5944            ));
 5945
 5946            // Update this selection's endpoints to reflect the indentation.
 5947            if row == selection.start.row {
 5948                selection.start.column += indent_delta.len;
 5949            }
 5950            if row == selection.end.row {
 5951                selection.end.column += indent_delta.len;
 5952                delta_for_end_row = indent_delta.len;
 5953            }
 5954        }
 5955
 5956        if selection.start.row == selection.end.row {
 5957            delta_for_start_row + delta_for_end_row
 5958        } else {
 5959            delta_for_end_row
 5960        }
 5961    }
 5962
 5963    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5964        if self.read_only(cx) {
 5965            return;
 5966        }
 5967        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5968        let selections = self.selections.all::<Point>(cx);
 5969        let mut deletion_ranges = Vec::new();
 5970        let mut last_outdent = None;
 5971        {
 5972            let buffer = self.buffer.read(cx);
 5973            let snapshot = buffer.snapshot(cx);
 5974            for selection in &selections {
 5975                let settings = buffer.settings_at(selection.start, cx);
 5976                let tab_size = settings.tab_size.get();
 5977                let mut rows = selection.spanned_rows(false, &display_map);
 5978
 5979                // Avoid re-outdenting a row that has already been outdented by a
 5980                // previous selection.
 5981                if let Some(last_row) = last_outdent {
 5982                    if last_row == rows.start {
 5983                        rows.start = rows.start.next_row();
 5984                    }
 5985                }
 5986                let has_multiple_rows = rows.len() > 1;
 5987                for row in rows.iter_rows() {
 5988                    let indent_size = snapshot.indent_size_for_line(row);
 5989                    if indent_size.len > 0 {
 5990                        let deletion_len = match indent_size.kind {
 5991                            IndentKind::Space => {
 5992                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5993                                if columns_to_prev_tab_stop == 0 {
 5994                                    tab_size
 5995                                } else {
 5996                                    columns_to_prev_tab_stop
 5997                                }
 5998                            }
 5999                            IndentKind::Tab => 1,
 6000                        };
 6001                        let start = if has_multiple_rows
 6002                            || deletion_len > selection.start.column
 6003                            || indent_size.len < selection.start.column
 6004                        {
 6005                            0
 6006                        } else {
 6007                            selection.start.column - deletion_len
 6008                        };
 6009                        deletion_ranges.push(
 6010                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6011                        );
 6012                        last_outdent = Some(row);
 6013                    }
 6014                }
 6015            }
 6016        }
 6017
 6018        self.transact(cx, |this, cx| {
 6019            this.buffer.update(cx, |buffer, cx| {
 6020                let empty_str: Arc<str> = Arc::default();
 6021                buffer.edit(
 6022                    deletion_ranges
 6023                        .into_iter()
 6024                        .map(|range| (range, empty_str.clone())),
 6025                    None,
 6026                    cx,
 6027                );
 6028            });
 6029            let selections = this.selections.all::<usize>(cx);
 6030            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6031        });
 6032    }
 6033
 6034    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6035        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6036        let selections = self.selections.all::<Point>(cx);
 6037
 6038        let mut new_cursors = Vec::new();
 6039        let mut edit_ranges = Vec::new();
 6040        let mut selections = selections.iter().peekable();
 6041        while let Some(selection) = selections.next() {
 6042            let mut rows = selection.spanned_rows(false, &display_map);
 6043            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6044
 6045            // Accumulate contiguous regions of rows that we want to delete.
 6046            while let Some(next_selection) = selections.peek() {
 6047                let next_rows = next_selection.spanned_rows(false, &display_map);
 6048                if next_rows.start <= rows.end {
 6049                    rows.end = next_rows.end;
 6050                    selections.next().unwrap();
 6051                } else {
 6052                    break;
 6053                }
 6054            }
 6055
 6056            let buffer = &display_map.buffer_snapshot;
 6057            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6058            let edit_end;
 6059            let cursor_buffer_row;
 6060            if buffer.max_point().row >= rows.end.0 {
 6061                // If there's a line after the range, delete the \n from the end of the row range
 6062                // and position the cursor on the next line.
 6063                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6064                cursor_buffer_row = rows.end;
 6065            } else {
 6066                // If there isn't a line after the range, delete the \n from the line before the
 6067                // start of the row range and position the cursor there.
 6068                edit_start = edit_start.saturating_sub(1);
 6069                edit_end = buffer.len();
 6070                cursor_buffer_row = rows.start.previous_row();
 6071            }
 6072
 6073            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6074            *cursor.column_mut() =
 6075                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6076
 6077            new_cursors.push((
 6078                selection.id,
 6079                buffer.anchor_after(cursor.to_point(&display_map)),
 6080            ));
 6081            edit_ranges.push(edit_start..edit_end);
 6082        }
 6083
 6084        self.transact(cx, |this, cx| {
 6085            let buffer = this.buffer.update(cx, |buffer, cx| {
 6086                let empty_str: Arc<str> = Arc::default();
 6087                buffer.edit(
 6088                    edit_ranges
 6089                        .into_iter()
 6090                        .map(|range| (range, empty_str.clone())),
 6091                    None,
 6092                    cx,
 6093                );
 6094                buffer.snapshot(cx)
 6095            });
 6096            let new_selections = new_cursors
 6097                .into_iter()
 6098                .map(|(id, cursor)| {
 6099                    let cursor = cursor.to_point(&buffer);
 6100                    Selection {
 6101                        id,
 6102                        start: cursor,
 6103                        end: cursor,
 6104                        reversed: false,
 6105                        goal: SelectionGoal::None,
 6106                    }
 6107                })
 6108                .collect();
 6109
 6110            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6111                s.select(new_selections);
 6112            });
 6113        });
 6114    }
 6115
 6116    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6117        if self.read_only(cx) {
 6118            return;
 6119        }
 6120        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6121        for selection in self.selections.all::<Point>(cx) {
 6122            let start = MultiBufferRow(selection.start.row);
 6123            let end = if selection.start.row == selection.end.row {
 6124                MultiBufferRow(selection.start.row + 1)
 6125            } else {
 6126                MultiBufferRow(selection.end.row)
 6127            };
 6128
 6129            if let Some(last_row_range) = row_ranges.last_mut() {
 6130                if start <= last_row_range.end {
 6131                    last_row_range.end = end;
 6132                    continue;
 6133                }
 6134            }
 6135            row_ranges.push(start..end);
 6136        }
 6137
 6138        let snapshot = self.buffer.read(cx).snapshot(cx);
 6139        let mut cursor_positions = Vec::new();
 6140        for row_range in &row_ranges {
 6141            let anchor = snapshot.anchor_before(Point::new(
 6142                row_range.end.previous_row().0,
 6143                snapshot.line_len(row_range.end.previous_row()),
 6144            ));
 6145            cursor_positions.push(anchor..anchor);
 6146        }
 6147
 6148        self.transact(cx, |this, cx| {
 6149            for row_range in row_ranges.into_iter().rev() {
 6150                for row in row_range.iter_rows().rev() {
 6151                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6152                    let next_line_row = row.next_row();
 6153                    let indent = snapshot.indent_size_for_line(next_line_row);
 6154                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6155
 6156                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6157                        " "
 6158                    } else {
 6159                        ""
 6160                    };
 6161
 6162                    this.buffer.update(cx, |buffer, cx| {
 6163                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6164                    });
 6165                }
 6166            }
 6167
 6168            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6169                s.select_anchor_ranges(cursor_positions)
 6170            });
 6171        });
 6172    }
 6173
 6174    pub fn sort_lines_case_sensitive(
 6175        &mut self,
 6176        _: &SortLinesCaseSensitive,
 6177        cx: &mut ViewContext<Self>,
 6178    ) {
 6179        self.manipulate_lines(cx, |lines| lines.sort())
 6180    }
 6181
 6182    pub fn sort_lines_case_insensitive(
 6183        &mut self,
 6184        _: &SortLinesCaseInsensitive,
 6185        cx: &mut ViewContext<Self>,
 6186    ) {
 6187        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6188    }
 6189
 6190    pub fn unique_lines_case_insensitive(
 6191        &mut self,
 6192        _: &UniqueLinesCaseInsensitive,
 6193        cx: &mut ViewContext<Self>,
 6194    ) {
 6195        self.manipulate_lines(cx, |lines| {
 6196            let mut seen = HashSet::default();
 6197            lines.retain(|line| seen.insert(line.to_lowercase()));
 6198        })
 6199    }
 6200
 6201    pub fn unique_lines_case_sensitive(
 6202        &mut self,
 6203        _: &UniqueLinesCaseSensitive,
 6204        cx: &mut ViewContext<Self>,
 6205    ) {
 6206        self.manipulate_lines(cx, |lines| {
 6207            let mut seen = HashSet::default();
 6208            lines.retain(|line| seen.insert(*line));
 6209        })
 6210    }
 6211
 6212    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6213        let mut revert_changes = HashMap::default();
 6214        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6215        for hunk in hunks_for_rows(
 6216            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6217            &multi_buffer_snapshot,
 6218        ) {
 6219            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6220        }
 6221        if !revert_changes.is_empty() {
 6222            self.transact(cx, |editor, cx| {
 6223                editor.revert(revert_changes, cx);
 6224            });
 6225        }
 6226    }
 6227
 6228    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6229        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6230        if !revert_changes.is_empty() {
 6231            self.transact(cx, |editor, cx| {
 6232                editor.revert(revert_changes, cx);
 6233            });
 6234        }
 6235    }
 6236
 6237    fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
 6238        let snapshot = self.buffer.read(cx).snapshot(cx);
 6239        let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
 6240        self.transact(cx, |editor, cx| {
 6241            for hunk in hunks {
 6242                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
 6243                    buffer.update(cx, |buffer, cx| {
 6244                        buffer.merge_into_base(Some(hunk.buffer_range.to_offset(buffer)), cx);
 6245                    });
 6246                }
 6247            }
 6248        });
 6249    }
 6250
 6251    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6252        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6253            let project_path = buffer.read(cx).project_path(cx)?;
 6254            let project = self.project.as_ref()?.read(cx);
 6255            let entry = project.entry_for_path(&project_path, cx)?;
 6256            let abs_path = project.absolute_path(&project_path, cx)?;
 6257            let parent = if entry.is_symlink {
 6258                abs_path.canonicalize().ok()?
 6259            } else {
 6260                abs_path
 6261            }
 6262            .parent()?
 6263            .to_path_buf();
 6264            Some(parent)
 6265        }) {
 6266            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6267        }
 6268    }
 6269
 6270    fn gather_revert_changes(
 6271        &mut self,
 6272        selections: &[Selection<Anchor>],
 6273        cx: &mut ViewContext<'_, Editor>,
 6274    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6275        let mut revert_changes = HashMap::default();
 6276        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6277        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6278            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6279        }
 6280        revert_changes
 6281    }
 6282
 6283    pub fn prepare_revert_change(
 6284        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6285        multi_buffer: &Model<MultiBuffer>,
 6286        hunk: &MultiBufferDiffHunk,
 6287        cx: &AppContext,
 6288    ) -> Option<()> {
 6289        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6290        let buffer = buffer.read(cx);
 6291        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6292        let buffer_snapshot = buffer.snapshot();
 6293        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6294        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6295            probe
 6296                .0
 6297                .start
 6298                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6299                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6300        }) {
 6301            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6302            Some(())
 6303        } else {
 6304            None
 6305        }
 6306    }
 6307
 6308    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6309        self.manipulate_lines(cx, |lines| lines.reverse())
 6310    }
 6311
 6312    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6313        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6314    }
 6315
 6316    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6317    where
 6318        Fn: FnMut(&mut Vec<&str>),
 6319    {
 6320        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6321        let buffer = self.buffer.read(cx).snapshot(cx);
 6322
 6323        let mut edits = Vec::new();
 6324
 6325        let selections = self.selections.all::<Point>(cx);
 6326        let mut selections = selections.iter().peekable();
 6327        let mut contiguous_row_selections = Vec::new();
 6328        let mut new_selections = Vec::new();
 6329        let mut added_lines = 0;
 6330        let mut removed_lines = 0;
 6331
 6332        while let Some(selection) = selections.next() {
 6333            let (start_row, end_row) = consume_contiguous_rows(
 6334                &mut contiguous_row_selections,
 6335                selection,
 6336                &display_map,
 6337                &mut selections,
 6338            );
 6339
 6340            let start_point = Point::new(start_row.0, 0);
 6341            let end_point = Point::new(
 6342                end_row.previous_row().0,
 6343                buffer.line_len(end_row.previous_row()),
 6344            );
 6345            let text = buffer
 6346                .text_for_range(start_point..end_point)
 6347                .collect::<String>();
 6348
 6349            let mut lines = text.split('\n').collect_vec();
 6350
 6351            let lines_before = lines.len();
 6352            callback(&mut lines);
 6353            let lines_after = lines.len();
 6354
 6355            edits.push((start_point..end_point, lines.join("\n")));
 6356
 6357            // Selections must change based on added and removed line count
 6358            let start_row =
 6359                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6360            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6361            new_selections.push(Selection {
 6362                id: selection.id,
 6363                start: start_row,
 6364                end: end_row,
 6365                goal: SelectionGoal::None,
 6366                reversed: selection.reversed,
 6367            });
 6368
 6369            if lines_after > lines_before {
 6370                added_lines += lines_after - lines_before;
 6371            } else if lines_before > lines_after {
 6372                removed_lines += lines_before - lines_after;
 6373            }
 6374        }
 6375
 6376        self.transact(cx, |this, cx| {
 6377            let buffer = this.buffer.update(cx, |buffer, cx| {
 6378                buffer.edit(edits, None, cx);
 6379                buffer.snapshot(cx)
 6380            });
 6381
 6382            // Recalculate offsets on newly edited buffer
 6383            let new_selections = new_selections
 6384                .iter()
 6385                .map(|s| {
 6386                    let start_point = Point::new(s.start.0, 0);
 6387                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6388                    Selection {
 6389                        id: s.id,
 6390                        start: buffer.point_to_offset(start_point),
 6391                        end: buffer.point_to_offset(end_point),
 6392                        goal: s.goal,
 6393                        reversed: s.reversed,
 6394                    }
 6395                })
 6396                .collect();
 6397
 6398            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6399                s.select(new_selections);
 6400            });
 6401
 6402            this.request_autoscroll(Autoscroll::fit(), cx);
 6403        });
 6404    }
 6405
 6406    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6407        self.manipulate_text(cx, |text| text.to_uppercase())
 6408    }
 6409
 6410    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6411        self.manipulate_text(cx, |text| text.to_lowercase())
 6412    }
 6413
 6414    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6415        self.manipulate_text(cx, |text| {
 6416            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6417            // https://github.com/rutrum/convert-case/issues/16
 6418            text.split('\n')
 6419                .map(|line| line.to_case(Case::Title))
 6420                .join("\n")
 6421        })
 6422    }
 6423
 6424    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6425        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6426    }
 6427
 6428    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6429        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6430    }
 6431
 6432    pub fn convert_to_upper_camel_case(
 6433        &mut self,
 6434        _: &ConvertToUpperCamelCase,
 6435        cx: &mut ViewContext<Self>,
 6436    ) {
 6437        self.manipulate_text(cx, |text| {
 6438            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6439            // https://github.com/rutrum/convert-case/issues/16
 6440            text.split('\n')
 6441                .map(|line| line.to_case(Case::UpperCamel))
 6442                .join("\n")
 6443        })
 6444    }
 6445
 6446    pub fn convert_to_lower_camel_case(
 6447        &mut self,
 6448        _: &ConvertToLowerCamelCase,
 6449        cx: &mut ViewContext<Self>,
 6450    ) {
 6451        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6452    }
 6453
 6454    pub fn convert_to_opposite_case(
 6455        &mut self,
 6456        _: &ConvertToOppositeCase,
 6457        cx: &mut ViewContext<Self>,
 6458    ) {
 6459        self.manipulate_text(cx, |text| {
 6460            text.chars()
 6461                .fold(String::with_capacity(text.len()), |mut t, c| {
 6462                    if c.is_uppercase() {
 6463                        t.extend(c.to_lowercase());
 6464                    } else {
 6465                        t.extend(c.to_uppercase());
 6466                    }
 6467                    t
 6468                })
 6469        })
 6470    }
 6471
 6472    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6473    where
 6474        Fn: FnMut(&str) -> String,
 6475    {
 6476        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6477        let buffer = self.buffer.read(cx).snapshot(cx);
 6478
 6479        let mut new_selections = Vec::new();
 6480        let mut edits = Vec::new();
 6481        let mut selection_adjustment = 0i32;
 6482
 6483        for selection in self.selections.all::<usize>(cx) {
 6484            let selection_is_empty = selection.is_empty();
 6485
 6486            let (start, end) = if selection_is_empty {
 6487                let word_range = movement::surrounding_word(
 6488                    &display_map,
 6489                    selection.start.to_display_point(&display_map),
 6490                );
 6491                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6492                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6493                (start, end)
 6494            } else {
 6495                (selection.start, selection.end)
 6496            };
 6497
 6498            let text = buffer.text_for_range(start..end).collect::<String>();
 6499            let old_length = text.len() as i32;
 6500            let text = callback(&text);
 6501
 6502            new_selections.push(Selection {
 6503                start: (start as i32 - selection_adjustment) as usize,
 6504                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6505                goal: SelectionGoal::None,
 6506                ..selection
 6507            });
 6508
 6509            selection_adjustment += old_length - text.len() as i32;
 6510
 6511            edits.push((start..end, text));
 6512        }
 6513
 6514        self.transact(cx, |this, cx| {
 6515            this.buffer.update(cx, |buffer, cx| {
 6516                buffer.edit(edits, None, cx);
 6517            });
 6518
 6519            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6520                s.select(new_selections);
 6521            });
 6522
 6523            this.request_autoscroll(Autoscroll::fit(), cx);
 6524        });
 6525    }
 6526
 6527    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6528        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6529        let buffer = &display_map.buffer_snapshot;
 6530        let selections = self.selections.all::<Point>(cx);
 6531
 6532        let mut edits = Vec::new();
 6533        let mut selections_iter = selections.iter().peekable();
 6534        while let Some(selection) = selections_iter.next() {
 6535            // Avoid duplicating the same lines twice.
 6536            let mut rows = selection.spanned_rows(false, &display_map);
 6537
 6538            while let Some(next_selection) = selections_iter.peek() {
 6539                let next_rows = next_selection.spanned_rows(false, &display_map);
 6540                if next_rows.start < rows.end {
 6541                    rows.end = next_rows.end;
 6542                    selections_iter.next().unwrap();
 6543                } else {
 6544                    break;
 6545                }
 6546            }
 6547
 6548            // Copy the text from the selected row region and splice it either at the start
 6549            // or end of the region.
 6550            let start = Point::new(rows.start.0, 0);
 6551            let end = Point::new(
 6552                rows.end.previous_row().0,
 6553                buffer.line_len(rows.end.previous_row()),
 6554            );
 6555            let text = buffer
 6556                .text_for_range(start..end)
 6557                .chain(Some("\n"))
 6558                .collect::<String>();
 6559            let insert_location = if upwards {
 6560                Point::new(rows.end.0, 0)
 6561            } else {
 6562                start
 6563            };
 6564            edits.push((insert_location..insert_location, text));
 6565        }
 6566
 6567        self.transact(cx, |this, cx| {
 6568            this.buffer.update(cx, |buffer, cx| {
 6569                buffer.edit(edits, None, cx);
 6570            });
 6571
 6572            this.request_autoscroll(Autoscroll::fit(), cx);
 6573        });
 6574    }
 6575
 6576    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6577        self.duplicate_line(true, cx);
 6578    }
 6579
 6580    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6581        self.duplicate_line(false, cx);
 6582    }
 6583
 6584    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6585        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6586        let buffer = self.buffer.read(cx).snapshot(cx);
 6587
 6588        let mut edits = Vec::new();
 6589        let mut unfold_ranges = Vec::new();
 6590        let mut refold_ranges = Vec::new();
 6591
 6592        let selections = self.selections.all::<Point>(cx);
 6593        let mut selections = selections.iter().peekable();
 6594        let mut contiguous_row_selections = Vec::new();
 6595        let mut new_selections = Vec::new();
 6596
 6597        while let Some(selection) = selections.next() {
 6598            // Find all the selections that span a contiguous row range
 6599            let (start_row, end_row) = consume_contiguous_rows(
 6600                &mut contiguous_row_selections,
 6601                selection,
 6602                &display_map,
 6603                &mut selections,
 6604            );
 6605
 6606            // Move the text spanned by the row range to be before the line preceding the row range
 6607            if start_row.0 > 0 {
 6608                let range_to_move = Point::new(
 6609                    start_row.previous_row().0,
 6610                    buffer.line_len(start_row.previous_row()),
 6611                )
 6612                    ..Point::new(
 6613                        end_row.previous_row().0,
 6614                        buffer.line_len(end_row.previous_row()),
 6615                    );
 6616                let insertion_point = display_map
 6617                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6618                    .0;
 6619
 6620                // Don't move lines across excerpts
 6621                if buffer
 6622                    .excerpt_boundaries_in_range((
 6623                        Bound::Excluded(insertion_point),
 6624                        Bound::Included(range_to_move.end),
 6625                    ))
 6626                    .next()
 6627                    .is_none()
 6628                {
 6629                    let text = buffer
 6630                        .text_for_range(range_to_move.clone())
 6631                        .flat_map(|s| s.chars())
 6632                        .skip(1)
 6633                        .chain(['\n'])
 6634                        .collect::<String>();
 6635
 6636                    edits.push((
 6637                        buffer.anchor_after(range_to_move.start)
 6638                            ..buffer.anchor_before(range_to_move.end),
 6639                        String::new(),
 6640                    ));
 6641                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6642                    edits.push((insertion_anchor..insertion_anchor, text));
 6643
 6644                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6645
 6646                    // Move selections up
 6647                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6648                        |mut selection| {
 6649                            selection.start.row -= row_delta;
 6650                            selection.end.row -= row_delta;
 6651                            selection
 6652                        },
 6653                    ));
 6654
 6655                    // Move folds up
 6656                    unfold_ranges.push(range_to_move.clone());
 6657                    for fold in display_map.folds_in_range(
 6658                        buffer.anchor_before(range_to_move.start)
 6659                            ..buffer.anchor_after(range_to_move.end),
 6660                    ) {
 6661                        let mut start = fold.range.start.to_point(&buffer);
 6662                        let mut end = fold.range.end.to_point(&buffer);
 6663                        start.row -= row_delta;
 6664                        end.row -= row_delta;
 6665                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6666                    }
 6667                }
 6668            }
 6669
 6670            // If we didn't move line(s), preserve the existing selections
 6671            new_selections.append(&mut contiguous_row_selections);
 6672        }
 6673
 6674        self.transact(cx, |this, cx| {
 6675            this.unfold_ranges(unfold_ranges, true, true, cx);
 6676            this.buffer.update(cx, |buffer, cx| {
 6677                for (range, text) in edits {
 6678                    buffer.edit([(range, text)], None, cx);
 6679                }
 6680            });
 6681            this.fold_ranges(refold_ranges, true, cx);
 6682            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6683                s.select(new_selections);
 6684            })
 6685        });
 6686    }
 6687
 6688    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6689        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6690        let buffer = self.buffer.read(cx).snapshot(cx);
 6691
 6692        let mut edits = Vec::new();
 6693        let mut unfold_ranges = Vec::new();
 6694        let mut refold_ranges = Vec::new();
 6695
 6696        let selections = self.selections.all::<Point>(cx);
 6697        let mut selections = selections.iter().peekable();
 6698        let mut contiguous_row_selections = Vec::new();
 6699        let mut new_selections = Vec::new();
 6700
 6701        while let Some(selection) = selections.next() {
 6702            // Find all the selections that span a contiguous row range
 6703            let (start_row, end_row) = consume_contiguous_rows(
 6704                &mut contiguous_row_selections,
 6705                selection,
 6706                &display_map,
 6707                &mut selections,
 6708            );
 6709
 6710            // Move the text spanned by the row range to be after the last line of the row range
 6711            if end_row.0 <= buffer.max_point().row {
 6712                let range_to_move =
 6713                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6714                let insertion_point = display_map
 6715                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6716                    .0;
 6717
 6718                // Don't move lines across excerpt boundaries
 6719                if buffer
 6720                    .excerpt_boundaries_in_range((
 6721                        Bound::Excluded(range_to_move.start),
 6722                        Bound::Included(insertion_point),
 6723                    ))
 6724                    .next()
 6725                    .is_none()
 6726                {
 6727                    let mut text = String::from("\n");
 6728                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6729                    text.pop(); // Drop trailing newline
 6730                    edits.push((
 6731                        buffer.anchor_after(range_to_move.start)
 6732                            ..buffer.anchor_before(range_to_move.end),
 6733                        String::new(),
 6734                    ));
 6735                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6736                    edits.push((insertion_anchor..insertion_anchor, text));
 6737
 6738                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6739
 6740                    // Move selections down
 6741                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6742                        |mut selection| {
 6743                            selection.start.row += row_delta;
 6744                            selection.end.row += row_delta;
 6745                            selection
 6746                        },
 6747                    ));
 6748
 6749                    // Move folds down
 6750                    unfold_ranges.push(range_to_move.clone());
 6751                    for fold in display_map.folds_in_range(
 6752                        buffer.anchor_before(range_to_move.start)
 6753                            ..buffer.anchor_after(range_to_move.end),
 6754                    ) {
 6755                        let mut start = fold.range.start.to_point(&buffer);
 6756                        let mut end = fold.range.end.to_point(&buffer);
 6757                        start.row += row_delta;
 6758                        end.row += row_delta;
 6759                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6760                    }
 6761                }
 6762            }
 6763
 6764            // If we didn't move line(s), preserve the existing selections
 6765            new_selections.append(&mut contiguous_row_selections);
 6766        }
 6767
 6768        self.transact(cx, |this, cx| {
 6769            this.unfold_ranges(unfold_ranges, true, true, cx);
 6770            this.buffer.update(cx, |buffer, cx| {
 6771                for (range, text) in edits {
 6772                    buffer.edit([(range, text)], None, cx);
 6773                }
 6774            });
 6775            this.fold_ranges(refold_ranges, true, cx);
 6776            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6777        });
 6778    }
 6779
 6780    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6781        let text_layout_details = &self.text_layout_details(cx);
 6782        self.transact(cx, |this, cx| {
 6783            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6784                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6785                let line_mode = s.line_mode;
 6786                s.move_with(|display_map, selection| {
 6787                    if !selection.is_empty() || line_mode {
 6788                        return;
 6789                    }
 6790
 6791                    let mut head = selection.head();
 6792                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6793                    if head.column() == display_map.line_len(head.row()) {
 6794                        transpose_offset = display_map
 6795                            .buffer_snapshot
 6796                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6797                    }
 6798
 6799                    if transpose_offset == 0 {
 6800                        return;
 6801                    }
 6802
 6803                    *head.column_mut() += 1;
 6804                    head = display_map.clip_point(head, Bias::Right);
 6805                    let goal = SelectionGoal::HorizontalPosition(
 6806                        display_map
 6807                            .x_for_display_point(head, text_layout_details)
 6808                            .into(),
 6809                    );
 6810                    selection.collapse_to(head, goal);
 6811
 6812                    let transpose_start = display_map
 6813                        .buffer_snapshot
 6814                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6815                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6816                        let transpose_end = display_map
 6817                            .buffer_snapshot
 6818                            .clip_offset(transpose_offset + 1, Bias::Right);
 6819                        if let Some(ch) =
 6820                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6821                        {
 6822                            edits.push((transpose_start..transpose_offset, String::new()));
 6823                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6824                        }
 6825                    }
 6826                });
 6827                edits
 6828            });
 6829            this.buffer
 6830                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6831            let selections = this.selections.all::<usize>(cx);
 6832            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6833                s.select(selections);
 6834            });
 6835        });
 6836    }
 6837
 6838    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6839        self.rewrap_impl(true, cx)
 6840    }
 6841
 6842    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6843        let buffer = self.buffer.read(cx).snapshot(cx);
 6844        let selections = self.selections.all::<Point>(cx);
 6845        let mut selections = selections.iter().peekable();
 6846
 6847        let mut edits = Vec::new();
 6848        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6849
 6850        while let Some(selection) = selections.next() {
 6851            let mut start_row = selection.start.row;
 6852            let mut end_row = selection.end.row;
 6853
 6854            // Skip selections that overlap with a range that has already been rewrapped.
 6855            let selection_range = start_row..end_row;
 6856            if rewrapped_row_ranges
 6857                .iter()
 6858                .any(|range| range.overlaps(&selection_range))
 6859            {
 6860                continue;
 6861            }
 6862
 6863            let mut should_rewrap = !only_text;
 6864
 6865            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6866                match language_scope.language_name().0.as_ref() {
 6867                    "Markdown" | "Plain Text" => {
 6868                        should_rewrap = true;
 6869                    }
 6870                    _ => {}
 6871                }
 6872            }
 6873
 6874            // Since not all lines in the selection may be at the same indent
 6875            // level, choose the indent size that is the most common between all
 6876            // of the lines.
 6877            //
 6878            // If there is a tie, we use the deepest indent.
 6879            let (indent_size, indent_end) = {
 6880                let mut indent_size_occurrences = HashMap::default();
 6881                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6882
 6883                for row in start_row..=end_row {
 6884                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6885                    rows_by_indent_size.entry(indent).or_default().push(row);
 6886                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6887                }
 6888
 6889                let indent_size = indent_size_occurrences
 6890                    .into_iter()
 6891                    .max_by_key(|(indent, count)| (*count, indent.len))
 6892                    .map(|(indent, _)| indent)
 6893                    .unwrap_or_default();
 6894                let row = rows_by_indent_size[&indent_size][0];
 6895                let indent_end = Point::new(row, indent_size.len);
 6896
 6897                (indent_size, indent_end)
 6898            };
 6899
 6900            let mut line_prefix = indent_size.chars().collect::<String>();
 6901
 6902            if let Some(comment_prefix) =
 6903                buffer
 6904                    .language_scope_at(selection.head())
 6905                    .and_then(|language| {
 6906                        language
 6907                            .line_comment_prefixes()
 6908                            .iter()
 6909                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6910                            .cloned()
 6911                    })
 6912            {
 6913                line_prefix.push_str(&comment_prefix);
 6914                should_rewrap = true;
 6915            }
 6916
 6917            if selection.is_empty() {
 6918                'expand_upwards: while start_row > 0 {
 6919                    let prev_row = start_row - 1;
 6920                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6921                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6922                    {
 6923                        start_row = prev_row;
 6924                    } else {
 6925                        break 'expand_upwards;
 6926                    }
 6927                }
 6928
 6929                'expand_downwards: while end_row < buffer.max_point().row {
 6930                    let next_row = end_row + 1;
 6931                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6932                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6933                    {
 6934                        end_row = next_row;
 6935                    } else {
 6936                        break 'expand_downwards;
 6937                    }
 6938                }
 6939            }
 6940
 6941            if !should_rewrap {
 6942                continue;
 6943            }
 6944
 6945            let start = Point::new(start_row, 0);
 6946            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6947            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6948            let Some(lines_without_prefixes) = selection_text
 6949                .lines()
 6950                .map(|line| {
 6951                    line.strip_prefix(&line_prefix)
 6952                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6953                        .ok_or_else(|| {
 6954                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6955                        })
 6956                })
 6957                .collect::<Result<Vec<_>, _>>()
 6958                .log_err()
 6959            else {
 6960                continue;
 6961            };
 6962
 6963            let unwrapped_text = lines_without_prefixes.join(" ");
 6964            let wrap_column = buffer
 6965                .settings_at(Point::new(start_row, 0), cx)
 6966                .preferred_line_length as usize;
 6967            let mut wrapped_text = String::new();
 6968            let mut current_line = line_prefix.clone();
 6969            for word in unwrapped_text.split_whitespace() {
 6970                if current_line.len() + word.len() >= wrap_column {
 6971                    wrapped_text.push_str(&current_line);
 6972                    wrapped_text.push('\n');
 6973                    current_line.truncate(line_prefix.len());
 6974                }
 6975
 6976                if current_line.len() > line_prefix.len() {
 6977                    current_line.push(' ');
 6978                }
 6979
 6980                current_line.push_str(word);
 6981            }
 6982
 6983            if !current_line.is_empty() {
 6984                wrapped_text.push_str(&current_line);
 6985            }
 6986
 6987            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 6988            let mut offset = start.to_offset(&buffer);
 6989            let mut moved_since_edit = true;
 6990
 6991            for change in diff.iter_all_changes() {
 6992                let value = change.value();
 6993                match change.tag() {
 6994                    ChangeTag::Equal => {
 6995                        offset += value.len();
 6996                        moved_since_edit = true;
 6997                    }
 6998                    ChangeTag::Delete => {
 6999                        let start = buffer.anchor_after(offset);
 7000                        let end = buffer.anchor_before(offset + value.len());
 7001
 7002                        if moved_since_edit {
 7003                            edits.push((start..end, String::new()));
 7004                        } else {
 7005                            edits.last_mut().unwrap().0.end = end;
 7006                        }
 7007
 7008                        offset += value.len();
 7009                        moved_since_edit = false;
 7010                    }
 7011                    ChangeTag::Insert => {
 7012                        if moved_since_edit {
 7013                            let anchor = buffer.anchor_after(offset);
 7014                            edits.push((anchor..anchor, value.to_string()));
 7015                        } else {
 7016                            edits.last_mut().unwrap().1.push_str(value);
 7017                        }
 7018
 7019                        moved_since_edit = false;
 7020                    }
 7021                }
 7022            }
 7023
 7024            rewrapped_row_ranges.push(start_row..=end_row);
 7025        }
 7026
 7027        self.buffer
 7028            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7029    }
 7030
 7031    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7032        let mut text = String::new();
 7033        let buffer = self.buffer.read(cx).snapshot(cx);
 7034        let mut selections = self.selections.all::<Point>(cx);
 7035        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7036        {
 7037            let max_point = buffer.max_point();
 7038            let mut is_first = true;
 7039            for selection in &mut selections {
 7040                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7041                if is_entire_line {
 7042                    selection.start = Point::new(selection.start.row, 0);
 7043                    if !selection.is_empty() && selection.end.column == 0 {
 7044                        selection.end = cmp::min(max_point, selection.end);
 7045                    } else {
 7046                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7047                    }
 7048                    selection.goal = SelectionGoal::None;
 7049                }
 7050                if is_first {
 7051                    is_first = false;
 7052                } else {
 7053                    text += "\n";
 7054                }
 7055                let mut len = 0;
 7056                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7057                    text.push_str(chunk);
 7058                    len += chunk.len();
 7059                }
 7060                clipboard_selections.push(ClipboardSelection {
 7061                    len,
 7062                    is_entire_line,
 7063                    first_line_indent: buffer
 7064                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7065                        .len,
 7066                });
 7067            }
 7068        }
 7069
 7070        self.transact(cx, |this, cx| {
 7071            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7072                s.select(selections);
 7073            });
 7074            this.insert("", cx);
 7075            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7076                text,
 7077                clipboard_selections,
 7078            ));
 7079        });
 7080    }
 7081
 7082    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7083        let selections = self.selections.all::<Point>(cx);
 7084        let buffer = self.buffer.read(cx).read(cx);
 7085        let mut text = String::new();
 7086
 7087        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7088        {
 7089            let max_point = buffer.max_point();
 7090            let mut is_first = true;
 7091            for selection in selections.iter() {
 7092                let mut start = selection.start;
 7093                let mut end = selection.end;
 7094                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7095                if is_entire_line {
 7096                    start = Point::new(start.row, 0);
 7097                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7098                }
 7099                if is_first {
 7100                    is_first = false;
 7101                } else {
 7102                    text += "\n";
 7103                }
 7104                let mut len = 0;
 7105                for chunk in buffer.text_for_range(start..end) {
 7106                    text.push_str(chunk);
 7107                    len += chunk.len();
 7108                }
 7109                clipboard_selections.push(ClipboardSelection {
 7110                    len,
 7111                    is_entire_line,
 7112                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7113                });
 7114            }
 7115        }
 7116
 7117        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7118            text,
 7119            clipboard_selections,
 7120        ));
 7121    }
 7122
 7123    pub fn do_paste(
 7124        &mut self,
 7125        text: &String,
 7126        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7127        handle_entire_lines: bool,
 7128        cx: &mut ViewContext<Self>,
 7129    ) {
 7130        if self.read_only(cx) {
 7131            return;
 7132        }
 7133
 7134        let clipboard_text = Cow::Borrowed(text);
 7135
 7136        self.transact(cx, |this, cx| {
 7137            if let Some(mut clipboard_selections) = clipboard_selections {
 7138                let old_selections = this.selections.all::<usize>(cx);
 7139                let all_selections_were_entire_line =
 7140                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7141                let first_selection_indent_column =
 7142                    clipboard_selections.first().map(|s| s.first_line_indent);
 7143                if clipboard_selections.len() != old_selections.len() {
 7144                    clipboard_selections.drain(..);
 7145                }
 7146
 7147                this.buffer.update(cx, |buffer, cx| {
 7148                    let snapshot = buffer.read(cx);
 7149                    let mut start_offset = 0;
 7150                    let mut edits = Vec::new();
 7151                    let mut original_indent_columns = Vec::new();
 7152                    for (ix, selection) in old_selections.iter().enumerate() {
 7153                        let to_insert;
 7154                        let entire_line;
 7155                        let original_indent_column;
 7156                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7157                            let end_offset = start_offset + clipboard_selection.len;
 7158                            to_insert = &clipboard_text[start_offset..end_offset];
 7159                            entire_line = clipboard_selection.is_entire_line;
 7160                            start_offset = end_offset + 1;
 7161                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7162                        } else {
 7163                            to_insert = clipboard_text.as_str();
 7164                            entire_line = all_selections_were_entire_line;
 7165                            original_indent_column = first_selection_indent_column
 7166                        }
 7167
 7168                        // If the corresponding selection was empty when this slice of the
 7169                        // clipboard text was written, then the entire line containing the
 7170                        // selection was copied. If this selection is also currently empty,
 7171                        // then paste the line before the current line of the buffer.
 7172                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7173                            let column = selection.start.to_point(&snapshot).column as usize;
 7174                            let line_start = selection.start - column;
 7175                            line_start..line_start
 7176                        } else {
 7177                            selection.range()
 7178                        };
 7179
 7180                        edits.push((range, to_insert));
 7181                        original_indent_columns.extend(original_indent_column);
 7182                    }
 7183                    drop(snapshot);
 7184
 7185                    buffer.edit(
 7186                        edits,
 7187                        Some(AutoindentMode::Block {
 7188                            original_indent_columns,
 7189                        }),
 7190                        cx,
 7191                    );
 7192                });
 7193
 7194                let selections = this.selections.all::<usize>(cx);
 7195                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7196            } else {
 7197                this.insert(&clipboard_text, cx);
 7198            }
 7199        });
 7200    }
 7201
 7202    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7203        if let Some(item) = cx.read_from_clipboard() {
 7204            let entries = item.entries();
 7205
 7206            match entries.first() {
 7207                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7208                // of all the pasted entries.
 7209                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7210                    .do_paste(
 7211                        clipboard_string.text(),
 7212                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7213                        true,
 7214                        cx,
 7215                    ),
 7216                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7217            }
 7218        }
 7219    }
 7220
 7221    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7222        if self.read_only(cx) {
 7223            return;
 7224        }
 7225
 7226        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7227            if let Some((selections, _)) =
 7228                self.selection_history.transaction(transaction_id).cloned()
 7229            {
 7230                self.change_selections(None, cx, |s| {
 7231                    s.select_anchors(selections.to_vec());
 7232                });
 7233            }
 7234            self.request_autoscroll(Autoscroll::fit(), cx);
 7235            self.unmark_text(cx);
 7236            self.refresh_inline_completion(true, false, cx);
 7237            cx.emit(EditorEvent::Edited { transaction_id });
 7238            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7239        }
 7240    }
 7241
 7242    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7243        if self.read_only(cx) {
 7244            return;
 7245        }
 7246
 7247        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7248            if let Some((_, Some(selections))) =
 7249                self.selection_history.transaction(transaction_id).cloned()
 7250            {
 7251                self.change_selections(None, cx, |s| {
 7252                    s.select_anchors(selections.to_vec());
 7253                });
 7254            }
 7255            self.request_autoscroll(Autoscroll::fit(), cx);
 7256            self.unmark_text(cx);
 7257            self.refresh_inline_completion(true, false, cx);
 7258            cx.emit(EditorEvent::Edited { transaction_id });
 7259        }
 7260    }
 7261
 7262    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7263        self.buffer
 7264            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7265    }
 7266
 7267    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7268        self.buffer
 7269            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7270    }
 7271
 7272    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7273        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7274            let line_mode = s.line_mode;
 7275            s.move_with(|map, selection| {
 7276                let cursor = if selection.is_empty() && !line_mode {
 7277                    movement::left(map, selection.start)
 7278                } else {
 7279                    selection.start
 7280                };
 7281                selection.collapse_to(cursor, SelectionGoal::None);
 7282            });
 7283        })
 7284    }
 7285
 7286    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7287        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7288            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7289        })
 7290    }
 7291
 7292    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7293        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7294            let line_mode = s.line_mode;
 7295            s.move_with(|map, selection| {
 7296                let cursor = if selection.is_empty() && !line_mode {
 7297                    movement::right(map, selection.end)
 7298                } else {
 7299                    selection.end
 7300                };
 7301                selection.collapse_to(cursor, SelectionGoal::None)
 7302            });
 7303        })
 7304    }
 7305
 7306    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7307        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7308            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7309        })
 7310    }
 7311
 7312    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7313        if self.take_rename(true, cx).is_some() {
 7314            return;
 7315        }
 7316
 7317        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7318            cx.propagate();
 7319            return;
 7320        }
 7321
 7322        let text_layout_details = &self.text_layout_details(cx);
 7323        let selection_count = self.selections.count();
 7324        let first_selection = self.selections.first_anchor();
 7325
 7326        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7327            let line_mode = s.line_mode;
 7328            s.move_with(|map, selection| {
 7329                if !selection.is_empty() && !line_mode {
 7330                    selection.goal = SelectionGoal::None;
 7331                }
 7332                let (cursor, goal) = movement::up(
 7333                    map,
 7334                    selection.start,
 7335                    selection.goal,
 7336                    false,
 7337                    text_layout_details,
 7338                );
 7339                selection.collapse_to(cursor, goal);
 7340            });
 7341        });
 7342
 7343        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7344        {
 7345            cx.propagate();
 7346        }
 7347    }
 7348
 7349    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7350        if self.take_rename(true, cx).is_some() {
 7351            return;
 7352        }
 7353
 7354        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7355            cx.propagate();
 7356            return;
 7357        }
 7358
 7359        let text_layout_details = &self.text_layout_details(cx);
 7360
 7361        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7362            let line_mode = s.line_mode;
 7363            s.move_with(|map, selection| {
 7364                if !selection.is_empty() && !line_mode {
 7365                    selection.goal = SelectionGoal::None;
 7366                }
 7367                let (cursor, goal) = movement::up_by_rows(
 7368                    map,
 7369                    selection.start,
 7370                    action.lines,
 7371                    selection.goal,
 7372                    false,
 7373                    text_layout_details,
 7374                );
 7375                selection.collapse_to(cursor, goal);
 7376            });
 7377        })
 7378    }
 7379
 7380    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7381        if self.take_rename(true, cx).is_some() {
 7382            return;
 7383        }
 7384
 7385        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7386            cx.propagate();
 7387            return;
 7388        }
 7389
 7390        let text_layout_details = &self.text_layout_details(cx);
 7391
 7392        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7393            let line_mode = s.line_mode;
 7394            s.move_with(|map, selection| {
 7395                if !selection.is_empty() && !line_mode {
 7396                    selection.goal = SelectionGoal::None;
 7397                }
 7398                let (cursor, goal) = movement::down_by_rows(
 7399                    map,
 7400                    selection.start,
 7401                    action.lines,
 7402                    selection.goal,
 7403                    false,
 7404                    text_layout_details,
 7405                );
 7406                selection.collapse_to(cursor, goal);
 7407            });
 7408        })
 7409    }
 7410
 7411    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7412        let text_layout_details = &self.text_layout_details(cx);
 7413        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7414            s.move_heads_with(|map, head, goal| {
 7415                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7416            })
 7417        })
 7418    }
 7419
 7420    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7421        let text_layout_details = &self.text_layout_details(cx);
 7422        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7423            s.move_heads_with(|map, head, goal| {
 7424                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7425            })
 7426        })
 7427    }
 7428
 7429    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7430        let Some(row_count) = self.visible_row_count() else {
 7431            return;
 7432        };
 7433
 7434        let text_layout_details = &self.text_layout_details(cx);
 7435
 7436        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7437            s.move_heads_with(|map, head, goal| {
 7438                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7439            })
 7440        })
 7441    }
 7442
 7443    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7444        if self.take_rename(true, cx).is_some() {
 7445            return;
 7446        }
 7447
 7448        if self
 7449            .context_menu
 7450            .write()
 7451            .as_mut()
 7452            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 7453            .unwrap_or(false)
 7454        {
 7455            return;
 7456        }
 7457
 7458        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7459            cx.propagate();
 7460            return;
 7461        }
 7462
 7463        let Some(row_count) = self.visible_row_count() else {
 7464            return;
 7465        };
 7466
 7467        let autoscroll = if action.center_cursor {
 7468            Autoscroll::center()
 7469        } else {
 7470            Autoscroll::fit()
 7471        };
 7472
 7473        let text_layout_details = &self.text_layout_details(cx);
 7474
 7475        self.change_selections(Some(autoscroll), cx, |s| {
 7476            let line_mode = s.line_mode;
 7477            s.move_with(|map, selection| {
 7478                if !selection.is_empty() && !line_mode {
 7479                    selection.goal = SelectionGoal::None;
 7480                }
 7481                let (cursor, goal) = movement::up_by_rows(
 7482                    map,
 7483                    selection.end,
 7484                    row_count,
 7485                    selection.goal,
 7486                    false,
 7487                    text_layout_details,
 7488                );
 7489                selection.collapse_to(cursor, goal);
 7490            });
 7491        });
 7492    }
 7493
 7494    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7495        let text_layout_details = &self.text_layout_details(cx);
 7496        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7497            s.move_heads_with(|map, head, goal| {
 7498                movement::up(map, head, goal, false, text_layout_details)
 7499            })
 7500        })
 7501    }
 7502
 7503    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7504        self.take_rename(true, cx);
 7505
 7506        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7507            cx.propagate();
 7508            return;
 7509        }
 7510
 7511        let text_layout_details = &self.text_layout_details(cx);
 7512        let selection_count = self.selections.count();
 7513        let first_selection = self.selections.first_anchor();
 7514
 7515        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7516            let line_mode = s.line_mode;
 7517            s.move_with(|map, selection| {
 7518                if !selection.is_empty() && !line_mode {
 7519                    selection.goal = SelectionGoal::None;
 7520                }
 7521                let (cursor, goal) = movement::down(
 7522                    map,
 7523                    selection.end,
 7524                    selection.goal,
 7525                    false,
 7526                    text_layout_details,
 7527                );
 7528                selection.collapse_to(cursor, goal);
 7529            });
 7530        });
 7531
 7532        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7533        {
 7534            cx.propagate();
 7535        }
 7536    }
 7537
 7538    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7539        let Some(row_count) = self.visible_row_count() else {
 7540            return;
 7541        };
 7542
 7543        let text_layout_details = &self.text_layout_details(cx);
 7544
 7545        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7546            s.move_heads_with(|map, head, goal| {
 7547                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7548            })
 7549        })
 7550    }
 7551
 7552    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7553        if self.take_rename(true, cx).is_some() {
 7554            return;
 7555        }
 7556
 7557        if self
 7558            .context_menu
 7559            .write()
 7560            .as_mut()
 7561            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7562            .unwrap_or(false)
 7563        {
 7564            return;
 7565        }
 7566
 7567        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7568            cx.propagate();
 7569            return;
 7570        }
 7571
 7572        let Some(row_count) = self.visible_row_count() else {
 7573            return;
 7574        };
 7575
 7576        let autoscroll = if action.center_cursor {
 7577            Autoscroll::center()
 7578        } else {
 7579            Autoscroll::fit()
 7580        };
 7581
 7582        let text_layout_details = &self.text_layout_details(cx);
 7583        self.change_selections(Some(autoscroll), cx, |s| {
 7584            let line_mode = s.line_mode;
 7585            s.move_with(|map, selection| {
 7586                if !selection.is_empty() && !line_mode {
 7587                    selection.goal = SelectionGoal::None;
 7588                }
 7589                let (cursor, goal) = movement::down_by_rows(
 7590                    map,
 7591                    selection.end,
 7592                    row_count,
 7593                    selection.goal,
 7594                    false,
 7595                    text_layout_details,
 7596                );
 7597                selection.collapse_to(cursor, goal);
 7598            });
 7599        });
 7600    }
 7601
 7602    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7603        let text_layout_details = &self.text_layout_details(cx);
 7604        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7605            s.move_heads_with(|map, head, goal| {
 7606                movement::down(map, head, goal, false, text_layout_details)
 7607            })
 7608        });
 7609    }
 7610
 7611    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7612        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7613            context_menu.select_first(self.project.as_ref(), cx);
 7614        }
 7615    }
 7616
 7617    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7618        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7619            context_menu.select_prev(self.project.as_ref(), cx);
 7620        }
 7621    }
 7622
 7623    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7624        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7625            context_menu.select_next(self.project.as_ref(), cx);
 7626        }
 7627    }
 7628
 7629    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7630        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7631            context_menu.select_last(self.project.as_ref(), cx);
 7632        }
 7633    }
 7634
 7635    pub fn move_to_previous_word_start(
 7636        &mut self,
 7637        _: &MoveToPreviousWordStart,
 7638        cx: &mut ViewContext<Self>,
 7639    ) {
 7640        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7641            s.move_cursors_with(|map, head, _| {
 7642                (
 7643                    movement::previous_word_start(map, head),
 7644                    SelectionGoal::None,
 7645                )
 7646            });
 7647        })
 7648    }
 7649
 7650    pub fn move_to_previous_subword_start(
 7651        &mut self,
 7652        _: &MoveToPreviousSubwordStart,
 7653        cx: &mut ViewContext<Self>,
 7654    ) {
 7655        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7656            s.move_cursors_with(|map, head, _| {
 7657                (
 7658                    movement::previous_subword_start(map, head),
 7659                    SelectionGoal::None,
 7660                )
 7661            });
 7662        })
 7663    }
 7664
 7665    pub fn select_to_previous_word_start(
 7666        &mut self,
 7667        _: &SelectToPreviousWordStart,
 7668        cx: &mut ViewContext<Self>,
 7669    ) {
 7670        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7671            s.move_heads_with(|map, head, _| {
 7672                (
 7673                    movement::previous_word_start(map, head),
 7674                    SelectionGoal::None,
 7675                )
 7676            });
 7677        })
 7678    }
 7679
 7680    pub fn select_to_previous_subword_start(
 7681        &mut self,
 7682        _: &SelectToPreviousSubwordStart,
 7683        cx: &mut ViewContext<Self>,
 7684    ) {
 7685        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7686            s.move_heads_with(|map, head, _| {
 7687                (
 7688                    movement::previous_subword_start(map, head),
 7689                    SelectionGoal::None,
 7690                )
 7691            });
 7692        })
 7693    }
 7694
 7695    pub fn delete_to_previous_word_start(
 7696        &mut self,
 7697        action: &DeleteToPreviousWordStart,
 7698        cx: &mut ViewContext<Self>,
 7699    ) {
 7700        self.transact(cx, |this, cx| {
 7701            this.select_autoclose_pair(cx);
 7702            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7703                let line_mode = s.line_mode;
 7704                s.move_with(|map, selection| {
 7705                    if selection.is_empty() && !line_mode {
 7706                        let cursor = if action.ignore_newlines {
 7707                            movement::previous_word_start(map, selection.head())
 7708                        } else {
 7709                            movement::previous_word_start_or_newline(map, selection.head())
 7710                        };
 7711                        selection.set_head(cursor, SelectionGoal::None);
 7712                    }
 7713                });
 7714            });
 7715            this.insert("", cx);
 7716        });
 7717    }
 7718
 7719    pub fn delete_to_previous_subword_start(
 7720        &mut self,
 7721        _: &DeleteToPreviousSubwordStart,
 7722        cx: &mut ViewContext<Self>,
 7723    ) {
 7724        self.transact(cx, |this, cx| {
 7725            this.select_autoclose_pair(cx);
 7726            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7727                let line_mode = s.line_mode;
 7728                s.move_with(|map, selection| {
 7729                    if selection.is_empty() && !line_mode {
 7730                        let cursor = movement::previous_subword_start(map, selection.head());
 7731                        selection.set_head(cursor, SelectionGoal::None);
 7732                    }
 7733                });
 7734            });
 7735            this.insert("", cx);
 7736        });
 7737    }
 7738
 7739    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7740        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7741            s.move_cursors_with(|map, head, _| {
 7742                (movement::next_word_end(map, head), SelectionGoal::None)
 7743            });
 7744        })
 7745    }
 7746
 7747    pub fn move_to_next_subword_end(
 7748        &mut self,
 7749        _: &MoveToNextSubwordEnd,
 7750        cx: &mut ViewContext<Self>,
 7751    ) {
 7752        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7753            s.move_cursors_with(|map, head, _| {
 7754                (movement::next_subword_end(map, head), SelectionGoal::None)
 7755            });
 7756        })
 7757    }
 7758
 7759    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7760        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7761            s.move_heads_with(|map, head, _| {
 7762                (movement::next_word_end(map, head), SelectionGoal::None)
 7763            });
 7764        })
 7765    }
 7766
 7767    pub fn select_to_next_subword_end(
 7768        &mut self,
 7769        _: &SelectToNextSubwordEnd,
 7770        cx: &mut ViewContext<Self>,
 7771    ) {
 7772        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7773            s.move_heads_with(|map, head, _| {
 7774                (movement::next_subword_end(map, head), SelectionGoal::None)
 7775            });
 7776        })
 7777    }
 7778
 7779    pub fn delete_to_next_word_end(
 7780        &mut self,
 7781        action: &DeleteToNextWordEnd,
 7782        cx: &mut ViewContext<Self>,
 7783    ) {
 7784        self.transact(cx, |this, cx| {
 7785            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7786                let line_mode = s.line_mode;
 7787                s.move_with(|map, selection| {
 7788                    if selection.is_empty() && !line_mode {
 7789                        let cursor = if action.ignore_newlines {
 7790                            movement::next_word_end(map, selection.head())
 7791                        } else {
 7792                            movement::next_word_end_or_newline(map, selection.head())
 7793                        };
 7794                        selection.set_head(cursor, SelectionGoal::None);
 7795                    }
 7796                });
 7797            });
 7798            this.insert("", cx);
 7799        });
 7800    }
 7801
 7802    pub fn delete_to_next_subword_end(
 7803        &mut self,
 7804        _: &DeleteToNextSubwordEnd,
 7805        cx: &mut ViewContext<Self>,
 7806    ) {
 7807        self.transact(cx, |this, cx| {
 7808            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7809                s.move_with(|map, selection| {
 7810                    if selection.is_empty() {
 7811                        let cursor = movement::next_subword_end(map, selection.head());
 7812                        selection.set_head(cursor, SelectionGoal::None);
 7813                    }
 7814                });
 7815            });
 7816            this.insert("", cx);
 7817        });
 7818    }
 7819
 7820    pub fn move_to_beginning_of_line(
 7821        &mut self,
 7822        action: &MoveToBeginningOfLine,
 7823        cx: &mut ViewContext<Self>,
 7824    ) {
 7825        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7826            s.move_cursors_with(|map, head, _| {
 7827                (
 7828                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7829                    SelectionGoal::None,
 7830                )
 7831            });
 7832        })
 7833    }
 7834
 7835    pub fn select_to_beginning_of_line(
 7836        &mut self,
 7837        action: &SelectToBeginningOfLine,
 7838        cx: &mut ViewContext<Self>,
 7839    ) {
 7840        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7841            s.move_heads_with(|map, head, _| {
 7842                (
 7843                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7844                    SelectionGoal::None,
 7845                )
 7846            });
 7847        });
 7848    }
 7849
 7850    pub fn delete_to_beginning_of_line(
 7851        &mut self,
 7852        _: &DeleteToBeginningOfLine,
 7853        cx: &mut ViewContext<Self>,
 7854    ) {
 7855        self.transact(cx, |this, cx| {
 7856            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7857                s.move_with(|_, selection| {
 7858                    selection.reversed = true;
 7859                });
 7860            });
 7861
 7862            this.select_to_beginning_of_line(
 7863                &SelectToBeginningOfLine {
 7864                    stop_at_soft_wraps: false,
 7865                },
 7866                cx,
 7867            );
 7868            this.backspace(&Backspace, cx);
 7869        });
 7870    }
 7871
 7872    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7873        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7874            s.move_cursors_with(|map, head, _| {
 7875                (
 7876                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7877                    SelectionGoal::None,
 7878                )
 7879            });
 7880        })
 7881    }
 7882
 7883    pub fn select_to_end_of_line(
 7884        &mut self,
 7885        action: &SelectToEndOfLine,
 7886        cx: &mut ViewContext<Self>,
 7887    ) {
 7888        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7889            s.move_heads_with(|map, head, _| {
 7890                (
 7891                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7892                    SelectionGoal::None,
 7893                )
 7894            });
 7895        })
 7896    }
 7897
 7898    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7899        self.transact(cx, |this, cx| {
 7900            this.select_to_end_of_line(
 7901                &SelectToEndOfLine {
 7902                    stop_at_soft_wraps: false,
 7903                },
 7904                cx,
 7905            );
 7906            this.delete(&Delete, cx);
 7907        });
 7908    }
 7909
 7910    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7911        self.transact(cx, |this, cx| {
 7912            this.select_to_end_of_line(
 7913                &SelectToEndOfLine {
 7914                    stop_at_soft_wraps: false,
 7915                },
 7916                cx,
 7917            );
 7918            this.cut(&Cut, cx);
 7919        });
 7920    }
 7921
 7922    pub fn move_to_start_of_paragraph(
 7923        &mut self,
 7924        _: &MoveToStartOfParagraph,
 7925        cx: &mut ViewContext<Self>,
 7926    ) {
 7927        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7928            cx.propagate();
 7929            return;
 7930        }
 7931
 7932        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7933            s.move_with(|map, selection| {
 7934                selection.collapse_to(
 7935                    movement::start_of_paragraph(map, selection.head(), 1),
 7936                    SelectionGoal::None,
 7937                )
 7938            });
 7939        })
 7940    }
 7941
 7942    pub fn move_to_end_of_paragraph(
 7943        &mut self,
 7944        _: &MoveToEndOfParagraph,
 7945        cx: &mut ViewContext<Self>,
 7946    ) {
 7947        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7948            cx.propagate();
 7949            return;
 7950        }
 7951
 7952        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7953            s.move_with(|map, selection| {
 7954                selection.collapse_to(
 7955                    movement::end_of_paragraph(map, selection.head(), 1),
 7956                    SelectionGoal::None,
 7957                )
 7958            });
 7959        })
 7960    }
 7961
 7962    pub fn select_to_start_of_paragraph(
 7963        &mut self,
 7964        _: &SelectToStartOfParagraph,
 7965        cx: &mut ViewContext<Self>,
 7966    ) {
 7967        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7968            cx.propagate();
 7969            return;
 7970        }
 7971
 7972        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7973            s.move_heads_with(|map, head, _| {
 7974                (
 7975                    movement::start_of_paragraph(map, head, 1),
 7976                    SelectionGoal::None,
 7977                )
 7978            });
 7979        })
 7980    }
 7981
 7982    pub fn select_to_end_of_paragraph(
 7983        &mut self,
 7984        _: &SelectToEndOfParagraph,
 7985        cx: &mut ViewContext<Self>,
 7986    ) {
 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.move_heads_with(|map, head, _| {
 7994                (
 7995                    movement::end_of_paragraph(map, head, 1),
 7996                    SelectionGoal::None,
 7997                )
 7998            });
 7999        })
 8000    }
 8001
 8002    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8003        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8004            cx.propagate();
 8005            return;
 8006        }
 8007
 8008        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8009            s.select_ranges(vec![0..0]);
 8010        });
 8011    }
 8012
 8013    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8014        let mut selection = self.selections.last::<Point>(cx);
 8015        selection.set_head(Point::zero(), SelectionGoal::None);
 8016
 8017        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8018            s.select(vec![selection]);
 8019        });
 8020    }
 8021
 8022    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8023        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8024            cx.propagate();
 8025            return;
 8026        }
 8027
 8028        let cursor = self.buffer.read(cx).read(cx).len();
 8029        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8030            s.select_ranges(vec![cursor..cursor])
 8031        });
 8032    }
 8033
 8034    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8035        self.nav_history = nav_history;
 8036    }
 8037
 8038    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8039        self.nav_history.as_ref()
 8040    }
 8041
 8042    fn push_to_nav_history(
 8043        &mut self,
 8044        cursor_anchor: Anchor,
 8045        new_position: Option<Point>,
 8046        cx: &mut ViewContext<Self>,
 8047    ) {
 8048        if let Some(nav_history) = self.nav_history.as_mut() {
 8049            let buffer = self.buffer.read(cx).read(cx);
 8050            let cursor_position = cursor_anchor.to_point(&buffer);
 8051            let scroll_state = self.scroll_manager.anchor();
 8052            let scroll_top_row = scroll_state.top_row(&buffer);
 8053            drop(buffer);
 8054
 8055            if let Some(new_position) = new_position {
 8056                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8057                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8058                    return;
 8059                }
 8060            }
 8061
 8062            nav_history.push(
 8063                Some(NavigationData {
 8064                    cursor_anchor,
 8065                    cursor_position,
 8066                    scroll_anchor: scroll_state,
 8067                    scroll_top_row,
 8068                }),
 8069                cx,
 8070            );
 8071        }
 8072    }
 8073
 8074    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8075        let buffer = self.buffer.read(cx).snapshot(cx);
 8076        let mut selection = self.selections.first::<usize>(cx);
 8077        selection.set_head(buffer.len(), SelectionGoal::None);
 8078        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8079            s.select(vec![selection]);
 8080        });
 8081    }
 8082
 8083    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8084        let end = self.buffer.read(cx).read(cx).len();
 8085        self.change_selections(None, cx, |s| {
 8086            s.select_ranges(vec![0..end]);
 8087        });
 8088    }
 8089
 8090    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8091        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8092        let mut selections = self.selections.all::<Point>(cx);
 8093        let max_point = display_map.buffer_snapshot.max_point();
 8094        for selection in &mut selections {
 8095            let rows = selection.spanned_rows(true, &display_map);
 8096            selection.start = Point::new(rows.start.0, 0);
 8097            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8098            selection.reversed = false;
 8099        }
 8100        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8101            s.select(selections);
 8102        });
 8103    }
 8104
 8105    pub fn split_selection_into_lines(
 8106        &mut self,
 8107        _: &SplitSelectionIntoLines,
 8108        cx: &mut ViewContext<Self>,
 8109    ) {
 8110        let mut to_unfold = Vec::new();
 8111        let mut new_selection_ranges = Vec::new();
 8112        {
 8113            let selections = self.selections.all::<Point>(cx);
 8114            let buffer = self.buffer.read(cx).read(cx);
 8115            for selection in selections {
 8116                for row in selection.start.row..selection.end.row {
 8117                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8118                    new_selection_ranges.push(cursor..cursor);
 8119                }
 8120                new_selection_ranges.push(selection.end..selection.end);
 8121                to_unfold.push(selection.start..selection.end);
 8122            }
 8123        }
 8124        self.unfold_ranges(to_unfold, true, true, cx);
 8125        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8126            s.select_ranges(new_selection_ranges);
 8127        });
 8128    }
 8129
 8130    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8131        self.add_selection(true, cx);
 8132    }
 8133
 8134    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8135        self.add_selection(false, cx);
 8136    }
 8137
 8138    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8139        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8140        let mut selections = self.selections.all::<Point>(cx);
 8141        let text_layout_details = self.text_layout_details(cx);
 8142        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8143            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8144            let range = oldest_selection.display_range(&display_map).sorted();
 8145
 8146            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8147            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8148            let positions = start_x.min(end_x)..start_x.max(end_x);
 8149
 8150            selections.clear();
 8151            let mut stack = Vec::new();
 8152            for row in range.start.row().0..=range.end.row().0 {
 8153                if let Some(selection) = self.selections.build_columnar_selection(
 8154                    &display_map,
 8155                    DisplayRow(row),
 8156                    &positions,
 8157                    oldest_selection.reversed,
 8158                    &text_layout_details,
 8159                ) {
 8160                    stack.push(selection.id);
 8161                    selections.push(selection);
 8162                }
 8163            }
 8164
 8165            if above {
 8166                stack.reverse();
 8167            }
 8168
 8169            AddSelectionsState { above, stack }
 8170        });
 8171
 8172        let last_added_selection = *state.stack.last().unwrap();
 8173        let mut new_selections = Vec::new();
 8174        if above == state.above {
 8175            let end_row = if above {
 8176                DisplayRow(0)
 8177            } else {
 8178                display_map.max_point().row()
 8179            };
 8180
 8181            'outer: for selection in selections {
 8182                if selection.id == last_added_selection {
 8183                    let range = selection.display_range(&display_map).sorted();
 8184                    debug_assert_eq!(range.start.row(), range.end.row());
 8185                    let mut row = range.start.row();
 8186                    let positions =
 8187                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8188                            px(start)..px(end)
 8189                        } else {
 8190                            let start_x =
 8191                                display_map.x_for_display_point(range.start, &text_layout_details);
 8192                            let end_x =
 8193                                display_map.x_for_display_point(range.end, &text_layout_details);
 8194                            start_x.min(end_x)..start_x.max(end_x)
 8195                        };
 8196
 8197                    while row != end_row {
 8198                        if above {
 8199                            row.0 -= 1;
 8200                        } else {
 8201                            row.0 += 1;
 8202                        }
 8203
 8204                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8205                            &display_map,
 8206                            row,
 8207                            &positions,
 8208                            selection.reversed,
 8209                            &text_layout_details,
 8210                        ) {
 8211                            state.stack.push(new_selection.id);
 8212                            if above {
 8213                                new_selections.push(new_selection);
 8214                                new_selections.push(selection);
 8215                            } else {
 8216                                new_selections.push(selection);
 8217                                new_selections.push(new_selection);
 8218                            }
 8219
 8220                            continue 'outer;
 8221                        }
 8222                    }
 8223                }
 8224
 8225                new_selections.push(selection);
 8226            }
 8227        } else {
 8228            new_selections = selections;
 8229            new_selections.retain(|s| s.id != last_added_selection);
 8230            state.stack.pop();
 8231        }
 8232
 8233        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8234            s.select(new_selections);
 8235        });
 8236        if state.stack.len() > 1 {
 8237            self.add_selections_state = Some(state);
 8238        }
 8239    }
 8240
 8241    pub fn select_next_match_internal(
 8242        &mut self,
 8243        display_map: &DisplaySnapshot,
 8244        replace_newest: bool,
 8245        autoscroll: Option<Autoscroll>,
 8246        cx: &mut ViewContext<Self>,
 8247    ) -> Result<()> {
 8248        fn select_next_match_ranges(
 8249            this: &mut Editor,
 8250            range: Range<usize>,
 8251            replace_newest: bool,
 8252            auto_scroll: Option<Autoscroll>,
 8253            cx: &mut ViewContext<Editor>,
 8254        ) {
 8255            this.unfold_ranges([range.clone()], false, true, cx);
 8256            this.change_selections(auto_scroll, cx, |s| {
 8257                if replace_newest {
 8258                    s.delete(s.newest_anchor().id);
 8259                }
 8260                s.insert_range(range.clone());
 8261            });
 8262        }
 8263
 8264        let buffer = &display_map.buffer_snapshot;
 8265        let mut selections = self.selections.all::<usize>(cx);
 8266        if let Some(mut select_next_state) = self.select_next_state.take() {
 8267            let query = &select_next_state.query;
 8268            if !select_next_state.done {
 8269                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8270                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8271                let mut next_selected_range = None;
 8272
 8273                let bytes_after_last_selection =
 8274                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8275                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8276                let query_matches = query
 8277                    .stream_find_iter(bytes_after_last_selection)
 8278                    .map(|result| (last_selection.end, result))
 8279                    .chain(
 8280                        query
 8281                            .stream_find_iter(bytes_before_first_selection)
 8282                            .map(|result| (0, result)),
 8283                    );
 8284
 8285                for (start_offset, query_match) in query_matches {
 8286                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8287                    let offset_range =
 8288                        start_offset + query_match.start()..start_offset + query_match.end();
 8289                    let display_range = offset_range.start.to_display_point(display_map)
 8290                        ..offset_range.end.to_display_point(display_map);
 8291
 8292                    if !select_next_state.wordwise
 8293                        || (!movement::is_inside_word(display_map, display_range.start)
 8294                            && !movement::is_inside_word(display_map, display_range.end))
 8295                    {
 8296                        // TODO: This is n^2, because we might check all the selections
 8297                        if !selections
 8298                            .iter()
 8299                            .any(|selection| selection.range().overlaps(&offset_range))
 8300                        {
 8301                            next_selected_range = Some(offset_range);
 8302                            break;
 8303                        }
 8304                    }
 8305                }
 8306
 8307                if let Some(next_selected_range) = next_selected_range {
 8308                    select_next_match_ranges(
 8309                        self,
 8310                        next_selected_range,
 8311                        replace_newest,
 8312                        autoscroll,
 8313                        cx,
 8314                    );
 8315                } else {
 8316                    select_next_state.done = true;
 8317                }
 8318            }
 8319
 8320            self.select_next_state = Some(select_next_state);
 8321        } else {
 8322            let mut only_carets = true;
 8323            let mut same_text_selected = true;
 8324            let mut selected_text = None;
 8325
 8326            let mut selections_iter = selections.iter().peekable();
 8327            while let Some(selection) = selections_iter.next() {
 8328                if selection.start != selection.end {
 8329                    only_carets = false;
 8330                }
 8331
 8332                if same_text_selected {
 8333                    if selected_text.is_none() {
 8334                        selected_text =
 8335                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8336                    }
 8337
 8338                    if let Some(next_selection) = selections_iter.peek() {
 8339                        if next_selection.range().len() == selection.range().len() {
 8340                            let next_selected_text = buffer
 8341                                .text_for_range(next_selection.range())
 8342                                .collect::<String>();
 8343                            if Some(next_selected_text) != selected_text {
 8344                                same_text_selected = false;
 8345                                selected_text = None;
 8346                            }
 8347                        } else {
 8348                            same_text_selected = false;
 8349                            selected_text = None;
 8350                        }
 8351                    }
 8352                }
 8353            }
 8354
 8355            if only_carets {
 8356                for selection in &mut selections {
 8357                    let word_range = movement::surrounding_word(
 8358                        display_map,
 8359                        selection.start.to_display_point(display_map),
 8360                    );
 8361                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8362                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8363                    selection.goal = SelectionGoal::None;
 8364                    selection.reversed = false;
 8365                    select_next_match_ranges(
 8366                        self,
 8367                        selection.start..selection.end,
 8368                        replace_newest,
 8369                        autoscroll,
 8370                        cx,
 8371                    );
 8372                }
 8373
 8374                if selections.len() == 1 {
 8375                    let selection = selections
 8376                        .last()
 8377                        .expect("ensured that there's only one selection");
 8378                    let query = buffer
 8379                        .text_for_range(selection.start..selection.end)
 8380                        .collect::<String>();
 8381                    let is_empty = query.is_empty();
 8382                    let select_state = SelectNextState {
 8383                        query: AhoCorasick::new(&[query])?,
 8384                        wordwise: true,
 8385                        done: is_empty,
 8386                    };
 8387                    self.select_next_state = Some(select_state);
 8388                } else {
 8389                    self.select_next_state = None;
 8390                }
 8391            } else if let Some(selected_text) = selected_text {
 8392                self.select_next_state = Some(SelectNextState {
 8393                    query: AhoCorasick::new(&[selected_text])?,
 8394                    wordwise: false,
 8395                    done: false,
 8396                });
 8397                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8398            }
 8399        }
 8400        Ok(())
 8401    }
 8402
 8403    pub fn select_all_matches(
 8404        &mut self,
 8405        _action: &SelectAllMatches,
 8406        cx: &mut ViewContext<Self>,
 8407    ) -> Result<()> {
 8408        self.push_to_selection_history();
 8409        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8410
 8411        self.select_next_match_internal(&display_map, false, None, cx)?;
 8412        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8413            return Ok(());
 8414        };
 8415        if select_next_state.done {
 8416            return Ok(());
 8417        }
 8418
 8419        let mut new_selections = self.selections.all::<usize>(cx);
 8420
 8421        let buffer = &display_map.buffer_snapshot;
 8422        let query_matches = select_next_state
 8423            .query
 8424            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8425
 8426        for query_match in query_matches {
 8427            let query_match = query_match.unwrap(); // can only fail due to I/O
 8428            let offset_range = query_match.start()..query_match.end();
 8429            let display_range = offset_range.start.to_display_point(&display_map)
 8430                ..offset_range.end.to_display_point(&display_map);
 8431
 8432            if !select_next_state.wordwise
 8433                || (!movement::is_inside_word(&display_map, display_range.start)
 8434                    && !movement::is_inside_word(&display_map, display_range.end))
 8435            {
 8436                self.selections.change_with(cx, |selections| {
 8437                    new_selections.push(Selection {
 8438                        id: selections.new_selection_id(),
 8439                        start: offset_range.start,
 8440                        end: offset_range.end,
 8441                        reversed: false,
 8442                        goal: SelectionGoal::None,
 8443                    });
 8444                });
 8445            }
 8446        }
 8447
 8448        new_selections.sort_by_key(|selection| selection.start);
 8449        let mut ix = 0;
 8450        while ix + 1 < new_selections.len() {
 8451            let current_selection = &new_selections[ix];
 8452            let next_selection = &new_selections[ix + 1];
 8453            if current_selection.range().overlaps(&next_selection.range()) {
 8454                if current_selection.id < next_selection.id {
 8455                    new_selections.remove(ix + 1);
 8456                } else {
 8457                    new_selections.remove(ix);
 8458                }
 8459            } else {
 8460                ix += 1;
 8461            }
 8462        }
 8463
 8464        select_next_state.done = true;
 8465        self.unfold_ranges(
 8466            new_selections.iter().map(|selection| selection.range()),
 8467            false,
 8468            false,
 8469            cx,
 8470        );
 8471        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8472            selections.select(new_selections)
 8473        });
 8474
 8475        Ok(())
 8476    }
 8477
 8478    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8479        self.push_to_selection_history();
 8480        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8481        self.select_next_match_internal(
 8482            &display_map,
 8483            action.replace_newest,
 8484            Some(Autoscroll::newest()),
 8485            cx,
 8486        )?;
 8487        Ok(())
 8488    }
 8489
 8490    pub fn select_previous(
 8491        &mut self,
 8492        action: &SelectPrevious,
 8493        cx: &mut ViewContext<Self>,
 8494    ) -> Result<()> {
 8495        self.push_to_selection_history();
 8496        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8497        let buffer = &display_map.buffer_snapshot;
 8498        let mut selections = self.selections.all::<usize>(cx);
 8499        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8500            let query = &select_prev_state.query;
 8501            if !select_prev_state.done {
 8502                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8503                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8504                let mut next_selected_range = None;
 8505                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8506                let bytes_before_last_selection =
 8507                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8508                let bytes_after_first_selection =
 8509                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8510                let query_matches = query
 8511                    .stream_find_iter(bytes_before_last_selection)
 8512                    .map(|result| (last_selection.start, result))
 8513                    .chain(
 8514                        query
 8515                            .stream_find_iter(bytes_after_first_selection)
 8516                            .map(|result| (buffer.len(), result)),
 8517                    );
 8518                for (end_offset, query_match) in query_matches {
 8519                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8520                    let offset_range =
 8521                        end_offset - query_match.end()..end_offset - query_match.start();
 8522                    let display_range = offset_range.start.to_display_point(&display_map)
 8523                        ..offset_range.end.to_display_point(&display_map);
 8524
 8525                    if !select_prev_state.wordwise
 8526                        || (!movement::is_inside_word(&display_map, display_range.start)
 8527                            && !movement::is_inside_word(&display_map, display_range.end))
 8528                    {
 8529                        next_selected_range = Some(offset_range);
 8530                        break;
 8531                    }
 8532                }
 8533
 8534                if let Some(next_selected_range) = next_selected_range {
 8535                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8536                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8537                        if action.replace_newest {
 8538                            s.delete(s.newest_anchor().id);
 8539                        }
 8540                        s.insert_range(next_selected_range);
 8541                    });
 8542                } else {
 8543                    select_prev_state.done = true;
 8544                }
 8545            }
 8546
 8547            self.select_prev_state = Some(select_prev_state);
 8548        } else {
 8549            let mut only_carets = true;
 8550            let mut same_text_selected = true;
 8551            let mut selected_text = None;
 8552
 8553            let mut selections_iter = selections.iter().peekable();
 8554            while let Some(selection) = selections_iter.next() {
 8555                if selection.start != selection.end {
 8556                    only_carets = false;
 8557                }
 8558
 8559                if same_text_selected {
 8560                    if selected_text.is_none() {
 8561                        selected_text =
 8562                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8563                    }
 8564
 8565                    if let Some(next_selection) = selections_iter.peek() {
 8566                        if next_selection.range().len() == selection.range().len() {
 8567                            let next_selected_text = buffer
 8568                                .text_for_range(next_selection.range())
 8569                                .collect::<String>();
 8570                            if Some(next_selected_text) != selected_text {
 8571                                same_text_selected = false;
 8572                                selected_text = None;
 8573                            }
 8574                        } else {
 8575                            same_text_selected = false;
 8576                            selected_text = None;
 8577                        }
 8578                    }
 8579                }
 8580            }
 8581
 8582            if only_carets {
 8583                for selection in &mut selections {
 8584                    let word_range = movement::surrounding_word(
 8585                        &display_map,
 8586                        selection.start.to_display_point(&display_map),
 8587                    );
 8588                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8589                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8590                    selection.goal = SelectionGoal::None;
 8591                    selection.reversed = false;
 8592                }
 8593                if selections.len() == 1 {
 8594                    let selection = selections
 8595                        .last()
 8596                        .expect("ensured that there's only one selection");
 8597                    let query = buffer
 8598                        .text_for_range(selection.start..selection.end)
 8599                        .collect::<String>();
 8600                    let is_empty = query.is_empty();
 8601                    let select_state = SelectNextState {
 8602                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8603                        wordwise: true,
 8604                        done: is_empty,
 8605                    };
 8606                    self.select_prev_state = Some(select_state);
 8607                } else {
 8608                    self.select_prev_state = None;
 8609                }
 8610
 8611                self.unfold_ranges(
 8612                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8613                    false,
 8614                    true,
 8615                    cx,
 8616                );
 8617                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8618                    s.select(selections);
 8619                });
 8620            } else if let Some(selected_text) = selected_text {
 8621                self.select_prev_state = Some(SelectNextState {
 8622                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8623                    wordwise: false,
 8624                    done: false,
 8625                });
 8626                self.select_previous(action, cx)?;
 8627            }
 8628        }
 8629        Ok(())
 8630    }
 8631
 8632    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8633        let text_layout_details = &self.text_layout_details(cx);
 8634        self.transact(cx, |this, cx| {
 8635            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8636            let mut edits = Vec::new();
 8637            let mut selection_edit_ranges = Vec::new();
 8638            let mut last_toggled_row = None;
 8639            let snapshot = this.buffer.read(cx).read(cx);
 8640            let empty_str: Arc<str> = Arc::default();
 8641            let mut suffixes_inserted = Vec::new();
 8642
 8643            fn comment_prefix_range(
 8644                snapshot: &MultiBufferSnapshot,
 8645                row: MultiBufferRow,
 8646                comment_prefix: &str,
 8647                comment_prefix_whitespace: &str,
 8648            ) -> Range<Point> {
 8649                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8650
 8651                let mut line_bytes = snapshot
 8652                    .bytes_in_range(start..snapshot.max_point())
 8653                    .flatten()
 8654                    .copied();
 8655
 8656                // If this line currently begins with the line comment prefix, then record
 8657                // the range containing the prefix.
 8658                if line_bytes
 8659                    .by_ref()
 8660                    .take(comment_prefix.len())
 8661                    .eq(comment_prefix.bytes())
 8662                {
 8663                    // Include any whitespace that matches the comment prefix.
 8664                    let matching_whitespace_len = line_bytes
 8665                        .zip(comment_prefix_whitespace.bytes())
 8666                        .take_while(|(a, b)| a == b)
 8667                        .count() as u32;
 8668                    let end = Point::new(
 8669                        start.row,
 8670                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8671                    );
 8672                    start..end
 8673                } else {
 8674                    start..start
 8675                }
 8676            }
 8677
 8678            fn comment_suffix_range(
 8679                snapshot: &MultiBufferSnapshot,
 8680                row: MultiBufferRow,
 8681                comment_suffix: &str,
 8682                comment_suffix_has_leading_space: bool,
 8683            ) -> Range<Point> {
 8684                let end = Point::new(row.0, snapshot.line_len(row));
 8685                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8686
 8687                let mut line_end_bytes = snapshot
 8688                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8689                    .flatten()
 8690                    .copied();
 8691
 8692                let leading_space_len = if suffix_start_column > 0
 8693                    && line_end_bytes.next() == Some(b' ')
 8694                    && comment_suffix_has_leading_space
 8695                {
 8696                    1
 8697                } else {
 8698                    0
 8699                };
 8700
 8701                // If this line currently begins with the line comment prefix, then record
 8702                // the range containing the prefix.
 8703                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8704                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8705                    start..end
 8706                } else {
 8707                    end..end
 8708                }
 8709            }
 8710
 8711            // TODO: Handle selections that cross excerpts
 8712            for selection in &mut selections {
 8713                let start_column = snapshot
 8714                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8715                    .len;
 8716                let language = if let Some(language) =
 8717                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8718                {
 8719                    language
 8720                } else {
 8721                    continue;
 8722                };
 8723
 8724                selection_edit_ranges.clear();
 8725
 8726                // If multiple selections contain a given row, avoid processing that
 8727                // row more than once.
 8728                let mut start_row = MultiBufferRow(selection.start.row);
 8729                if last_toggled_row == Some(start_row) {
 8730                    start_row = start_row.next_row();
 8731                }
 8732                let end_row =
 8733                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8734                        MultiBufferRow(selection.end.row - 1)
 8735                    } else {
 8736                        MultiBufferRow(selection.end.row)
 8737                    };
 8738                last_toggled_row = Some(end_row);
 8739
 8740                if start_row > end_row {
 8741                    continue;
 8742                }
 8743
 8744                // If the language has line comments, toggle those.
 8745                let full_comment_prefixes = language.line_comment_prefixes();
 8746                if !full_comment_prefixes.is_empty() {
 8747                    let first_prefix = full_comment_prefixes
 8748                        .first()
 8749                        .expect("prefixes is non-empty");
 8750                    let prefix_trimmed_lengths = full_comment_prefixes
 8751                        .iter()
 8752                        .map(|p| p.trim_end_matches(' ').len())
 8753                        .collect::<SmallVec<[usize; 4]>>();
 8754
 8755                    let mut all_selection_lines_are_comments = true;
 8756
 8757                    for row in start_row.0..=end_row.0 {
 8758                        let row = MultiBufferRow(row);
 8759                        if start_row < end_row && snapshot.is_line_blank(row) {
 8760                            continue;
 8761                        }
 8762
 8763                        let prefix_range = full_comment_prefixes
 8764                            .iter()
 8765                            .zip(prefix_trimmed_lengths.iter().copied())
 8766                            .map(|(prefix, trimmed_prefix_len)| {
 8767                                comment_prefix_range(
 8768                                    snapshot.deref(),
 8769                                    row,
 8770                                    &prefix[..trimmed_prefix_len],
 8771                                    &prefix[trimmed_prefix_len..],
 8772                                )
 8773                            })
 8774                            .max_by_key(|range| range.end.column - range.start.column)
 8775                            .expect("prefixes is non-empty");
 8776
 8777                        if prefix_range.is_empty() {
 8778                            all_selection_lines_are_comments = false;
 8779                        }
 8780
 8781                        selection_edit_ranges.push(prefix_range);
 8782                    }
 8783
 8784                    if all_selection_lines_are_comments {
 8785                        edits.extend(
 8786                            selection_edit_ranges
 8787                                .iter()
 8788                                .cloned()
 8789                                .map(|range| (range, empty_str.clone())),
 8790                        );
 8791                    } else {
 8792                        let min_column = selection_edit_ranges
 8793                            .iter()
 8794                            .map(|range| range.start.column)
 8795                            .min()
 8796                            .unwrap_or(0);
 8797                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8798                            let position = Point::new(range.start.row, min_column);
 8799                            (position..position, first_prefix.clone())
 8800                        }));
 8801                    }
 8802                } else if let Some((full_comment_prefix, comment_suffix)) =
 8803                    language.block_comment_delimiters()
 8804                {
 8805                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8806                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8807                    let prefix_range = comment_prefix_range(
 8808                        snapshot.deref(),
 8809                        start_row,
 8810                        comment_prefix,
 8811                        comment_prefix_whitespace,
 8812                    );
 8813                    let suffix_range = comment_suffix_range(
 8814                        snapshot.deref(),
 8815                        end_row,
 8816                        comment_suffix.trim_start_matches(' '),
 8817                        comment_suffix.starts_with(' '),
 8818                    );
 8819
 8820                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8821                        edits.push((
 8822                            prefix_range.start..prefix_range.start,
 8823                            full_comment_prefix.clone(),
 8824                        ));
 8825                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8826                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8827                    } else {
 8828                        edits.push((prefix_range, empty_str.clone()));
 8829                        edits.push((suffix_range, empty_str.clone()));
 8830                    }
 8831                } else {
 8832                    continue;
 8833                }
 8834            }
 8835
 8836            drop(snapshot);
 8837            this.buffer.update(cx, |buffer, cx| {
 8838                buffer.edit(edits, None, cx);
 8839            });
 8840
 8841            // Adjust selections so that they end before any comment suffixes that
 8842            // were inserted.
 8843            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8844            let mut selections = this.selections.all::<Point>(cx);
 8845            let snapshot = this.buffer.read(cx).read(cx);
 8846            for selection in &mut selections {
 8847                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8848                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8849                        Ordering::Less => {
 8850                            suffixes_inserted.next();
 8851                            continue;
 8852                        }
 8853                        Ordering::Greater => break,
 8854                        Ordering::Equal => {
 8855                            if selection.end.column == snapshot.line_len(row) {
 8856                                if selection.is_empty() {
 8857                                    selection.start.column -= suffix_len as u32;
 8858                                }
 8859                                selection.end.column -= suffix_len as u32;
 8860                            }
 8861                            break;
 8862                        }
 8863                    }
 8864                }
 8865            }
 8866
 8867            drop(snapshot);
 8868            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8869
 8870            let selections = this.selections.all::<Point>(cx);
 8871            let selections_on_single_row = selections.windows(2).all(|selections| {
 8872                selections[0].start.row == selections[1].start.row
 8873                    && selections[0].end.row == selections[1].end.row
 8874                    && selections[0].start.row == selections[0].end.row
 8875            });
 8876            let selections_selecting = selections
 8877                .iter()
 8878                .any(|selection| selection.start != selection.end);
 8879            let advance_downwards = action.advance_downwards
 8880                && selections_on_single_row
 8881                && !selections_selecting
 8882                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8883
 8884            if advance_downwards {
 8885                let snapshot = this.buffer.read(cx).snapshot(cx);
 8886
 8887                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8888                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8889                        let mut point = display_point.to_point(display_snapshot);
 8890                        point.row += 1;
 8891                        point = snapshot.clip_point(point, Bias::Left);
 8892                        let display_point = point.to_display_point(display_snapshot);
 8893                        let goal = SelectionGoal::HorizontalPosition(
 8894                            display_snapshot
 8895                                .x_for_display_point(display_point, text_layout_details)
 8896                                .into(),
 8897                        );
 8898                        (display_point, goal)
 8899                    })
 8900                });
 8901            }
 8902        });
 8903    }
 8904
 8905    pub fn select_enclosing_symbol(
 8906        &mut self,
 8907        _: &SelectEnclosingSymbol,
 8908        cx: &mut ViewContext<Self>,
 8909    ) {
 8910        let buffer = self.buffer.read(cx).snapshot(cx);
 8911        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8912
 8913        fn update_selection(
 8914            selection: &Selection<usize>,
 8915            buffer_snap: &MultiBufferSnapshot,
 8916        ) -> Option<Selection<usize>> {
 8917            let cursor = selection.head();
 8918            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8919            for symbol in symbols.iter().rev() {
 8920                let start = symbol.range.start.to_offset(buffer_snap);
 8921                let end = symbol.range.end.to_offset(buffer_snap);
 8922                let new_range = start..end;
 8923                if start < selection.start || end > selection.end {
 8924                    return Some(Selection {
 8925                        id: selection.id,
 8926                        start: new_range.start,
 8927                        end: new_range.end,
 8928                        goal: SelectionGoal::None,
 8929                        reversed: selection.reversed,
 8930                    });
 8931                }
 8932            }
 8933            None
 8934        }
 8935
 8936        let mut selected_larger_symbol = false;
 8937        let new_selections = old_selections
 8938            .iter()
 8939            .map(|selection| match update_selection(selection, &buffer) {
 8940                Some(new_selection) => {
 8941                    if new_selection.range() != selection.range() {
 8942                        selected_larger_symbol = true;
 8943                    }
 8944                    new_selection
 8945                }
 8946                None => selection.clone(),
 8947            })
 8948            .collect::<Vec<_>>();
 8949
 8950        if selected_larger_symbol {
 8951            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8952                s.select(new_selections);
 8953            });
 8954        }
 8955    }
 8956
 8957    pub fn select_larger_syntax_node(
 8958        &mut self,
 8959        _: &SelectLargerSyntaxNode,
 8960        cx: &mut ViewContext<Self>,
 8961    ) {
 8962        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8963        let buffer = self.buffer.read(cx).snapshot(cx);
 8964        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8965
 8966        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8967        let mut selected_larger_node = false;
 8968        let new_selections = old_selections
 8969            .iter()
 8970            .map(|selection| {
 8971                let old_range = selection.start..selection.end;
 8972                let mut new_range = old_range.clone();
 8973                while let Some(containing_range) =
 8974                    buffer.range_for_syntax_ancestor(new_range.clone())
 8975                {
 8976                    new_range = containing_range;
 8977                    if !display_map.intersects_fold(new_range.start)
 8978                        && !display_map.intersects_fold(new_range.end)
 8979                    {
 8980                        break;
 8981                    }
 8982                }
 8983
 8984                selected_larger_node |= new_range != old_range;
 8985                Selection {
 8986                    id: selection.id,
 8987                    start: new_range.start,
 8988                    end: new_range.end,
 8989                    goal: SelectionGoal::None,
 8990                    reversed: selection.reversed,
 8991                }
 8992            })
 8993            .collect::<Vec<_>>();
 8994
 8995        if selected_larger_node {
 8996            stack.push(old_selections);
 8997            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8998                s.select(new_selections);
 8999            });
 9000        }
 9001        self.select_larger_syntax_node_stack = stack;
 9002    }
 9003
 9004    pub fn select_smaller_syntax_node(
 9005        &mut self,
 9006        _: &SelectSmallerSyntaxNode,
 9007        cx: &mut ViewContext<Self>,
 9008    ) {
 9009        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9010        if let Some(selections) = stack.pop() {
 9011            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9012                s.select(selections.to_vec());
 9013            });
 9014        }
 9015        self.select_larger_syntax_node_stack = stack;
 9016    }
 9017
 9018    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9019        if !EditorSettings::get_global(cx).gutter.runnables {
 9020            self.clear_tasks();
 9021            return Task::ready(());
 9022        }
 9023        let project = self.project.clone();
 9024        cx.spawn(|this, mut cx| async move {
 9025            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9026                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9027            }) else {
 9028                return;
 9029            };
 9030
 9031            let Some(project) = project else {
 9032                return;
 9033            };
 9034
 9035            let hide_runnables = project
 9036                .update(&mut cx, |project, cx| {
 9037                    // Do not display any test indicators in non-dev server remote projects.
 9038                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9039                })
 9040                .unwrap_or(true);
 9041            if hide_runnables {
 9042                return;
 9043            }
 9044            let new_rows =
 9045                cx.background_executor()
 9046                    .spawn({
 9047                        let snapshot = display_snapshot.clone();
 9048                        async move {
 9049                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9050                        }
 9051                    })
 9052                    .await;
 9053            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9054
 9055            this.update(&mut cx, |this, _| {
 9056                this.clear_tasks();
 9057                for (key, value) in rows {
 9058                    this.insert_tasks(key, value);
 9059                }
 9060            })
 9061            .ok();
 9062        })
 9063    }
 9064    fn fetch_runnable_ranges(
 9065        snapshot: &DisplaySnapshot,
 9066        range: Range<Anchor>,
 9067    ) -> Vec<language::RunnableRange> {
 9068        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9069    }
 9070
 9071    fn runnable_rows(
 9072        project: Model<Project>,
 9073        snapshot: DisplaySnapshot,
 9074        runnable_ranges: Vec<RunnableRange>,
 9075        mut cx: AsyncWindowContext,
 9076    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9077        runnable_ranges
 9078            .into_iter()
 9079            .filter_map(|mut runnable| {
 9080                let tasks = cx
 9081                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9082                    .ok()?;
 9083                if tasks.is_empty() {
 9084                    return None;
 9085                }
 9086
 9087                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9088
 9089                let row = snapshot
 9090                    .buffer_snapshot
 9091                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9092                    .1
 9093                    .start
 9094                    .row;
 9095
 9096                let context_range =
 9097                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9098                Some((
 9099                    (runnable.buffer_id, row),
 9100                    RunnableTasks {
 9101                        templates: tasks,
 9102                        offset: MultiBufferOffset(runnable.run_range.start),
 9103                        context_range,
 9104                        column: point.column,
 9105                        extra_variables: runnable.extra_captures,
 9106                    },
 9107                ))
 9108            })
 9109            .collect()
 9110    }
 9111
 9112    fn templates_with_tags(
 9113        project: &Model<Project>,
 9114        runnable: &mut Runnable,
 9115        cx: &WindowContext<'_>,
 9116    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9117        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9118            let (worktree_id, file) = project
 9119                .buffer_for_id(runnable.buffer, cx)
 9120                .and_then(|buffer| buffer.read(cx).file())
 9121                .map(|file| (file.worktree_id(cx), file.clone()))
 9122                .unzip();
 9123
 9124            (project.task_inventory().clone(), worktree_id, file)
 9125        });
 9126
 9127        let inventory = inventory.read(cx);
 9128        let tags = mem::take(&mut runnable.tags);
 9129        let mut tags: Vec<_> = tags
 9130            .into_iter()
 9131            .flat_map(|tag| {
 9132                let tag = tag.0.clone();
 9133                inventory
 9134                    .list_tasks(
 9135                        file.clone(),
 9136                        Some(runnable.language.clone()),
 9137                        worktree_id,
 9138                        cx,
 9139                    )
 9140                    .into_iter()
 9141                    .filter(move |(_, template)| {
 9142                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9143                    })
 9144            })
 9145            .sorted_by_key(|(kind, _)| kind.to_owned())
 9146            .collect();
 9147        if let Some((leading_tag_source, _)) = tags.first() {
 9148            // Strongest source wins; if we have worktree tag binding, prefer that to
 9149            // global and language bindings;
 9150            // if we have a global binding, prefer that to language binding.
 9151            let first_mismatch = tags
 9152                .iter()
 9153                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9154            if let Some(index) = first_mismatch {
 9155                tags.truncate(index);
 9156            }
 9157        }
 9158
 9159        tags
 9160    }
 9161
 9162    pub fn move_to_enclosing_bracket(
 9163        &mut self,
 9164        _: &MoveToEnclosingBracket,
 9165        cx: &mut ViewContext<Self>,
 9166    ) {
 9167        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9168            s.move_offsets_with(|snapshot, selection| {
 9169                let Some(enclosing_bracket_ranges) =
 9170                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9171                else {
 9172                    return;
 9173                };
 9174
 9175                let mut best_length = usize::MAX;
 9176                let mut best_inside = false;
 9177                let mut best_in_bracket_range = false;
 9178                let mut best_destination = None;
 9179                for (open, close) in enclosing_bracket_ranges {
 9180                    let close = close.to_inclusive();
 9181                    let length = close.end() - open.start;
 9182                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9183                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9184                        || close.contains(&selection.head());
 9185
 9186                    // If best is next to a bracket and current isn't, skip
 9187                    if !in_bracket_range && best_in_bracket_range {
 9188                        continue;
 9189                    }
 9190
 9191                    // Prefer smaller lengths unless best is inside and current isn't
 9192                    if length > best_length && (best_inside || !inside) {
 9193                        continue;
 9194                    }
 9195
 9196                    best_length = length;
 9197                    best_inside = inside;
 9198                    best_in_bracket_range = in_bracket_range;
 9199                    best_destination = Some(
 9200                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9201                            if inside {
 9202                                open.end
 9203                            } else {
 9204                                open.start
 9205                            }
 9206                        } else if inside {
 9207                            *close.start()
 9208                        } else {
 9209                            *close.end()
 9210                        },
 9211                    );
 9212                }
 9213
 9214                if let Some(destination) = best_destination {
 9215                    selection.collapse_to(destination, SelectionGoal::None);
 9216                }
 9217            })
 9218        });
 9219    }
 9220
 9221    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9222        self.end_selection(cx);
 9223        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9224        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9225            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9226            self.select_next_state = entry.select_next_state;
 9227            self.select_prev_state = entry.select_prev_state;
 9228            self.add_selections_state = entry.add_selections_state;
 9229            self.request_autoscroll(Autoscroll::newest(), cx);
 9230        }
 9231        self.selection_history.mode = SelectionHistoryMode::Normal;
 9232    }
 9233
 9234    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9235        self.end_selection(cx);
 9236        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9237        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9238            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9239            self.select_next_state = entry.select_next_state;
 9240            self.select_prev_state = entry.select_prev_state;
 9241            self.add_selections_state = entry.add_selections_state;
 9242            self.request_autoscroll(Autoscroll::newest(), cx);
 9243        }
 9244        self.selection_history.mode = SelectionHistoryMode::Normal;
 9245    }
 9246
 9247    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9248        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9249    }
 9250
 9251    pub fn expand_excerpts_down(
 9252        &mut self,
 9253        action: &ExpandExcerptsDown,
 9254        cx: &mut ViewContext<Self>,
 9255    ) {
 9256        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9257    }
 9258
 9259    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9260        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9261    }
 9262
 9263    pub fn expand_excerpts_for_direction(
 9264        &mut self,
 9265        lines: u32,
 9266        direction: ExpandExcerptDirection,
 9267        cx: &mut ViewContext<Self>,
 9268    ) {
 9269        let selections = self.selections.disjoint_anchors();
 9270
 9271        let lines = if lines == 0 {
 9272            EditorSettings::get_global(cx).expand_excerpt_lines
 9273        } else {
 9274            lines
 9275        };
 9276
 9277        self.buffer.update(cx, |buffer, cx| {
 9278            buffer.expand_excerpts(
 9279                selections
 9280                    .iter()
 9281                    .map(|selection| selection.head().excerpt_id)
 9282                    .dedup(),
 9283                lines,
 9284                direction,
 9285                cx,
 9286            )
 9287        })
 9288    }
 9289
 9290    pub fn expand_excerpt(
 9291        &mut self,
 9292        excerpt: ExcerptId,
 9293        direction: ExpandExcerptDirection,
 9294        cx: &mut ViewContext<Self>,
 9295    ) {
 9296        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9297        self.buffer.update(cx, |buffer, cx| {
 9298            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9299        })
 9300    }
 9301
 9302    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9303        self.go_to_diagnostic_impl(Direction::Next, cx)
 9304    }
 9305
 9306    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9307        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9308    }
 9309
 9310    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9311        let buffer = self.buffer.read(cx).snapshot(cx);
 9312        let selection = self.selections.newest::<usize>(cx);
 9313
 9314        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9315        if direction == Direction::Next {
 9316            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9317                let (group_id, jump_to) = popover.activation_info();
 9318                if self.activate_diagnostics(group_id, cx) {
 9319                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9320                        let mut new_selection = s.newest_anchor().clone();
 9321                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9322                        s.select_anchors(vec![new_selection.clone()]);
 9323                    });
 9324                }
 9325                return;
 9326            }
 9327        }
 9328
 9329        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9330            active_diagnostics
 9331                .primary_range
 9332                .to_offset(&buffer)
 9333                .to_inclusive()
 9334        });
 9335        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9336            if active_primary_range.contains(&selection.head()) {
 9337                *active_primary_range.start()
 9338            } else {
 9339                selection.head()
 9340            }
 9341        } else {
 9342            selection.head()
 9343        };
 9344        let snapshot = self.snapshot(cx);
 9345        loop {
 9346            let diagnostics = if direction == Direction::Prev {
 9347                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9348            } else {
 9349                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9350            }
 9351            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9352            let group = diagnostics
 9353                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9354                // be sorted in a stable way
 9355                // skip until we are at current active diagnostic, if it exists
 9356                .skip_while(|entry| {
 9357                    (match direction {
 9358                        Direction::Prev => entry.range.start >= search_start,
 9359                        Direction::Next => entry.range.start <= search_start,
 9360                    }) && self
 9361                        .active_diagnostics
 9362                        .as_ref()
 9363                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9364                })
 9365                .find_map(|entry| {
 9366                    if entry.diagnostic.is_primary
 9367                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9368                        && !entry.range.is_empty()
 9369                        // if we match with the active diagnostic, skip it
 9370                        && Some(entry.diagnostic.group_id)
 9371                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9372                    {
 9373                        Some((entry.range, entry.diagnostic.group_id))
 9374                    } else {
 9375                        None
 9376                    }
 9377                });
 9378
 9379            if let Some((primary_range, group_id)) = group {
 9380                if self.activate_diagnostics(group_id, cx) {
 9381                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9382                        s.select(vec![Selection {
 9383                            id: selection.id,
 9384                            start: primary_range.start,
 9385                            end: primary_range.start,
 9386                            reversed: false,
 9387                            goal: SelectionGoal::None,
 9388                        }]);
 9389                    });
 9390                }
 9391                break;
 9392            } else {
 9393                // Cycle around to the start of the buffer, potentially moving back to the start of
 9394                // the currently active diagnostic.
 9395                active_primary_range.take();
 9396                if direction == Direction::Prev {
 9397                    if search_start == buffer.len() {
 9398                        break;
 9399                    } else {
 9400                        search_start = buffer.len();
 9401                    }
 9402                } else if search_start == 0 {
 9403                    break;
 9404                } else {
 9405                    search_start = 0;
 9406                }
 9407            }
 9408        }
 9409    }
 9410
 9411    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9412        let snapshot = self
 9413            .display_map
 9414            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9415        let selection = self.selections.newest::<Point>(cx);
 9416        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9417    }
 9418
 9419    fn go_to_hunk_after_position(
 9420        &mut self,
 9421        snapshot: &DisplaySnapshot,
 9422        position: Point,
 9423        cx: &mut ViewContext<'_, Editor>,
 9424    ) -> Option<MultiBufferDiffHunk> {
 9425        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9426            snapshot,
 9427            position,
 9428            false,
 9429            snapshot
 9430                .buffer_snapshot
 9431                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9432            cx,
 9433        ) {
 9434            return Some(hunk);
 9435        }
 9436
 9437        let wrapped_point = Point::zero();
 9438        self.go_to_next_hunk_in_direction(
 9439            snapshot,
 9440            wrapped_point,
 9441            true,
 9442            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9443                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9444            ),
 9445            cx,
 9446        )
 9447    }
 9448
 9449    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9450        let snapshot = self
 9451            .display_map
 9452            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9453        let selection = self.selections.newest::<Point>(cx);
 9454
 9455        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9456    }
 9457
 9458    fn go_to_hunk_before_position(
 9459        &mut self,
 9460        snapshot: &DisplaySnapshot,
 9461        position: Point,
 9462        cx: &mut ViewContext<'_, Editor>,
 9463    ) -> Option<MultiBufferDiffHunk> {
 9464        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9465            snapshot,
 9466            position,
 9467            false,
 9468            snapshot
 9469                .buffer_snapshot
 9470                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9471            cx,
 9472        ) {
 9473            return Some(hunk);
 9474        }
 9475
 9476        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9477        self.go_to_next_hunk_in_direction(
 9478            snapshot,
 9479            wrapped_point,
 9480            true,
 9481            snapshot
 9482                .buffer_snapshot
 9483                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9484            cx,
 9485        )
 9486    }
 9487
 9488    fn go_to_next_hunk_in_direction(
 9489        &mut self,
 9490        snapshot: &DisplaySnapshot,
 9491        initial_point: Point,
 9492        is_wrapped: bool,
 9493        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9494        cx: &mut ViewContext<Editor>,
 9495    ) -> Option<MultiBufferDiffHunk> {
 9496        let display_point = initial_point.to_display_point(snapshot);
 9497        let mut hunks = hunks
 9498            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9499            .filter(|(display_hunk, _)| {
 9500                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9501            })
 9502            .dedup();
 9503
 9504        if let Some((display_hunk, hunk)) = hunks.next() {
 9505            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9506                let row = display_hunk.start_display_row();
 9507                let point = DisplayPoint::new(row, 0);
 9508                s.select_display_ranges([point..point]);
 9509            });
 9510
 9511            Some(hunk)
 9512        } else {
 9513            None
 9514        }
 9515    }
 9516
 9517    pub fn go_to_definition(
 9518        &mut self,
 9519        _: &GoToDefinition,
 9520        cx: &mut ViewContext<Self>,
 9521    ) -> Task<Result<Navigated>> {
 9522        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9523        cx.spawn(|editor, mut cx| async move {
 9524            if definition.await? == Navigated::Yes {
 9525                return Ok(Navigated::Yes);
 9526            }
 9527            match editor.update(&mut cx, |editor, cx| {
 9528                editor.find_all_references(&FindAllReferences, cx)
 9529            })? {
 9530                Some(references) => references.await,
 9531                None => Ok(Navigated::No),
 9532            }
 9533        })
 9534    }
 9535
 9536    pub fn go_to_declaration(
 9537        &mut self,
 9538        _: &GoToDeclaration,
 9539        cx: &mut ViewContext<Self>,
 9540    ) -> Task<Result<Navigated>> {
 9541        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9542    }
 9543
 9544    pub fn go_to_declaration_split(
 9545        &mut self,
 9546        _: &GoToDeclaration,
 9547        cx: &mut ViewContext<Self>,
 9548    ) -> Task<Result<Navigated>> {
 9549        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9550    }
 9551
 9552    pub fn go_to_implementation(
 9553        &mut self,
 9554        _: &GoToImplementation,
 9555        cx: &mut ViewContext<Self>,
 9556    ) -> Task<Result<Navigated>> {
 9557        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9558    }
 9559
 9560    pub fn go_to_implementation_split(
 9561        &mut self,
 9562        _: &GoToImplementationSplit,
 9563        cx: &mut ViewContext<Self>,
 9564    ) -> Task<Result<Navigated>> {
 9565        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9566    }
 9567
 9568    pub fn go_to_type_definition(
 9569        &mut self,
 9570        _: &GoToTypeDefinition,
 9571        cx: &mut ViewContext<Self>,
 9572    ) -> Task<Result<Navigated>> {
 9573        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9574    }
 9575
 9576    pub fn go_to_definition_split(
 9577        &mut self,
 9578        _: &GoToDefinitionSplit,
 9579        cx: &mut ViewContext<Self>,
 9580    ) -> Task<Result<Navigated>> {
 9581        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9582    }
 9583
 9584    pub fn go_to_type_definition_split(
 9585        &mut self,
 9586        _: &GoToTypeDefinitionSplit,
 9587        cx: &mut ViewContext<Self>,
 9588    ) -> Task<Result<Navigated>> {
 9589        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9590    }
 9591
 9592    fn go_to_definition_of_kind(
 9593        &mut self,
 9594        kind: GotoDefinitionKind,
 9595        split: bool,
 9596        cx: &mut ViewContext<Self>,
 9597    ) -> Task<Result<Navigated>> {
 9598        let Some(workspace) = self.workspace() else {
 9599            return Task::ready(Ok(Navigated::No));
 9600        };
 9601        let buffer = self.buffer.read(cx);
 9602        let head = self.selections.newest::<usize>(cx).head();
 9603        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9604            text_anchor
 9605        } else {
 9606            return Task::ready(Ok(Navigated::No));
 9607        };
 9608
 9609        let project = workspace.read(cx).project().clone();
 9610        let definitions = project.update(cx, |project, cx| match kind {
 9611            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 9612            GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
 9613            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 9614            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 9615        });
 9616
 9617        cx.spawn(|editor, mut cx| async move {
 9618            let definitions = definitions.await?;
 9619            let navigated = editor
 9620                .update(&mut cx, |editor, cx| {
 9621                    editor.navigate_to_hover_links(
 9622                        Some(kind),
 9623                        definitions
 9624                            .into_iter()
 9625                            .filter(|location| {
 9626                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9627                            })
 9628                            .map(HoverLink::Text)
 9629                            .collect::<Vec<_>>(),
 9630                        split,
 9631                        cx,
 9632                    )
 9633                })?
 9634                .await?;
 9635            anyhow::Ok(navigated)
 9636        })
 9637    }
 9638
 9639    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9640        let position = self.selections.newest_anchor().head();
 9641        let Some((buffer, buffer_position)) =
 9642            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9643        else {
 9644            return;
 9645        };
 9646
 9647        cx.spawn(|editor, mut cx| async move {
 9648            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9649                editor.update(&mut cx, |_, cx| {
 9650                    cx.open_url(&url);
 9651                })
 9652            } else {
 9653                Ok(())
 9654            }
 9655        })
 9656        .detach();
 9657    }
 9658
 9659    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9660        let Some(workspace) = self.workspace() else {
 9661            return;
 9662        };
 9663
 9664        let position = self.selections.newest_anchor().head();
 9665
 9666        let Some((buffer, buffer_position)) =
 9667            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9668        else {
 9669            return;
 9670        };
 9671
 9672        let Some(project) = self.project.clone() else {
 9673            return;
 9674        };
 9675
 9676        cx.spawn(|_, mut cx| async move {
 9677            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9678
 9679            if let Some((_, path)) = result {
 9680                workspace
 9681                    .update(&mut cx, |workspace, cx| {
 9682                        workspace.open_resolved_path(path, cx)
 9683                    })?
 9684                    .await?;
 9685            }
 9686            anyhow::Ok(())
 9687        })
 9688        .detach();
 9689    }
 9690
 9691    pub(crate) fn navigate_to_hover_links(
 9692        &mut self,
 9693        kind: Option<GotoDefinitionKind>,
 9694        mut definitions: Vec<HoverLink>,
 9695        split: bool,
 9696        cx: &mut ViewContext<Editor>,
 9697    ) -> Task<Result<Navigated>> {
 9698        // If there is one definition, just open it directly
 9699        if definitions.len() == 1 {
 9700            let definition = definitions.pop().unwrap();
 9701
 9702            enum TargetTaskResult {
 9703                Location(Option<Location>),
 9704                AlreadyNavigated,
 9705            }
 9706
 9707            let target_task = match definition {
 9708                HoverLink::Text(link) => {
 9709                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9710                }
 9711                HoverLink::InlayHint(lsp_location, server_id) => {
 9712                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9713                    cx.background_executor().spawn(async move {
 9714                        let location = computation.await?;
 9715                        Ok(TargetTaskResult::Location(location))
 9716                    })
 9717                }
 9718                HoverLink::Url(url) => {
 9719                    cx.open_url(&url);
 9720                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9721                }
 9722                HoverLink::File(path) => {
 9723                    if let Some(workspace) = self.workspace() {
 9724                        cx.spawn(|_, mut cx| async move {
 9725                            workspace
 9726                                .update(&mut cx, |workspace, cx| {
 9727                                    workspace.open_resolved_path(path, cx)
 9728                                })?
 9729                                .await
 9730                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9731                        })
 9732                    } else {
 9733                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9734                    }
 9735                }
 9736            };
 9737            cx.spawn(|editor, mut cx| async move {
 9738                let target = match target_task.await.context("target resolution task")? {
 9739                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9740                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9741                    TargetTaskResult::Location(Some(target)) => target,
 9742                };
 9743
 9744                editor.update(&mut cx, |editor, cx| {
 9745                    let Some(workspace) = editor.workspace() else {
 9746                        return Navigated::No;
 9747                    };
 9748                    let pane = workspace.read(cx).active_pane().clone();
 9749
 9750                    let range = target.range.to_offset(target.buffer.read(cx));
 9751                    let range = editor.range_for_match(&range);
 9752
 9753                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9754                        let buffer = target.buffer.read(cx);
 9755                        let range = check_multiline_range(buffer, range);
 9756                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9757                            s.select_ranges([range]);
 9758                        });
 9759                    } else {
 9760                        cx.window_context().defer(move |cx| {
 9761                            let target_editor: View<Self> =
 9762                                workspace.update(cx, |workspace, cx| {
 9763                                    let pane = if split {
 9764                                        workspace.adjacent_pane(cx)
 9765                                    } else {
 9766                                        workspace.active_pane().clone()
 9767                                    };
 9768
 9769                                    workspace.open_project_item(
 9770                                        pane,
 9771                                        target.buffer.clone(),
 9772                                        true,
 9773                                        true,
 9774                                        cx,
 9775                                    )
 9776                                });
 9777                            target_editor.update(cx, |target_editor, cx| {
 9778                                // When selecting a definition in a different buffer, disable the nav history
 9779                                // to avoid creating a history entry at the previous cursor location.
 9780                                pane.update(cx, |pane, _| pane.disable_history());
 9781                                let buffer = target.buffer.read(cx);
 9782                                let range = check_multiline_range(buffer, range);
 9783                                target_editor.change_selections(
 9784                                    Some(Autoscroll::focused()),
 9785                                    cx,
 9786                                    |s| {
 9787                                        s.select_ranges([range]);
 9788                                    },
 9789                                );
 9790                                pane.update(cx, |pane, _| pane.enable_history());
 9791                            });
 9792                        });
 9793                    }
 9794                    Navigated::Yes
 9795                })
 9796            })
 9797        } else if !definitions.is_empty() {
 9798            cx.spawn(|editor, mut cx| async move {
 9799                let (title, location_tasks, workspace) = editor
 9800                    .update(&mut cx, |editor, cx| {
 9801                        let tab_kind = match kind {
 9802                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9803                            _ => "Definitions",
 9804                        };
 9805                        let title = definitions
 9806                            .iter()
 9807                            .find_map(|definition| match definition {
 9808                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9809                                    let buffer = origin.buffer.read(cx);
 9810                                    format!(
 9811                                        "{} for {}",
 9812                                        tab_kind,
 9813                                        buffer
 9814                                            .text_for_range(origin.range.clone())
 9815                                            .collect::<String>()
 9816                                    )
 9817                                }),
 9818                                HoverLink::InlayHint(_, _) => None,
 9819                                HoverLink::Url(_) => None,
 9820                                HoverLink::File(_) => None,
 9821                            })
 9822                            .unwrap_or(tab_kind.to_string());
 9823                        let location_tasks = definitions
 9824                            .into_iter()
 9825                            .map(|definition| match definition {
 9826                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9827                                HoverLink::InlayHint(lsp_location, server_id) => {
 9828                                    editor.compute_target_location(lsp_location, server_id, cx)
 9829                                }
 9830                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9831                                HoverLink::File(_) => Task::ready(Ok(None)),
 9832                            })
 9833                            .collect::<Vec<_>>();
 9834                        (title, location_tasks, editor.workspace().clone())
 9835                    })
 9836                    .context("location tasks preparation")?;
 9837
 9838                let locations = future::join_all(location_tasks)
 9839                    .await
 9840                    .into_iter()
 9841                    .filter_map(|location| location.transpose())
 9842                    .collect::<Result<_>>()
 9843                    .context("location tasks")?;
 9844
 9845                let Some(workspace) = workspace else {
 9846                    return Ok(Navigated::No);
 9847                };
 9848                let opened = workspace
 9849                    .update(&mut cx, |workspace, cx| {
 9850                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9851                    })
 9852                    .ok();
 9853
 9854                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9855            })
 9856        } else {
 9857            Task::ready(Ok(Navigated::No))
 9858        }
 9859    }
 9860
 9861    fn compute_target_location(
 9862        &self,
 9863        lsp_location: lsp::Location,
 9864        server_id: LanguageServerId,
 9865        cx: &mut ViewContext<Editor>,
 9866    ) -> Task<anyhow::Result<Option<Location>>> {
 9867        let Some(project) = self.project.clone() else {
 9868            return Task::Ready(Some(Ok(None)));
 9869        };
 9870
 9871        cx.spawn(move |editor, mut cx| async move {
 9872            let location_task = editor.update(&mut cx, |editor, cx| {
 9873                project.update(cx, |project, cx| {
 9874                    let language_server_name =
 9875                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9876                            project
 9877                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9878                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9879                        });
 9880                    language_server_name.map(|language_server_name| {
 9881                        project.open_local_buffer_via_lsp(
 9882                            lsp_location.uri.clone(),
 9883                            server_id,
 9884                            language_server_name,
 9885                            cx,
 9886                        )
 9887                    })
 9888                })
 9889            })?;
 9890            let location = match location_task {
 9891                Some(task) => Some({
 9892                    let target_buffer_handle = task.await.context("open local buffer")?;
 9893                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9894                        let target_start = target_buffer
 9895                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9896                        let target_end = target_buffer
 9897                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9898                        target_buffer.anchor_after(target_start)
 9899                            ..target_buffer.anchor_before(target_end)
 9900                    })?;
 9901                    Location {
 9902                        buffer: target_buffer_handle,
 9903                        range,
 9904                    }
 9905                }),
 9906                None => None,
 9907            };
 9908            Ok(location)
 9909        })
 9910    }
 9911
 9912    pub fn find_all_references(
 9913        &mut self,
 9914        _: &FindAllReferences,
 9915        cx: &mut ViewContext<Self>,
 9916    ) -> Option<Task<Result<Navigated>>> {
 9917        let multi_buffer = self.buffer.read(cx);
 9918        let selection = self.selections.newest::<usize>(cx);
 9919        let head = selection.head();
 9920
 9921        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9922        let head_anchor = multi_buffer_snapshot.anchor_at(
 9923            head,
 9924            if head < selection.tail() {
 9925                Bias::Right
 9926            } else {
 9927                Bias::Left
 9928            },
 9929        );
 9930
 9931        match self
 9932            .find_all_references_task_sources
 9933            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9934        {
 9935            Ok(_) => {
 9936                log::info!(
 9937                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9938                );
 9939                return None;
 9940            }
 9941            Err(i) => {
 9942                self.find_all_references_task_sources.insert(i, head_anchor);
 9943            }
 9944        }
 9945
 9946        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9947        let workspace = self.workspace()?;
 9948        let project = workspace.read(cx).project().clone();
 9949        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9950        Some(cx.spawn(|editor, mut cx| async move {
 9951            let _cleanup = defer({
 9952                let mut cx = cx.clone();
 9953                move || {
 9954                    let _ = editor.update(&mut cx, |editor, _| {
 9955                        if let Ok(i) =
 9956                            editor
 9957                                .find_all_references_task_sources
 9958                                .binary_search_by(|anchor| {
 9959                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9960                                })
 9961                        {
 9962                            editor.find_all_references_task_sources.remove(i);
 9963                        }
 9964                    });
 9965                }
 9966            });
 9967
 9968            let locations = references.await?;
 9969            if locations.is_empty() {
 9970                return anyhow::Ok(Navigated::No);
 9971            }
 9972
 9973            workspace.update(&mut cx, |workspace, cx| {
 9974                let title = locations
 9975                    .first()
 9976                    .as_ref()
 9977                    .map(|location| {
 9978                        let buffer = location.buffer.read(cx);
 9979                        format!(
 9980                            "References to `{}`",
 9981                            buffer
 9982                                .text_for_range(location.range.clone())
 9983                                .collect::<String>()
 9984                        )
 9985                    })
 9986                    .unwrap();
 9987                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9988                Navigated::Yes
 9989            })
 9990        }))
 9991    }
 9992
 9993    /// Opens a multibuffer with the given project locations in it
 9994    pub fn open_locations_in_multibuffer(
 9995        workspace: &mut Workspace,
 9996        mut locations: Vec<Location>,
 9997        title: String,
 9998        split: bool,
 9999        cx: &mut ViewContext<Workspace>,
10000    ) {
10001        // If there are multiple definitions, open them in a multibuffer
10002        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10003        let mut locations = locations.into_iter().peekable();
10004        let mut ranges_to_highlight = Vec::new();
10005        let capability = workspace.project().read(cx).capability();
10006
10007        let excerpt_buffer = cx.new_model(|cx| {
10008            let mut multibuffer = MultiBuffer::new(capability);
10009            while let Some(location) = locations.next() {
10010                let buffer = location.buffer.read(cx);
10011                let mut ranges_for_buffer = Vec::new();
10012                let range = location.range.to_offset(buffer);
10013                ranges_for_buffer.push(range.clone());
10014
10015                while let Some(next_location) = locations.peek() {
10016                    if next_location.buffer == location.buffer {
10017                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10018                        locations.next();
10019                    } else {
10020                        break;
10021                    }
10022                }
10023
10024                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10025                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10026                    location.buffer.clone(),
10027                    ranges_for_buffer,
10028                    DEFAULT_MULTIBUFFER_CONTEXT,
10029                    cx,
10030                ))
10031            }
10032
10033            multibuffer.with_title(title)
10034        });
10035
10036        let editor = cx.new_view(|cx| {
10037            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10038        });
10039        editor.update(cx, |editor, cx| {
10040            if let Some(first_range) = ranges_to_highlight.first() {
10041                editor.change_selections(None, cx, |selections| {
10042                    selections.clear_disjoint();
10043                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10044                });
10045            }
10046            editor.highlight_background::<Self>(
10047                &ranges_to_highlight,
10048                |theme| theme.editor_highlighted_line_background,
10049                cx,
10050            );
10051        });
10052
10053        let item = Box::new(editor);
10054        let item_id = item.item_id();
10055
10056        if split {
10057            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10058        } else {
10059            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10060                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10061                    pane.close_current_preview_item(cx)
10062                } else {
10063                    None
10064                }
10065            });
10066            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10067        }
10068        workspace.active_pane().update(cx, |pane, cx| {
10069            pane.set_preview_item_id(Some(item_id), cx);
10070        });
10071    }
10072
10073    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10074        use language::ToOffset as _;
10075
10076        let project = self.project.clone()?;
10077        let selection = self.selections.newest_anchor().clone();
10078        let (cursor_buffer, cursor_buffer_position) = self
10079            .buffer
10080            .read(cx)
10081            .text_anchor_for_position(selection.head(), cx)?;
10082        let (tail_buffer, cursor_buffer_position_end) = self
10083            .buffer
10084            .read(cx)
10085            .text_anchor_for_position(selection.tail(), cx)?;
10086        if tail_buffer != cursor_buffer {
10087            return None;
10088        }
10089
10090        let snapshot = cursor_buffer.read(cx).snapshot();
10091        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10092        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10093        let prepare_rename = project.update(cx, |project, cx| {
10094            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10095        });
10096        drop(snapshot);
10097
10098        Some(cx.spawn(|this, mut cx| async move {
10099            let rename_range = if let Some(range) = prepare_rename.await? {
10100                Some(range)
10101            } else {
10102                this.update(&mut cx, |this, cx| {
10103                    let buffer = this.buffer.read(cx).snapshot(cx);
10104                    let mut buffer_highlights = this
10105                        .document_highlights_for_position(selection.head(), &buffer)
10106                        .filter(|highlight| {
10107                            highlight.start.excerpt_id == selection.head().excerpt_id
10108                                && highlight.end.excerpt_id == selection.head().excerpt_id
10109                        });
10110                    buffer_highlights
10111                        .next()
10112                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10113                })?
10114            };
10115            if let Some(rename_range) = rename_range {
10116                this.update(&mut cx, |this, cx| {
10117                    let snapshot = cursor_buffer.read(cx).snapshot();
10118                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10119                    let cursor_offset_in_rename_range =
10120                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10121                    let cursor_offset_in_rename_range_end =
10122                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10123
10124                    this.take_rename(false, cx);
10125                    let buffer = this.buffer.read(cx).read(cx);
10126                    let cursor_offset = selection.head().to_offset(&buffer);
10127                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10128                    let rename_end = rename_start + rename_buffer_range.len();
10129                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10130                    let mut old_highlight_id = None;
10131                    let old_name: Arc<str> = buffer
10132                        .chunks(rename_start..rename_end, true)
10133                        .map(|chunk| {
10134                            if old_highlight_id.is_none() {
10135                                old_highlight_id = chunk.syntax_highlight_id;
10136                            }
10137                            chunk.text
10138                        })
10139                        .collect::<String>()
10140                        .into();
10141
10142                    drop(buffer);
10143
10144                    // Position the selection in the rename editor so that it matches the current selection.
10145                    this.show_local_selections = false;
10146                    let rename_editor = cx.new_view(|cx| {
10147                        let mut editor = Editor::single_line(cx);
10148                        editor.buffer.update(cx, |buffer, cx| {
10149                            buffer.edit([(0..0, old_name.clone())], None, cx)
10150                        });
10151                        let rename_selection_range = match cursor_offset_in_rename_range
10152                            .cmp(&cursor_offset_in_rename_range_end)
10153                        {
10154                            Ordering::Equal => {
10155                                editor.select_all(&SelectAll, cx);
10156                                return editor;
10157                            }
10158                            Ordering::Less => {
10159                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10160                            }
10161                            Ordering::Greater => {
10162                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10163                            }
10164                        };
10165                        if rename_selection_range.end > old_name.len() {
10166                            editor.select_all(&SelectAll, cx);
10167                        } else {
10168                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10169                                s.select_ranges([rename_selection_range]);
10170                            });
10171                        }
10172                        editor
10173                    });
10174                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10175                        if e == &EditorEvent::Focused {
10176                            cx.emit(EditorEvent::FocusedIn)
10177                        }
10178                    })
10179                    .detach();
10180
10181                    let write_highlights =
10182                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10183                    let read_highlights =
10184                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10185                    let ranges = write_highlights
10186                        .iter()
10187                        .flat_map(|(_, ranges)| ranges.iter())
10188                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10189                        .cloned()
10190                        .collect();
10191
10192                    this.highlight_text::<Rename>(
10193                        ranges,
10194                        HighlightStyle {
10195                            fade_out: Some(0.6),
10196                            ..Default::default()
10197                        },
10198                        cx,
10199                    );
10200                    let rename_focus_handle = rename_editor.focus_handle(cx);
10201                    cx.focus(&rename_focus_handle);
10202                    let block_id = this.insert_blocks(
10203                        [BlockProperties {
10204                            style: BlockStyle::Flex,
10205                            position: range.start,
10206                            height: 1,
10207                            render: Box::new({
10208                                let rename_editor = rename_editor.clone();
10209                                move |cx: &mut BlockContext| {
10210                                    let mut text_style = cx.editor_style.text.clone();
10211                                    if let Some(highlight_style) = old_highlight_id
10212                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10213                                    {
10214                                        text_style = text_style.highlight(highlight_style);
10215                                    }
10216                                    div()
10217                                        .pl(cx.anchor_x)
10218                                        .child(EditorElement::new(
10219                                            &rename_editor,
10220                                            EditorStyle {
10221                                                background: cx.theme().system().transparent,
10222                                                local_player: cx.editor_style.local_player,
10223                                                text: text_style,
10224                                                scrollbar_width: cx.editor_style.scrollbar_width,
10225                                                syntax: cx.editor_style.syntax.clone(),
10226                                                status: cx.editor_style.status.clone(),
10227                                                inlay_hints_style: HighlightStyle {
10228                                                    font_weight: Some(FontWeight::BOLD),
10229                                                    ..make_inlay_hints_style(cx)
10230                                                },
10231                                                suggestions_style: HighlightStyle {
10232                                                    color: Some(cx.theme().status().predictive),
10233                                                    ..HighlightStyle::default()
10234                                                },
10235                                                ..EditorStyle::default()
10236                                            },
10237                                        ))
10238                                        .into_any_element()
10239                                }
10240                            }),
10241                            disposition: BlockDisposition::Below,
10242                            priority: 0,
10243                        }],
10244                        Some(Autoscroll::fit()),
10245                        cx,
10246                    )[0];
10247                    this.pending_rename = Some(RenameState {
10248                        range,
10249                        old_name,
10250                        editor: rename_editor,
10251                        block_id,
10252                    });
10253                })?;
10254            }
10255
10256            Ok(())
10257        }))
10258    }
10259
10260    pub fn confirm_rename(
10261        &mut self,
10262        _: &ConfirmRename,
10263        cx: &mut ViewContext<Self>,
10264    ) -> Option<Task<Result<()>>> {
10265        let rename = self.take_rename(false, cx)?;
10266        let workspace = self.workspace()?;
10267        let (start_buffer, start) = self
10268            .buffer
10269            .read(cx)
10270            .text_anchor_for_position(rename.range.start, cx)?;
10271        let (end_buffer, end) = self
10272            .buffer
10273            .read(cx)
10274            .text_anchor_for_position(rename.range.end, cx)?;
10275        if start_buffer != end_buffer {
10276            return None;
10277        }
10278
10279        let buffer = start_buffer;
10280        let range = start..end;
10281        let old_name = rename.old_name;
10282        let new_name = rename.editor.read(cx).text(cx);
10283
10284        let rename = workspace
10285            .read(cx)
10286            .project()
10287            .clone()
10288            .update(cx, |project, cx| {
10289                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10290            });
10291        let workspace = workspace.downgrade();
10292
10293        Some(cx.spawn(|editor, mut cx| async move {
10294            let project_transaction = rename.await?;
10295            Self::open_project_transaction(
10296                &editor,
10297                workspace,
10298                project_transaction,
10299                format!("Rename: {}{}", old_name, new_name),
10300                cx.clone(),
10301            )
10302            .await?;
10303
10304            editor.update(&mut cx, |editor, cx| {
10305                editor.refresh_document_highlights(cx);
10306            })?;
10307            Ok(())
10308        }))
10309    }
10310
10311    fn take_rename(
10312        &mut self,
10313        moving_cursor: bool,
10314        cx: &mut ViewContext<Self>,
10315    ) -> Option<RenameState> {
10316        let rename = self.pending_rename.take()?;
10317        if rename.editor.focus_handle(cx).is_focused(cx) {
10318            cx.focus(&self.focus_handle);
10319        }
10320
10321        self.remove_blocks(
10322            [rename.block_id].into_iter().collect(),
10323            Some(Autoscroll::fit()),
10324            cx,
10325        );
10326        self.clear_highlights::<Rename>(cx);
10327        self.show_local_selections = true;
10328
10329        if moving_cursor {
10330            let rename_editor = rename.editor.read(cx);
10331            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10332
10333            // Update the selection to match the position of the selection inside
10334            // the rename editor.
10335            let snapshot = self.buffer.read(cx).read(cx);
10336            let rename_range = rename.range.to_offset(&snapshot);
10337            let cursor_in_editor = snapshot
10338                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10339                .min(rename_range.end);
10340            drop(snapshot);
10341
10342            self.change_selections(None, cx, |s| {
10343                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10344            });
10345        } else {
10346            self.refresh_document_highlights(cx);
10347        }
10348
10349        Some(rename)
10350    }
10351
10352    pub fn pending_rename(&self) -> Option<&RenameState> {
10353        self.pending_rename.as_ref()
10354    }
10355
10356    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10357        let project = match &self.project {
10358            Some(project) => project.clone(),
10359            None => return None,
10360        };
10361
10362        Some(self.perform_format(project, FormatTrigger::Manual, cx))
10363    }
10364
10365    fn perform_format(
10366        &mut self,
10367        project: Model<Project>,
10368        trigger: FormatTrigger,
10369        cx: &mut ViewContext<Self>,
10370    ) -> Task<Result<()>> {
10371        let buffer = self.buffer().clone();
10372        let mut buffers = buffer.read(cx).all_buffers();
10373        if trigger == FormatTrigger::Save {
10374            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10375        }
10376
10377        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10378        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10379
10380        cx.spawn(|_, mut cx| async move {
10381            let transaction = futures::select_biased! {
10382                () = timeout => {
10383                    log::warn!("timed out waiting for formatting");
10384                    None
10385                }
10386                transaction = format.log_err().fuse() => transaction,
10387            };
10388
10389            buffer
10390                .update(&mut cx, |buffer, cx| {
10391                    if let Some(transaction) = transaction {
10392                        if !buffer.is_singleton() {
10393                            buffer.push_transaction(&transaction.0, cx);
10394                        }
10395                    }
10396
10397                    cx.notify();
10398                })
10399                .ok();
10400
10401            Ok(())
10402        })
10403    }
10404
10405    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10406        if let Some(project) = self.project.clone() {
10407            self.buffer.update(cx, |multi_buffer, cx| {
10408                project.update(cx, |project, cx| {
10409                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10410                });
10411            })
10412        }
10413    }
10414
10415    fn cancel_language_server_work(
10416        &mut self,
10417        _: &CancelLanguageServerWork,
10418        cx: &mut ViewContext<Self>,
10419    ) {
10420        if let Some(project) = self.project.clone() {
10421            self.buffer.update(cx, |multi_buffer, cx| {
10422                project.update(cx, |project, cx| {
10423                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10424                });
10425            })
10426        }
10427    }
10428
10429    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10430        cx.show_character_palette();
10431    }
10432
10433    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10434        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10435            let buffer = self.buffer.read(cx).snapshot(cx);
10436            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10437            let is_valid = buffer
10438                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10439                .any(|entry| {
10440                    entry.diagnostic.is_primary
10441                        && !entry.range.is_empty()
10442                        && entry.range.start == primary_range_start
10443                        && entry.diagnostic.message == active_diagnostics.primary_message
10444                });
10445
10446            if is_valid != active_diagnostics.is_valid {
10447                active_diagnostics.is_valid = is_valid;
10448                let mut new_styles = HashMap::default();
10449                for (block_id, diagnostic) in &active_diagnostics.blocks {
10450                    new_styles.insert(
10451                        *block_id,
10452                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10453                    );
10454                }
10455                self.display_map.update(cx, |display_map, _cx| {
10456                    display_map.replace_blocks(new_styles)
10457                });
10458            }
10459        }
10460    }
10461
10462    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10463        self.dismiss_diagnostics(cx);
10464        let snapshot = self.snapshot(cx);
10465        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10466            let buffer = self.buffer.read(cx).snapshot(cx);
10467
10468            let mut primary_range = None;
10469            let mut primary_message = None;
10470            let mut group_end = Point::zero();
10471            let diagnostic_group = buffer
10472                .diagnostic_group::<MultiBufferPoint>(group_id)
10473                .filter_map(|entry| {
10474                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10475                        && (entry.range.start.row == entry.range.end.row
10476                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10477                    {
10478                        return None;
10479                    }
10480                    if entry.range.end > group_end {
10481                        group_end = entry.range.end;
10482                    }
10483                    if entry.diagnostic.is_primary {
10484                        primary_range = Some(entry.range.clone());
10485                        primary_message = Some(entry.diagnostic.message.clone());
10486                    }
10487                    Some(entry)
10488                })
10489                .collect::<Vec<_>>();
10490            let primary_range = primary_range?;
10491            let primary_message = primary_message?;
10492            let primary_range =
10493                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10494
10495            let blocks = display_map
10496                .insert_blocks(
10497                    diagnostic_group.iter().map(|entry| {
10498                        let diagnostic = entry.diagnostic.clone();
10499                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10500                        BlockProperties {
10501                            style: BlockStyle::Fixed,
10502                            position: buffer.anchor_after(entry.range.start),
10503                            height: message_height,
10504                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10505                            disposition: BlockDisposition::Below,
10506                            priority: 0,
10507                        }
10508                    }),
10509                    cx,
10510                )
10511                .into_iter()
10512                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10513                .collect();
10514
10515            Some(ActiveDiagnosticGroup {
10516                primary_range,
10517                primary_message,
10518                group_id,
10519                blocks,
10520                is_valid: true,
10521            })
10522        });
10523        self.active_diagnostics.is_some()
10524    }
10525
10526    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10527        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10528            self.display_map.update(cx, |display_map, cx| {
10529                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10530            });
10531            cx.notify();
10532        }
10533    }
10534
10535    pub fn set_selections_from_remote(
10536        &mut self,
10537        selections: Vec<Selection<Anchor>>,
10538        pending_selection: Option<Selection<Anchor>>,
10539        cx: &mut ViewContext<Self>,
10540    ) {
10541        let old_cursor_position = self.selections.newest_anchor().head();
10542        self.selections.change_with(cx, |s| {
10543            s.select_anchors(selections);
10544            if let Some(pending_selection) = pending_selection {
10545                s.set_pending(pending_selection, SelectMode::Character);
10546            } else {
10547                s.clear_pending();
10548            }
10549        });
10550        self.selections_did_change(false, &old_cursor_position, true, cx);
10551    }
10552
10553    fn push_to_selection_history(&mut self) {
10554        self.selection_history.push(SelectionHistoryEntry {
10555            selections: self.selections.disjoint_anchors(),
10556            select_next_state: self.select_next_state.clone(),
10557            select_prev_state: self.select_prev_state.clone(),
10558            add_selections_state: self.add_selections_state.clone(),
10559        });
10560    }
10561
10562    pub fn transact(
10563        &mut self,
10564        cx: &mut ViewContext<Self>,
10565        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10566    ) -> Option<TransactionId> {
10567        self.start_transaction_at(Instant::now(), cx);
10568        update(self, cx);
10569        self.end_transaction_at(Instant::now(), cx)
10570    }
10571
10572    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10573        self.end_selection(cx);
10574        if let Some(tx_id) = self
10575            .buffer
10576            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10577        {
10578            self.selection_history
10579                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10580            cx.emit(EditorEvent::TransactionBegun {
10581                transaction_id: tx_id,
10582            })
10583        }
10584    }
10585
10586    fn end_transaction_at(
10587        &mut self,
10588        now: Instant,
10589        cx: &mut ViewContext<Self>,
10590    ) -> Option<TransactionId> {
10591        if let Some(transaction_id) = self
10592            .buffer
10593            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10594        {
10595            if let Some((_, end_selections)) =
10596                self.selection_history.transaction_mut(transaction_id)
10597            {
10598                *end_selections = Some(self.selections.disjoint_anchors());
10599            } else {
10600                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10601            }
10602
10603            cx.emit(EditorEvent::Edited { transaction_id });
10604            Some(transaction_id)
10605        } else {
10606            None
10607        }
10608    }
10609
10610    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10611        let selection = self.selections.newest::<Point>(cx);
10612
10613        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10614        let range = if selection.is_empty() {
10615            let point = selection.head().to_display_point(&display_map);
10616            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10617            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10618                .to_point(&display_map);
10619            start..end
10620        } else {
10621            selection.range()
10622        };
10623        if display_map.folds_in_range(range).next().is_some() {
10624            self.unfold_lines(&Default::default(), cx)
10625        } else {
10626            self.fold(&Default::default(), cx)
10627        }
10628    }
10629
10630    pub fn toggle_fold_recursive(
10631        &mut self,
10632        _: &actions::ToggleFoldRecursive,
10633        cx: &mut ViewContext<Self>,
10634    ) {
10635        let selection = self.selections.newest::<Point>(cx);
10636
10637        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10638        let range = if selection.is_empty() {
10639            let point = selection.head().to_display_point(&display_map);
10640            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10641            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10642                .to_point(&display_map);
10643            start..end
10644        } else {
10645            selection.range()
10646        };
10647        if display_map.folds_in_range(range).next().is_some() {
10648            self.unfold_recursive(&Default::default(), cx)
10649        } else {
10650            self.fold_recursive(&Default::default(), cx)
10651        }
10652    }
10653
10654    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10655        let mut fold_ranges = Vec::new();
10656        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10657        let selections = self.selections.all_adjusted(cx);
10658
10659        for selection in selections {
10660            let range = selection.range().sorted();
10661            let buffer_start_row = range.start.row;
10662
10663            if range.start.row != range.end.row {
10664                let mut found = false;
10665                let mut row = range.start.row;
10666                while row <= range.end.row {
10667                    if let Some((foldable_range, fold_text)) =
10668                        { display_map.foldable_range(MultiBufferRow(row)) }
10669                    {
10670                        found = true;
10671                        row = foldable_range.end.row + 1;
10672                        fold_ranges.push((foldable_range, fold_text));
10673                    } else {
10674                        row += 1
10675                    }
10676                }
10677                if found {
10678                    continue;
10679                }
10680            }
10681
10682            for row in (0..=range.start.row).rev() {
10683                if let Some((foldable_range, fold_text)) =
10684                    display_map.foldable_range(MultiBufferRow(row))
10685                {
10686                    if foldable_range.end.row >= buffer_start_row {
10687                        fold_ranges.push((foldable_range, fold_text));
10688                        if row <= range.start.row {
10689                            break;
10690                        }
10691                    }
10692                }
10693            }
10694        }
10695
10696        self.fold_ranges(fold_ranges, true, cx);
10697    }
10698
10699    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10700        let mut fold_ranges = Vec::new();
10701        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10702
10703        for row in 0..display_map.max_buffer_row().0 {
10704            if let Some((foldable_range, fold_text)) =
10705                display_map.foldable_range(MultiBufferRow(row))
10706            {
10707                fold_ranges.push((foldable_range, fold_text));
10708            }
10709        }
10710
10711        self.fold_ranges(fold_ranges, true, cx);
10712    }
10713
10714    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10715        let mut fold_ranges = Vec::new();
10716        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10717        let selections = self.selections.all_adjusted(cx);
10718
10719        for selection in selections {
10720            let range = selection.range().sorted();
10721            let buffer_start_row = range.start.row;
10722
10723            if range.start.row != range.end.row {
10724                let mut found = false;
10725                for row in range.start.row..=range.end.row {
10726                    if let Some((foldable_range, fold_text)) =
10727                        { display_map.foldable_range(MultiBufferRow(row)) }
10728                    {
10729                        found = true;
10730                        fold_ranges.push((foldable_range, fold_text));
10731                    }
10732                }
10733                if found {
10734                    continue;
10735                }
10736            }
10737
10738            for row in (0..=range.start.row).rev() {
10739                if let Some((foldable_range, fold_text)) =
10740                    display_map.foldable_range(MultiBufferRow(row))
10741                {
10742                    if foldable_range.end.row >= buffer_start_row {
10743                        fold_ranges.push((foldable_range, fold_text));
10744                    } else {
10745                        break;
10746                    }
10747                }
10748            }
10749        }
10750
10751        self.fold_ranges(fold_ranges, true, cx);
10752    }
10753
10754    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10755        let buffer_row = fold_at.buffer_row;
10756        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10757
10758        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10759            let autoscroll = self
10760                .selections
10761                .all::<Point>(cx)
10762                .iter()
10763                .any(|selection| fold_range.overlaps(&selection.range()));
10764
10765            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10766        }
10767    }
10768
10769    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10770        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10771        let buffer = &display_map.buffer_snapshot;
10772        let selections = self.selections.all::<Point>(cx);
10773        let ranges = selections
10774            .iter()
10775            .map(|s| {
10776                let range = s.display_range(&display_map).sorted();
10777                let mut start = range.start.to_point(&display_map);
10778                let mut end = range.end.to_point(&display_map);
10779                start.column = 0;
10780                end.column = buffer.line_len(MultiBufferRow(end.row));
10781                start..end
10782            })
10783            .collect::<Vec<_>>();
10784
10785        self.unfold_ranges(ranges, true, true, cx);
10786    }
10787
10788    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10789        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10790        let selections = self.selections.all::<Point>(cx);
10791        let ranges = selections
10792            .iter()
10793            .map(|s| {
10794                let mut range = s.display_range(&display_map).sorted();
10795                *range.start.column_mut() = 0;
10796                *range.end.column_mut() = display_map.line_len(range.end.row());
10797                let start = range.start.to_point(&display_map);
10798                let end = range.end.to_point(&display_map);
10799                start..end
10800            })
10801            .collect::<Vec<_>>();
10802
10803        self.unfold_ranges(ranges, true, true, cx);
10804    }
10805
10806    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10807        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10808
10809        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10810            ..Point::new(
10811                unfold_at.buffer_row.0,
10812                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10813            );
10814
10815        let autoscroll = self
10816            .selections
10817            .all::<Point>(cx)
10818            .iter()
10819            .any(|selection| selection.range().overlaps(&intersection_range));
10820
10821        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10822    }
10823
10824    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10825        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10826        self.unfold_ranges(
10827            [Point::zero()..display_map.max_point().to_point(&display_map)],
10828            true,
10829            true,
10830            cx,
10831        );
10832    }
10833
10834    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10835        let selections = self.selections.all::<Point>(cx);
10836        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10837        let line_mode = self.selections.line_mode;
10838        let ranges = selections.into_iter().map(|s| {
10839            if line_mode {
10840                let start = Point::new(s.start.row, 0);
10841                let end = Point::new(
10842                    s.end.row,
10843                    display_map
10844                        .buffer_snapshot
10845                        .line_len(MultiBufferRow(s.end.row)),
10846                );
10847                (start..end, display_map.fold_placeholder.clone())
10848            } else {
10849                (s.start..s.end, display_map.fold_placeholder.clone())
10850            }
10851        });
10852        self.fold_ranges(ranges, true, cx);
10853    }
10854
10855    pub fn fold_ranges<T: ToOffset + Clone>(
10856        &mut self,
10857        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10858        auto_scroll: bool,
10859        cx: &mut ViewContext<Self>,
10860    ) {
10861        let mut fold_ranges = Vec::new();
10862        let mut buffers_affected = HashMap::default();
10863        let multi_buffer = self.buffer().read(cx);
10864        for (fold_range, fold_text) in ranges {
10865            if let Some((_, buffer, _)) =
10866                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10867            {
10868                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10869            };
10870            fold_ranges.push((fold_range, fold_text));
10871        }
10872
10873        let mut ranges = fold_ranges.into_iter().peekable();
10874        if ranges.peek().is_some() {
10875            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10876
10877            if auto_scroll {
10878                self.request_autoscroll(Autoscroll::fit(), cx);
10879            }
10880
10881            for buffer in buffers_affected.into_values() {
10882                self.sync_expanded_diff_hunks(buffer, cx);
10883            }
10884
10885            cx.notify();
10886
10887            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10888                // Clear diagnostics block when folding a range that contains it.
10889                let snapshot = self.snapshot(cx);
10890                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10891                    drop(snapshot);
10892                    self.active_diagnostics = Some(active_diagnostics);
10893                    self.dismiss_diagnostics(cx);
10894                } else {
10895                    self.active_diagnostics = Some(active_diagnostics);
10896                }
10897            }
10898
10899            self.scrollbar_marker_state.dirty = true;
10900        }
10901    }
10902
10903    pub fn unfold_ranges<T: ToOffset + Clone>(
10904        &mut self,
10905        ranges: impl IntoIterator<Item = Range<T>>,
10906        inclusive: bool,
10907        auto_scroll: bool,
10908        cx: &mut ViewContext<Self>,
10909    ) {
10910        let mut unfold_ranges = Vec::new();
10911        let mut buffers_affected = HashMap::default();
10912        let multi_buffer = self.buffer().read(cx);
10913        for range in ranges {
10914            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10915                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10916            };
10917            unfold_ranges.push(range);
10918        }
10919
10920        let mut ranges = unfold_ranges.into_iter().peekable();
10921        if ranges.peek().is_some() {
10922            self.display_map
10923                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10924            if auto_scroll {
10925                self.request_autoscroll(Autoscroll::fit(), cx);
10926            }
10927
10928            for buffer in buffers_affected.into_values() {
10929                self.sync_expanded_diff_hunks(buffer, cx);
10930            }
10931
10932            cx.notify();
10933            self.scrollbar_marker_state.dirty = true;
10934            self.active_indent_guides_state.dirty = true;
10935        }
10936    }
10937
10938    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10939        self.display_map.read(cx).fold_placeholder.clone()
10940    }
10941
10942    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10943        if hovered != self.gutter_hovered {
10944            self.gutter_hovered = hovered;
10945            cx.notify();
10946        }
10947    }
10948
10949    pub fn insert_blocks(
10950        &mut self,
10951        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10952        autoscroll: Option<Autoscroll>,
10953        cx: &mut ViewContext<Self>,
10954    ) -> Vec<CustomBlockId> {
10955        let blocks = self
10956            .display_map
10957            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10958        if let Some(autoscroll) = autoscroll {
10959            self.request_autoscroll(autoscroll, cx);
10960        }
10961        cx.notify();
10962        blocks
10963    }
10964
10965    pub fn resize_blocks(
10966        &mut self,
10967        heights: HashMap<CustomBlockId, u32>,
10968        autoscroll: Option<Autoscroll>,
10969        cx: &mut ViewContext<Self>,
10970    ) {
10971        self.display_map
10972            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10973        if let Some(autoscroll) = autoscroll {
10974            self.request_autoscroll(autoscroll, cx);
10975        }
10976        cx.notify();
10977    }
10978
10979    pub fn replace_blocks(
10980        &mut self,
10981        renderers: HashMap<CustomBlockId, RenderBlock>,
10982        autoscroll: Option<Autoscroll>,
10983        cx: &mut ViewContext<Self>,
10984    ) {
10985        self.display_map
10986            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10987        if let Some(autoscroll) = autoscroll {
10988            self.request_autoscroll(autoscroll, cx);
10989        }
10990        cx.notify();
10991    }
10992
10993    pub fn remove_blocks(
10994        &mut self,
10995        block_ids: HashSet<CustomBlockId>,
10996        autoscroll: Option<Autoscroll>,
10997        cx: &mut ViewContext<Self>,
10998    ) {
10999        self.display_map.update(cx, |display_map, cx| {
11000            display_map.remove_blocks(block_ids, cx)
11001        });
11002        if let Some(autoscroll) = autoscroll {
11003            self.request_autoscroll(autoscroll, cx);
11004        }
11005        cx.notify();
11006    }
11007
11008    pub fn row_for_block(
11009        &self,
11010        block_id: CustomBlockId,
11011        cx: &mut ViewContext<Self>,
11012    ) -> Option<DisplayRow> {
11013        self.display_map
11014            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11015    }
11016
11017    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11018        self.focused_block = Some(focused_block);
11019    }
11020
11021    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11022        self.focused_block.take()
11023    }
11024
11025    pub fn insert_creases(
11026        &mut self,
11027        creases: impl IntoIterator<Item = Crease>,
11028        cx: &mut ViewContext<Self>,
11029    ) -> Vec<CreaseId> {
11030        self.display_map
11031            .update(cx, |map, cx| map.insert_creases(creases, cx))
11032    }
11033
11034    pub fn remove_creases(
11035        &mut self,
11036        ids: impl IntoIterator<Item = CreaseId>,
11037        cx: &mut ViewContext<Self>,
11038    ) {
11039        self.display_map
11040            .update(cx, |map, cx| map.remove_creases(ids, cx));
11041    }
11042
11043    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11044        self.display_map
11045            .update(cx, |map, cx| map.snapshot(cx))
11046            .longest_row()
11047    }
11048
11049    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11050        self.display_map
11051            .update(cx, |map, cx| map.snapshot(cx))
11052            .max_point()
11053    }
11054
11055    pub fn text(&self, cx: &AppContext) -> String {
11056        self.buffer.read(cx).read(cx).text()
11057    }
11058
11059    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11060        let text = self.text(cx);
11061        let text = text.trim();
11062
11063        if text.is_empty() {
11064            return None;
11065        }
11066
11067        Some(text.to_string())
11068    }
11069
11070    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11071        self.transact(cx, |this, cx| {
11072            this.buffer
11073                .read(cx)
11074                .as_singleton()
11075                .expect("you can only call set_text on editors for singleton buffers")
11076                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11077        });
11078    }
11079
11080    pub fn display_text(&self, cx: &mut AppContext) -> String {
11081        self.display_map
11082            .update(cx, |map, cx| map.snapshot(cx))
11083            .text()
11084    }
11085
11086    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11087        let mut wrap_guides = smallvec::smallvec![];
11088
11089        if self.show_wrap_guides == Some(false) {
11090            return wrap_guides;
11091        }
11092
11093        let settings = self.buffer.read(cx).settings_at(0, cx);
11094        if settings.show_wrap_guides {
11095            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11096                wrap_guides.push((soft_wrap as usize, true));
11097            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11098                wrap_guides.push((soft_wrap as usize, true));
11099            }
11100            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11101        }
11102
11103        wrap_guides
11104    }
11105
11106    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11107        let settings = self.buffer.read(cx).settings_at(0, cx);
11108        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11109        match mode {
11110            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11111                SoftWrap::None
11112            }
11113            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11114            language_settings::SoftWrap::PreferredLineLength => {
11115                SoftWrap::Column(settings.preferred_line_length)
11116            }
11117            language_settings::SoftWrap::Bounded => {
11118                SoftWrap::Bounded(settings.preferred_line_length)
11119            }
11120        }
11121    }
11122
11123    pub fn set_soft_wrap_mode(
11124        &mut self,
11125        mode: language_settings::SoftWrap,
11126        cx: &mut ViewContext<Self>,
11127    ) {
11128        self.soft_wrap_mode_override = Some(mode);
11129        cx.notify();
11130    }
11131
11132    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11133        let rem_size = cx.rem_size();
11134        self.display_map.update(cx, |map, cx| {
11135            map.set_font(
11136                style.text.font(),
11137                style.text.font_size.to_pixels(rem_size),
11138                cx,
11139            )
11140        });
11141        self.style = Some(style);
11142    }
11143
11144    pub fn style(&self) -> Option<&EditorStyle> {
11145        self.style.as_ref()
11146    }
11147
11148    // Called by the element. This method is not designed to be called outside of the editor
11149    // element's layout code because it does not notify when rewrapping is computed synchronously.
11150    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11151        self.display_map
11152            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11153    }
11154
11155    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11156        if self.soft_wrap_mode_override.is_some() {
11157            self.soft_wrap_mode_override.take();
11158        } else {
11159            let soft_wrap = match self.soft_wrap_mode(cx) {
11160                SoftWrap::GitDiff => return,
11161                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11162                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11163                    language_settings::SoftWrap::None
11164                }
11165            };
11166            self.soft_wrap_mode_override = Some(soft_wrap);
11167        }
11168        cx.notify();
11169    }
11170
11171    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11172        let Some(workspace) = self.workspace() else {
11173            return;
11174        };
11175        let fs = workspace.read(cx).app_state().fs.clone();
11176        let current_show = TabBarSettings::get_global(cx).show;
11177        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11178            setting.show = Some(!current_show);
11179        });
11180    }
11181
11182    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11183        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11184            self.buffer
11185                .read(cx)
11186                .settings_at(0, cx)
11187                .indent_guides
11188                .enabled
11189        });
11190        self.show_indent_guides = Some(!currently_enabled);
11191        cx.notify();
11192    }
11193
11194    fn should_show_indent_guides(&self) -> Option<bool> {
11195        self.show_indent_guides
11196    }
11197
11198    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11199        let mut editor_settings = EditorSettings::get_global(cx).clone();
11200        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11201        EditorSettings::override_global(editor_settings, cx);
11202    }
11203
11204    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11205        self.use_relative_line_numbers
11206            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11207    }
11208
11209    pub fn toggle_relative_line_numbers(
11210        &mut self,
11211        _: &ToggleRelativeLineNumbers,
11212        cx: &mut ViewContext<Self>,
11213    ) {
11214        let is_relative = self.should_use_relative_line_numbers(cx);
11215        self.set_relative_line_number(Some(!is_relative), cx)
11216    }
11217
11218    pub fn set_relative_line_number(
11219        &mut self,
11220        is_relative: Option<bool>,
11221        cx: &mut ViewContext<Self>,
11222    ) {
11223        self.use_relative_line_numbers = is_relative;
11224        cx.notify();
11225    }
11226
11227    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11228        self.show_gutter = show_gutter;
11229        cx.notify();
11230    }
11231
11232    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11233        self.show_line_numbers = Some(show_line_numbers);
11234        cx.notify();
11235    }
11236
11237    pub fn set_show_git_diff_gutter(
11238        &mut self,
11239        show_git_diff_gutter: bool,
11240        cx: &mut ViewContext<Self>,
11241    ) {
11242        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11243        cx.notify();
11244    }
11245
11246    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11247        self.show_code_actions = Some(show_code_actions);
11248        cx.notify();
11249    }
11250
11251    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11252        self.show_runnables = Some(show_runnables);
11253        cx.notify();
11254    }
11255
11256    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11257        if self.display_map.read(cx).masked != masked {
11258            self.display_map.update(cx, |map, _| map.masked = masked);
11259        }
11260        cx.notify()
11261    }
11262
11263    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11264        self.show_wrap_guides = Some(show_wrap_guides);
11265        cx.notify();
11266    }
11267
11268    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11269        self.show_indent_guides = Some(show_indent_guides);
11270        cx.notify();
11271    }
11272
11273    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11274        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11275            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11276                if let Some(dir) = file.abs_path(cx).parent() {
11277                    return Some(dir.to_owned());
11278                }
11279            }
11280
11281            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11282                return Some(project_path.path.to_path_buf());
11283            }
11284        }
11285
11286        None
11287    }
11288
11289    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11290        self.active_excerpt(cx)?
11291            .1
11292            .read(cx)
11293            .file()
11294            .and_then(|f| f.as_local())
11295    }
11296
11297    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11298        if let Some(target) = self.target_file(cx) {
11299            cx.reveal_path(&target.abs_path(cx));
11300        }
11301    }
11302
11303    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11304        if let Some(file) = self.target_file(cx) {
11305            if let Some(path) = file.abs_path(cx).to_str() {
11306                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11307            }
11308        }
11309    }
11310
11311    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11312        if let Some(file) = self.target_file(cx) {
11313            if let Some(path) = file.path().to_str() {
11314                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11315            }
11316        }
11317    }
11318
11319    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11320        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11321
11322        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11323            self.start_git_blame(true, cx);
11324        }
11325
11326        cx.notify();
11327    }
11328
11329    pub fn toggle_git_blame_inline(
11330        &mut self,
11331        _: &ToggleGitBlameInline,
11332        cx: &mut ViewContext<Self>,
11333    ) {
11334        self.toggle_git_blame_inline_internal(true, cx);
11335        cx.notify();
11336    }
11337
11338    pub fn git_blame_inline_enabled(&self) -> bool {
11339        self.git_blame_inline_enabled
11340    }
11341
11342    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11343        self.show_selection_menu = self
11344            .show_selection_menu
11345            .map(|show_selections_menu| !show_selections_menu)
11346            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11347
11348        cx.notify();
11349    }
11350
11351    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11352        self.show_selection_menu
11353            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11354    }
11355
11356    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11357        if let Some(project) = self.project.as_ref() {
11358            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11359                return;
11360            };
11361
11362            if buffer.read(cx).file().is_none() {
11363                return;
11364            }
11365
11366            let focused = self.focus_handle(cx).contains_focused(cx);
11367
11368            let project = project.clone();
11369            let blame =
11370                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11371            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11372            self.blame = Some(blame);
11373        }
11374    }
11375
11376    fn toggle_git_blame_inline_internal(
11377        &mut self,
11378        user_triggered: bool,
11379        cx: &mut ViewContext<Self>,
11380    ) {
11381        if self.git_blame_inline_enabled {
11382            self.git_blame_inline_enabled = false;
11383            self.show_git_blame_inline = false;
11384            self.show_git_blame_inline_delay_task.take();
11385        } else {
11386            self.git_blame_inline_enabled = true;
11387            self.start_git_blame_inline(user_triggered, cx);
11388        }
11389
11390        cx.notify();
11391    }
11392
11393    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11394        self.start_git_blame(user_triggered, cx);
11395
11396        if ProjectSettings::get_global(cx)
11397            .git
11398            .inline_blame_delay()
11399            .is_some()
11400        {
11401            self.start_inline_blame_timer(cx);
11402        } else {
11403            self.show_git_blame_inline = true
11404        }
11405    }
11406
11407    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11408        self.blame.as_ref()
11409    }
11410
11411    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11412        self.show_git_blame_gutter && self.has_blame_entries(cx)
11413    }
11414
11415    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11416        self.show_git_blame_inline
11417            && self.focus_handle.is_focused(cx)
11418            && !self.newest_selection_head_on_empty_line(cx)
11419            && self.has_blame_entries(cx)
11420    }
11421
11422    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11423        self.blame()
11424            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11425    }
11426
11427    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11428        let cursor_anchor = self.selections.newest_anchor().head();
11429
11430        let snapshot = self.buffer.read(cx).snapshot(cx);
11431        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11432
11433        snapshot.line_len(buffer_row) == 0
11434    }
11435
11436    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11437        let (path, selection, repo) = maybe!({
11438            let project_handle = self.project.as_ref()?.clone();
11439            let project = project_handle.read(cx);
11440
11441            let selection = self.selections.newest::<Point>(cx);
11442            let selection_range = selection.range();
11443
11444            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11445                (buffer, selection_range.start.row..selection_range.end.row)
11446            } else {
11447                let buffer_ranges = self
11448                    .buffer()
11449                    .read(cx)
11450                    .range_to_buffer_ranges(selection_range, cx);
11451
11452                let (buffer, range, _) = if selection.reversed {
11453                    buffer_ranges.first()
11454                } else {
11455                    buffer_ranges.last()
11456                }?;
11457
11458                let snapshot = buffer.read(cx).snapshot();
11459                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11460                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11461                (buffer.clone(), selection)
11462            };
11463
11464            let path = buffer
11465                .read(cx)
11466                .file()?
11467                .as_local()?
11468                .path()
11469                .to_str()?
11470                .to_string();
11471            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11472            Some((path, selection, repo))
11473        })
11474        .ok_or_else(|| anyhow!("unable to open git repository"))?;
11475
11476        const REMOTE_NAME: &str = "origin";
11477        let origin_url = repo
11478            .remote_url(REMOTE_NAME)
11479            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11480        let sha = repo
11481            .head_sha()
11482            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11483
11484        let (provider, remote) =
11485            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11486                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11487
11488        Ok(provider.build_permalink(
11489            remote,
11490            BuildPermalinkParams {
11491                sha: &sha,
11492                path: &path,
11493                selection: Some(selection),
11494            },
11495        ))
11496    }
11497
11498    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11499        let permalink = self.get_permalink_to_line(cx);
11500
11501        match permalink {
11502            Ok(permalink) => {
11503                cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11504            }
11505            Err(err) => {
11506                let message = format!("Failed to copy permalink: {err}");
11507
11508                Err::<(), anyhow::Error>(err).log_err();
11509
11510                if let Some(workspace) = self.workspace() {
11511                    workspace.update(cx, |workspace, cx| {
11512                        struct CopyPermalinkToLine;
11513
11514                        workspace.show_toast(
11515                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11516                            cx,
11517                        )
11518                    })
11519                }
11520            }
11521        }
11522    }
11523
11524    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11525        if let Some(file) = self.target_file(cx) {
11526            if let Some(path) = file.path().to_str() {
11527                let selection = self.selections.newest::<Point>(cx).start.row + 1;
11528                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11529            }
11530        }
11531    }
11532
11533    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11534        let permalink = self.get_permalink_to_line(cx);
11535
11536        match permalink {
11537            Ok(permalink) => {
11538                cx.open_url(permalink.as_ref());
11539            }
11540            Err(err) => {
11541                let message = format!("Failed to open permalink: {err}");
11542
11543                Err::<(), anyhow::Error>(err).log_err();
11544
11545                if let Some(workspace) = self.workspace() {
11546                    workspace.update(cx, |workspace, cx| {
11547                        struct OpenPermalinkToLine;
11548
11549                        workspace.show_toast(
11550                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11551                            cx,
11552                        )
11553                    })
11554                }
11555            }
11556        }
11557    }
11558
11559    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11560    /// last highlight added will be used.
11561    ///
11562    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11563    pub fn highlight_rows<T: 'static>(
11564        &mut self,
11565        range: Range<Anchor>,
11566        color: Hsla,
11567        should_autoscroll: bool,
11568        cx: &mut ViewContext<Self>,
11569    ) {
11570        let snapshot = self.buffer().read(cx).snapshot(cx);
11571        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11572        let ix = row_highlights.binary_search_by(|highlight| {
11573            Ordering::Equal
11574                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11575                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11576        });
11577
11578        if let Err(mut ix) = ix {
11579            let index = post_inc(&mut self.highlight_order);
11580
11581            // If this range intersects with the preceding highlight, then merge it with
11582            // the preceding highlight. Otherwise insert a new highlight.
11583            let mut merged = false;
11584            if ix > 0 {
11585                let prev_highlight = &mut row_highlights[ix - 1];
11586                if prev_highlight
11587                    .range
11588                    .end
11589                    .cmp(&range.start, &snapshot)
11590                    .is_ge()
11591                {
11592                    ix -= 1;
11593                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11594                        prev_highlight.range.end = range.end;
11595                    }
11596                    merged = true;
11597                    prev_highlight.index = index;
11598                    prev_highlight.color = color;
11599                    prev_highlight.should_autoscroll = should_autoscroll;
11600                }
11601            }
11602
11603            if !merged {
11604                row_highlights.insert(
11605                    ix,
11606                    RowHighlight {
11607                        range: range.clone(),
11608                        index,
11609                        color,
11610                        should_autoscroll,
11611                    },
11612                );
11613            }
11614
11615            // If any of the following highlights intersect with this one, merge them.
11616            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11617                let highlight = &row_highlights[ix];
11618                if next_highlight
11619                    .range
11620                    .start
11621                    .cmp(&highlight.range.end, &snapshot)
11622                    .is_le()
11623                {
11624                    if next_highlight
11625                        .range
11626                        .end
11627                        .cmp(&highlight.range.end, &snapshot)
11628                        .is_gt()
11629                    {
11630                        row_highlights[ix].range.end = next_highlight.range.end;
11631                    }
11632                    row_highlights.remove(ix + 1);
11633                } else {
11634                    break;
11635                }
11636            }
11637        }
11638    }
11639
11640    /// Remove any highlighted row ranges of the given type that intersect the
11641    /// given ranges.
11642    pub fn remove_highlighted_rows<T: 'static>(
11643        &mut self,
11644        ranges_to_remove: Vec<Range<Anchor>>,
11645        cx: &mut ViewContext<Self>,
11646    ) {
11647        let snapshot = self.buffer().read(cx).snapshot(cx);
11648        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11649        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11650        row_highlights.retain(|highlight| {
11651            while let Some(range_to_remove) = ranges_to_remove.peek() {
11652                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11653                    Ordering::Less | Ordering::Equal => {
11654                        ranges_to_remove.next();
11655                    }
11656                    Ordering::Greater => {
11657                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11658                            Ordering::Less | Ordering::Equal => {
11659                                return false;
11660                            }
11661                            Ordering::Greater => break,
11662                        }
11663                    }
11664                }
11665            }
11666
11667            true
11668        })
11669    }
11670
11671    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11672    pub fn clear_row_highlights<T: 'static>(&mut self) {
11673        self.highlighted_rows.remove(&TypeId::of::<T>());
11674    }
11675
11676    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11677    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11678        self.highlighted_rows
11679            .get(&TypeId::of::<T>())
11680            .map_or(&[] as &[_], |vec| vec.as_slice())
11681            .iter()
11682            .map(|highlight| (highlight.range.clone(), highlight.color))
11683    }
11684
11685    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11686    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11687    /// Allows to ignore certain kinds of highlights.
11688    pub fn highlighted_display_rows(
11689        &mut self,
11690        cx: &mut WindowContext,
11691    ) -> BTreeMap<DisplayRow, Hsla> {
11692        let snapshot = self.snapshot(cx);
11693        let mut used_highlight_orders = HashMap::default();
11694        self.highlighted_rows
11695            .iter()
11696            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11697            .fold(
11698                BTreeMap::<DisplayRow, Hsla>::new(),
11699                |mut unique_rows, highlight| {
11700                    let start = highlight.range.start.to_display_point(&snapshot);
11701                    let end = highlight.range.end.to_display_point(&snapshot);
11702                    let start_row = start.row().0;
11703                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11704                        && end.column() == 0
11705                    {
11706                        end.row().0.saturating_sub(1)
11707                    } else {
11708                        end.row().0
11709                    };
11710                    for row in start_row..=end_row {
11711                        let used_index =
11712                            used_highlight_orders.entry(row).or_insert(highlight.index);
11713                        if highlight.index >= *used_index {
11714                            *used_index = highlight.index;
11715                            unique_rows.insert(DisplayRow(row), highlight.color);
11716                        }
11717                    }
11718                    unique_rows
11719                },
11720            )
11721    }
11722
11723    pub fn highlighted_display_row_for_autoscroll(
11724        &self,
11725        snapshot: &DisplaySnapshot,
11726    ) -> Option<DisplayRow> {
11727        self.highlighted_rows
11728            .values()
11729            .flat_map(|highlighted_rows| highlighted_rows.iter())
11730            .filter_map(|highlight| {
11731                if highlight.should_autoscroll {
11732                    Some(highlight.range.start.to_display_point(snapshot).row())
11733                } else {
11734                    None
11735                }
11736            })
11737            .min()
11738    }
11739
11740    pub fn set_search_within_ranges(
11741        &mut self,
11742        ranges: &[Range<Anchor>],
11743        cx: &mut ViewContext<Self>,
11744    ) {
11745        self.highlight_background::<SearchWithinRange>(
11746            ranges,
11747            |colors| colors.editor_document_highlight_read_background,
11748            cx,
11749        )
11750    }
11751
11752    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11753        self.breadcrumb_header = Some(new_header);
11754    }
11755
11756    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11757        self.clear_background_highlights::<SearchWithinRange>(cx);
11758    }
11759
11760    pub fn highlight_background<T: 'static>(
11761        &mut self,
11762        ranges: &[Range<Anchor>],
11763        color_fetcher: fn(&ThemeColors) -> Hsla,
11764        cx: &mut ViewContext<Self>,
11765    ) {
11766        self.background_highlights
11767            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11768        self.scrollbar_marker_state.dirty = true;
11769        cx.notify();
11770    }
11771
11772    pub fn clear_background_highlights<T: 'static>(
11773        &mut self,
11774        cx: &mut ViewContext<Self>,
11775    ) -> Option<BackgroundHighlight> {
11776        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11777        if !text_highlights.1.is_empty() {
11778            self.scrollbar_marker_state.dirty = true;
11779            cx.notify();
11780        }
11781        Some(text_highlights)
11782    }
11783
11784    pub fn highlight_gutter<T: 'static>(
11785        &mut self,
11786        ranges: &[Range<Anchor>],
11787        color_fetcher: fn(&AppContext) -> Hsla,
11788        cx: &mut ViewContext<Self>,
11789    ) {
11790        self.gutter_highlights
11791            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11792        cx.notify();
11793    }
11794
11795    pub fn clear_gutter_highlights<T: 'static>(
11796        &mut self,
11797        cx: &mut ViewContext<Self>,
11798    ) -> Option<GutterHighlight> {
11799        cx.notify();
11800        self.gutter_highlights.remove(&TypeId::of::<T>())
11801    }
11802
11803    #[cfg(feature = "test-support")]
11804    pub fn all_text_background_highlights(
11805        &mut self,
11806        cx: &mut ViewContext<Self>,
11807    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11808        let snapshot = self.snapshot(cx);
11809        let buffer = &snapshot.buffer_snapshot;
11810        let start = buffer.anchor_before(0);
11811        let end = buffer.anchor_after(buffer.len());
11812        let theme = cx.theme().colors();
11813        self.background_highlights_in_range(start..end, &snapshot, theme)
11814    }
11815
11816    #[cfg(feature = "test-support")]
11817    pub fn search_background_highlights(
11818        &mut self,
11819        cx: &mut ViewContext<Self>,
11820    ) -> Vec<Range<Point>> {
11821        let snapshot = self.buffer().read(cx).snapshot(cx);
11822
11823        let highlights = self
11824            .background_highlights
11825            .get(&TypeId::of::<items::BufferSearchHighlights>());
11826
11827        if let Some((_color, ranges)) = highlights {
11828            ranges
11829                .iter()
11830                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11831                .collect_vec()
11832        } else {
11833            vec![]
11834        }
11835    }
11836
11837    fn document_highlights_for_position<'a>(
11838        &'a self,
11839        position: Anchor,
11840        buffer: &'a MultiBufferSnapshot,
11841    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11842        let read_highlights = self
11843            .background_highlights
11844            .get(&TypeId::of::<DocumentHighlightRead>())
11845            .map(|h| &h.1);
11846        let write_highlights = self
11847            .background_highlights
11848            .get(&TypeId::of::<DocumentHighlightWrite>())
11849            .map(|h| &h.1);
11850        let left_position = position.bias_left(buffer);
11851        let right_position = position.bias_right(buffer);
11852        read_highlights
11853            .into_iter()
11854            .chain(write_highlights)
11855            .flat_map(move |ranges| {
11856                let start_ix = match ranges.binary_search_by(|probe| {
11857                    let cmp = probe.end.cmp(&left_position, buffer);
11858                    if cmp.is_ge() {
11859                        Ordering::Greater
11860                    } else {
11861                        Ordering::Less
11862                    }
11863                }) {
11864                    Ok(i) | Err(i) => i,
11865                };
11866
11867                ranges[start_ix..]
11868                    .iter()
11869                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11870            })
11871    }
11872
11873    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11874        self.background_highlights
11875            .get(&TypeId::of::<T>())
11876            .map_or(false, |(_, highlights)| !highlights.is_empty())
11877    }
11878
11879    pub fn background_highlights_in_range(
11880        &self,
11881        search_range: Range<Anchor>,
11882        display_snapshot: &DisplaySnapshot,
11883        theme: &ThemeColors,
11884    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11885        let mut results = Vec::new();
11886        for (color_fetcher, ranges) in self.background_highlights.values() {
11887            let color = color_fetcher(theme);
11888            let start_ix = match ranges.binary_search_by(|probe| {
11889                let cmp = probe
11890                    .end
11891                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11892                if cmp.is_gt() {
11893                    Ordering::Greater
11894                } else {
11895                    Ordering::Less
11896                }
11897            }) {
11898                Ok(i) | Err(i) => i,
11899            };
11900            for range in &ranges[start_ix..] {
11901                if range
11902                    .start
11903                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11904                    .is_ge()
11905                {
11906                    break;
11907                }
11908
11909                let start = range.start.to_display_point(display_snapshot);
11910                let end = range.end.to_display_point(display_snapshot);
11911                results.push((start..end, color))
11912            }
11913        }
11914        results
11915    }
11916
11917    pub fn background_highlight_row_ranges<T: 'static>(
11918        &self,
11919        search_range: Range<Anchor>,
11920        display_snapshot: &DisplaySnapshot,
11921        count: usize,
11922    ) -> Vec<RangeInclusive<DisplayPoint>> {
11923        let mut results = Vec::new();
11924        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11925            return vec![];
11926        };
11927
11928        let start_ix = match ranges.binary_search_by(|probe| {
11929            let cmp = probe
11930                .end
11931                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11932            if cmp.is_gt() {
11933                Ordering::Greater
11934            } else {
11935                Ordering::Less
11936            }
11937        }) {
11938            Ok(i) | Err(i) => i,
11939        };
11940        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11941            if let (Some(start_display), Some(end_display)) = (start, end) {
11942                results.push(
11943                    start_display.to_display_point(display_snapshot)
11944                        ..=end_display.to_display_point(display_snapshot),
11945                );
11946            }
11947        };
11948        let mut start_row: Option<Point> = None;
11949        let mut end_row: Option<Point> = None;
11950        if ranges.len() > count {
11951            return Vec::new();
11952        }
11953        for range in &ranges[start_ix..] {
11954            if range
11955                .start
11956                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11957                .is_ge()
11958            {
11959                break;
11960            }
11961            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11962            if let Some(current_row) = &end_row {
11963                if end.row == current_row.row {
11964                    continue;
11965                }
11966            }
11967            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11968            if start_row.is_none() {
11969                assert_eq!(end_row, None);
11970                start_row = Some(start);
11971                end_row = Some(end);
11972                continue;
11973            }
11974            if let Some(current_end) = end_row.as_mut() {
11975                if start.row > current_end.row + 1 {
11976                    push_region(start_row, end_row);
11977                    start_row = Some(start);
11978                    end_row = Some(end);
11979                } else {
11980                    // Merge two hunks.
11981                    *current_end = end;
11982                }
11983            } else {
11984                unreachable!();
11985            }
11986        }
11987        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11988        push_region(start_row, end_row);
11989        results
11990    }
11991
11992    pub fn gutter_highlights_in_range(
11993        &self,
11994        search_range: Range<Anchor>,
11995        display_snapshot: &DisplaySnapshot,
11996        cx: &AppContext,
11997    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11998        let mut results = Vec::new();
11999        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12000            let color = color_fetcher(cx);
12001            let start_ix = match ranges.binary_search_by(|probe| {
12002                let cmp = probe
12003                    .end
12004                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12005                if cmp.is_gt() {
12006                    Ordering::Greater
12007                } else {
12008                    Ordering::Less
12009                }
12010            }) {
12011                Ok(i) | Err(i) => i,
12012            };
12013            for range in &ranges[start_ix..] {
12014                if range
12015                    .start
12016                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12017                    .is_ge()
12018                {
12019                    break;
12020                }
12021
12022                let start = range.start.to_display_point(display_snapshot);
12023                let end = range.end.to_display_point(display_snapshot);
12024                results.push((start..end, color))
12025            }
12026        }
12027        results
12028    }
12029
12030    /// Get the text ranges corresponding to the redaction query
12031    pub fn redacted_ranges(
12032        &self,
12033        search_range: Range<Anchor>,
12034        display_snapshot: &DisplaySnapshot,
12035        cx: &WindowContext,
12036    ) -> Vec<Range<DisplayPoint>> {
12037        display_snapshot
12038            .buffer_snapshot
12039            .redacted_ranges(search_range, |file| {
12040                if let Some(file) = file {
12041                    file.is_private()
12042                        && EditorSettings::get(
12043                            Some(SettingsLocation {
12044                                worktree_id: file.worktree_id(cx),
12045                                path: file.path().as_ref(),
12046                            }),
12047                            cx,
12048                        )
12049                        .redact_private_values
12050                } else {
12051                    false
12052                }
12053            })
12054            .map(|range| {
12055                range.start.to_display_point(display_snapshot)
12056                    ..range.end.to_display_point(display_snapshot)
12057            })
12058            .collect()
12059    }
12060
12061    pub fn highlight_text<T: 'static>(
12062        &mut self,
12063        ranges: Vec<Range<Anchor>>,
12064        style: HighlightStyle,
12065        cx: &mut ViewContext<Self>,
12066    ) {
12067        self.display_map.update(cx, |map, _| {
12068            map.highlight_text(TypeId::of::<T>(), ranges, style)
12069        });
12070        cx.notify();
12071    }
12072
12073    pub(crate) fn highlight_inlays<T: 'static>(
12074        &mut self,
12075        highlights: Vec<InlayHighlight>,
12076        style: HighlightStyle,
12077        cx: &mut ViewContext<Self>,
12078    ) {
12079        self.display_map.update(cx, |map, _| {
12080            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12081        });
12082        cx.notify();
12083    }
12084
12085    pub fn text_highlights<'a, T: 'static>(
12086        &'a self,
12087        cx: &'a AppContext,
12088    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12089        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12090    }
12091
12092    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12093        let cleared = self
12094            .display_map
12095            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12096        if cleared {
12097            cx.notify();
12098        }
12099    }
12100
12101    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12102        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12103            && self.focus_handle.is_focused(cx)
12104    }
12105
12106    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12107        self.show_cursor_when_unfocused = is_enabled;
12108        cx.notify();
12109    }
12110
12111    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12112        cx.notify();
12113    }
12114
12115    fn on_buffer_event(
12116        &mut self,
12117        multibuffer: Model<MultiBuffer>,
12118        event: &multi_buffer::Event,
12119        cx: &mut ViewContext<Self>,
12120    ) {
12121        match event {
12122            multi_buffer::Event::Edited {
12123                singleton_buffer_edited,
12124            } => {
12125                self.scrollbar_marker_state.dirty = true;
12126                self.active_indent_guides_state.dirty = true;
12127                self.refresh_active_diagnostics(cx);
12128                self.refresh_code_actions(cx);
12129                if self.has_active_inline_completion(cx) {
12130                    self.update_visible_inline_completion(cx);
12131                }
12132                cx.emit(EditorEvent::BufferEdited);
12133                cx.emit(SearchEvent::MatchesInvalidated);
12134                if *singleton_buffer_edited {
12135                    if let Some(project) = &self.project {
12136                        let project = project.read(cx);
12137                        #[allow(clippy::mutable_key_type)]
12138                        let languages_affected = multibuffer
12139                            .read(cx)
12140                            .all_buffers()
12141                            .into_iter()
12142                            .filter_map(|buffer| {
12143                                let buffer = buffer.read(cx);
12144                                let language = buffer.language()?;
12145                                if project.is_local()
12146                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12147                                {
12148                                    None
12149                                } else {
12150                                    Some(language)
12151                                }
12152                            })
12153                            .cloned()
12154                            .collect::<HashSet<_>>();
12155                        if !languages_affected.is_empty() {
12156                            self.refresh_inlay_hints(
12157                                InlayHintRefreshReason::BufferEdited(languages_affected),
12158                                cx,
12159                            );
12160                        }
12161                    }
12162                }
12163
12164                let Some(project) = &self.project else { return };
12165                let telemetry = project.read(cx).client().telemetry().clone();
12166                refresh_linked_ranges(self, cx);
12167                telemetry.log_edit_event("editor");
12168            }
12169            multi_buffer::Event::ExcerptsAdded {
12170                buffer,
12171                predecessor,
12172                excerpts,
12173            } => {
12174                self.tasks_update_task = Some(self.refresh_runnables(cx));
12175                cx.emit(EditorEvent::ExcerptsAdded {
12176                    buffer: buffer.clone(),
12177                    predecessor: *predecessor,
12178                    excerpts: excerpts.clone(),
12179                });
12180                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12181            }
12182            multi_buffer::Event::ExcerptsRemoved { ids } => {
12183                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12184                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12185            }
12186            multi_buffer::Event::ExcerptsEdited { ids } => {
12187                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12188            }
12189            multi_buffer::Event::ExcerptsExpanded { ids } => {
12190                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12191            }
12192            multi_buffer::Event::Reparsed(buffer_id) => {
12193                self.tasks_update_task = Some(self.refresh_runnables(cx));
12194
12195                cx.emit(EditorEvent::Reparsed(*buffer_id));
12196            }
12197            multi_buffer::Event::LanguageChanged(buffer_id) => {
12198                linked_editing_ranges::refresh_linked_ranges(self, cx);
12199                cx.emit(EditorEvent::Reparsed(*buffer_id));
12200                cx.notify();
12201            }
12202            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12203            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12204            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12205                cx.emit(EditorEvent::TitleChanged)
12206            }
12207            multi_buffer::Event::DiffBaseChanged => {
12208                self.scrollbar_marker_state.dirty = true;
12209                cx.emit(EditorEvent::DiffBaseChanged);
12210                cx.notify();
12211            }
12212            multi_buffer::Event::DiffUpdated { buffer } => {
12213                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12214                cx.notify();
12215            }
12216            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12217            multi_buffer::Event::DiagnosticsUpdated => {
12218                self.refresh_active_diagnostics(cx);
12219                self.scrollbar_marker_state.dirty = true;
12220                cx.notify();
12221            }
12222            _ => {}
12223        };
12224    }
12225
12226    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12227        cx.notify();
12228    }
12229
12230    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12231        self.tasks_update_task = Some(self.refresh_runnables(cx));
12232        self.refresh_inline_completion(true, false, cx);
12233        self.refresh_inlay_hints(
12234            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12235                self.selections.newest_anchor().head(),
12236                &self.buffer.read(cx).snapshot(cx),
12237                cx,
12238            )),
12239            cx,
12240        );
12241
12242        let old_cursor_shape = self.cursor_shape;
12243
12244        {
12245            let editor_settings = EditorSettings::get_global(cx);
12246            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12247            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12248            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12249        }
12250
12251        if old_cursor_shape != self.cursor_shape {
12252            cx.emit(EditorEvent::CursorShapeChanged);
12253        }
12254
12255        let project_settings = ProjectSettings::get_global(cx);
12256        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12257
12258        if self.mode == EditorMode::Full {
12259            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12260            if self.git_blame_inline_enabled != inline_blame_enabled {
12261                self.toggle_git_blame_inline_internal(false, cx);
12262            }
12263        }
12264
12265        cx.notify();
12266    }
12267
12268    pub fn set_searchable(&mut self, searchable: bool) {
12269        self.searchable = searchable;
12270    }
12271
12272    pub fn searchable(&self) -> bool {
12273        self.searchable
12274    }
12275
12276    fn open_proposed_changes_editor(
12277        &mut self,
12278        _: &OpenProposedChangesEditor,
12279        cx: &mut ViewContext<Self>,
12280    ) {
12281        let Some(workspace) = self.workspace() else {
12282            cx.propagate();
12283            return;
12284        };
12285
12286        let buffer = self.buffer.read(cx);
12287        let mut new_selections_by_buffer = HashMap::default();
12288        for selection in self.selections.all::<usize>(cx) {
12289            for (buffer, range, _) in
12290                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12291            {
12292                let mut range = range.to_point(buffer.read(cx));
12293                range.start.column = 0;
12294                range.end.column = buffer.read(cx).line_len(range.end.row);
12295                new_selections_by_buffer
12296                    .entry(buffer)
12297                    .or_insert(Vec::new())
12298                    .push(range)
12299            }
12300        }
12301
12302        let proposed_changes_buffers = new_selections_by_buffer
12303            .into_iter()
12304            .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12305            .collect::<Vec<_>>();
12306        let proposed_changes_editor = cx.new_view(|cx| {
12307            ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12308        });
12309
12310        cx.window_context().defer(move |cx| {
12311            workspace.update(cx, |workspace, cx| {
12312                workspace.active_pane().update(cx, |pane, cx| {
12313                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12314                });
12315            });
12316        });
12317    }
12318
12319    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12320        self.open_excerpts_common(true, cx)
12321    }
12322
12323    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12324        self.open_excerpts_common(false, cx)
12325    }
12326
12327    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12328        let buffer = self.buffer.read(cx);
12329        if buffer.is_singleton() {
12330            cx.propagate();
12331            return;
12332        }
12333
12334        let Some(workspace) = self.workspace() else {
12335            cx.propagate();
12336            return;
12337        };
12338
12339        let mut new_selections_by_buffer = HashMap::default();
12340        for selection in self.selections.all::<usize>(cx) {
12341            for (buffer, mut range, _) in
12342                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12343            {
12344                if selection.reversed {
12345                    mem::swap(&mut range.start, &mut range.end);
12346                }
12347                new_selections_by_buffer
12348                    .entry(buffer)
12349                    .or_insert(Vec::new())
12350                    .push(range)
12351            }
12352        }
12353
12354        // We defer the pane interaction because we ourselves are a workspace item
12355        // and activating a new item causes the pane to call a method on us reentrantly,
12356        // which panics if we're on the stack.
12357        cx.window_context().defer(move |cx| {
12358            workspace.update(cx, |workspace, cx| {
12359                let pane = if split {
12360                    workspace.adjacent_pane(cx)
12361                } else {
12362                    workspace.active_pane().clone()
12363                };
12364
12365                for (buffer, ranges) in new_selections_by_buffer {
12366                    let editor =
12367                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12368                    editor.update(cx, |editor, cx| {
12369                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12370                            s.select_ranges(ranges);
12371                        });
12372                    });
12373                }
12374            })
12375        });
12376    }
12377
12378    fn jump(
12379        &mut self,
12380        path: ProjectPath,
12381        position: Point,
12382        anchor: language::Anchor,
12383        offset_from_top: u32,
12384        cx: &mut ViewContext<Self>,
12385    ) {
12386        let workspace = self.workspace();
12387        cx.spawn(|_, mut cx| async move {
12388            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12389            let editor = workspace.update(&mut cx, |workspace, cx| {
12390                // Reset the preview item id before opening the new item
12391                workspace.active_pane().update(cx, |pane, cx| {
12392                    pane.set_preview_item_id(None, cx);
12393                });
12394                workspace.open_path_preview(path, None, true, true, cx)
12395            })?;
12396            let editor = editor
12397                .await?
12398                .downcast::<Editor>()
12399                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12400                .downgrade();
12401            editor.update(&mut cx, |editor, cx| {
12402                let buffer = editor
12403                    .buffer()
12404                    .read(cx)
12405                    .as_singleton()
12406                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12407                let buffer = buffer.read(cx);
12408                let cursor = if buffer.can_resolve(&anchor) {
12409                    language::ToPoint::to_point(&anchor, buffer)
12410                } else {
12411                    buffer.clip_point(position, Bias::Left)
12412                };
12413
12414                let nav_history = editor.nav_history.take();
12415                editor.change_selections(
12416                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12417                    cx,
12418                    |s| {
12419                        s.select_ranges([cursor..cursor]);
12420                    },
12421                );
12422                editor.nav_history = nav_history;
12423
12424                anyhow::Ok(())
12425            })??;
12426
12427            anyhow::Ok(())
12428        })
12429        .detach_and_log_err(cx);
12430    }
12431
12432    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12433        let snapshot = self.buffer.read(cx).read(cx);
12434        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12435        Some(
12436            ranges
12437                .iter()
12438                .map(move |range| {
12439                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12440                })
12441                .collect(),
12442        )
12443    }
12444
12445    fn selection_replacement_ranges(
12446        &self,
12447        range: Range<OffsetUtf16>,
12448        cx: &AppContext,
12449    ) -> Vec<Range<OffsetUtf16>> {
12450        let selections = self.selections.all::<OffsetUtf16>(cx);
12451        let newest_selection = selections
12452            .iter()
12453            .max_by_key(|selection| selection.id)
12454            .unwrap();
12455        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12456        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12457        let snapshot = self.buffer.read(cx).read(cx);
12458        selections
12459            .into_iter()
12460            .map(|mut selection| {
12461                selection.start.0 =
12462                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12463                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12464                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12465                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12466            })
12467            .collect()
12468    }
12469
12470    fn report_editor_event(
12471        &self,
12472        operation: &'static str,
12473        file_extension: Option<String>,
12474        cx: &AppContext,
12475    ) {
12476        if cfg!(any(test, feature = "test-support")) {
12477            return;
12478        }
12479
12480        let Some(project) = &self.project else { return };
12481
12482        // If None, we are in a file without an extension
12483        let file = self
12484            .buffer
12485            .read(cx)
12486            .as_singleton()
12487            .and_then(|b| b.read(cx).file());
12488        let file_extension = file_extension.or(file
12489            .as_ref()
12490            .and_then(|file| Path::new(file.file_name(cx)).extension())
12491            .and_then(|e| e.to_str())
12492            .map(|a| a.to_string()));
12493
12494        let vim_mode = cx
12495            .global::<SettingsStore>()
12496            .raw_user_settings()
12497            .get("vim_mode")
12498            == Some(&serde_json::Value::Bool(true));
12499
12500        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12501            == language::language_settings::InlineCompletionProvider::Copilot;
12502        let copilot_enabled_for_language = self
12503            .buffer
12504            .read(cx)
12505            .settings_at(0, cx)
12506            .show_inline_completions;
12507
12508        let telemetry = project.read(cx).client().telemetry().clone();
12509        telemetry.report_editor_event(
12510            file_extension,
12511            vim_mode,
12512            operation,
12513            copilot_enabled,
12514            copilot_enabled_for_language,
12515        )
12516    }
12517
12518    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12519    /// with each line being an array of {text, highlight} objects.
12520    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12521        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12522            return;
12523        };
12524
12525        #[derive(Serialize)]
12526        struct Chunk<'a> {
12527            text: String,
12528            highlight: Option<&'a str>,
12529        }
12530
12531        let snapshot = buffer.read(cx).snapshot();
12532        let range = self
12533            .selected_text_range(false, cx)
12534            .and_then(|selection| {
12535                if selection.range.is_empty() {
12536                    None
12537                } else {
12538                    Some(selection.range)
12539                }
12540            })
12541            .unwrap_or_else(|| 0..snapshot.len());
12542
12543        let chunks = snapshot.chunks(range, true);
12544        let mut lines = Vec::new();
12545        let mut line: VecDeque<Chunk> = VecDeque::new();
12546
12547        let Some(style) = self.style.as_ref() else {
12548            return;
12549        };
12550
12551        for chunk in chunks {
12552            let highlight = chunk
12553                .syntax_highlight_id
12554                .and_then(|id| id.name(&style.syntax));
12555            let mut chunk_lines = chunk.text.split('\n').peekable();
12556            while let Some(text) = chunk_lines.next() {
12557                let mut merged_with_last_token = false;
12558                if let Some(last_token) = line.back_mut() {
12559                    if last_token.highlight == highlight {
12560                        last_token.text.push_str(text);
12561                        merged_with_last_token = true;
12562                    }
12563                }
12564
12565                if !merged_with_last_token {
12566                    line.push_back(Chunk {
12567                        text: text.into(),
12568                        highlight,
12569                    });
12570                }
12571
12572                if chunk_lines.peek().is_some() {
12573                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12574                        line.pop_front();
12575                    }
12576                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12577                        line.pop_back();
12578                    }
12579
12580                    lines.push(mem::take(&mut line));
12581                }
12582            }
12583        }
12584
12585        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12586            return;
12587        };
12588        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12589    }
12590
12591    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12592        &self.inlay_hint_cache
12593    }
12594
12595    pub fn replay_insert_event(
12596        &mut self,
12597        text: &str,
12598        relative_utf16_range: Option<Range<isize>>,
12599        cx: &mut ViewContext<Self>,
12600    ) {
12601        if !self.input_enabled {
12602            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12603            return;
12604        }
12605        if let Some(relative_utf16_range) = relative_utf16_range {
12606            let selections = self.selections.all::<OffsetUtf16>(cx);
12607            self.change_selections(None, cx, |s| {
12608                let new_ranges = selections.into_iter().map(|range| {
12609                    let start = OffsetUtf16(
12610                        range
12611                            .head()
12612                            .0
12613                            .saturating_add_signed(relative_utf16_range.start),
12614                    );
12615                    let end = OffsetUtf16(
12616                        range
12617                            .head()
12618                            .0
12619                            .saturating_add_signed(relative_utf16_range.end),
12620                    );
12621                    start..end
12622                });
12623                s.select_ranges(new_ranges);
12624            });
12625        }
12626
12627        self.handle_input(text, cx);
12628    }
12629
12630    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12631        let Some(project) = self.project.as_ref() else {
12632            return false;
12633        };
12634        let project = project.read(cx);
12635
12636        let mut supports = false;
12637        self.buffer().read(cx).for_each_buffer(|buffer| {
12638            if !supports {
12639                supports = project
12640                    .language_servers_for_buffer(buffer.read(cx), cx)
12641                    .any(
12642                        |(_, server)| match server.capabilities().inlay_hint_provider {
12643                            Some(lsp::OneOf::Left(enabled)) => enabled,
12644                            Some(lsp::OneOf::Right(_)) => true,
12645                            None => false,
12646                        },
12647                    )
12648            }
12649        });
12650        supports
12651    }
12652
12653    pub fn focus(&self, cx: &mut WindowContext) {
12654        cx.focus(&self.focus_handle)
12655    }
12656
12657    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12658        self.focus_handle.is_focused(cx)
12659    }
12660
12661    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12662        cx.emit(EditorEvent::Focused);
12663
12664        if let Some(descendant) = self
12665            .last_focused_descendant
12666            .take()
12667            .and_then(|descendant| descendant.upgrade())
12668        {
12669            cx.focus(&descendant);
12670        } else {
12671            if let Some(blame) = self.blame.as_ref() {
12672                blame.update(cx, GitBlame::focus)
12673            }
12674
12675            self.blink_manager.update(cx, BlinkManager::enable);
12676            self.show_cursor_names(cx);
12677            self.buffer.update(cx, |buffer, cx| {
12678                buffer.finalize_last_transaction(cx);
12679                if self.leader_peer_id.is_none() {
12680                    buffer.set_active_selections(
12681                        &self.selections.disjoint_anchors(),
12682                        self.selections.line_mode,
12683                        self.cursor_shape,
12684                        cx,
12685                    );
12686                }
12687            });
12688        }
12689    }
12690
12691    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12692        cx.emit(EditorEvent::FocusedIn)
12693    }
12694
12695    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12696        if event.blurred != self.focus_handle {
12697            self.last_focused_descendant = Some(event.blurred);
12698        }
12699    }
12700
12701    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12702        self.blink_manager.update(cx, BlinkManager::disable);
12703        self.buffer
12704            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12705
12706        if let Some(blame) = self.blame.as_ref() {
12707            blame.update(cx, GitBlame::blur)
12708        }
12709        if !self.hover_state.focused(cx) {
12710            hide_hover(self, cx);
12711        }
12712
12713        self.hide_context_menu(cx);
12714        cx.emit(EditorEvent::Blurred);
12715        cx.notify();
12716    }
12717
12718    pub fn register_action<A: Action>(
12719        &mut self,
12720        listener: impl Fn(&A, &mut WindowContext) + 'static,
12721    ) -> Subscription {
12722        let id = self.next_editor_action_id.post_inc();
12723        let listener = Arc::new(listener);
12724        self.editor_actions.borrow_mut().insert(
12725            id,
12726            Box::new(move |cx| {
12727                let cx = cx.window_context();
12728                let listener = listener.clone();
12729                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12730                    let action = action.downcast_ref().unwrap();
12731                    if phase == DispatchPhase::Bubble {
12732                        listener(action, cx)
12733                    }
12734                })
12735            }),
12736        );
12737
12738        let editor_actions = self.editor_actions.clone();
12739        Subscription::new(move || {
12740            editor_actions.borrow_mut().remove(&id);
12741        })
12742    }
12743
12744    pub fn file_header_size(&self) -> u32 {
12745        self.file_header_size
12746    }
12747
12748    pub fn revert(
12749        &mut self,
12750        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12751        cx: &mut ViewContext<Self>,
12752    ) {
12753        self.buffer().update(cx, |multi_buffer, cx| {
12754            for (buffer_id, changes) in revert_changes {
12755                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12756                    buffer.update(cx, |buffer, cx| {
12757                        buffer.edit(
12758                            changes.into_iter().map(|(range, text)| {
12759                                (range, text.to_string().map(Arc::<str>::from))
12760                            }),
12761                            None,
12762                            cx,
12763                        );
12764                    });
12765                }
12766            }
12767        });
12768        self.change_selections(None, cx, |selections| selections.refresh());
12769    }
12770
12771    pub fn to_pixel_point(
12772        &mut self,
12773        source: multi_buffer::Anchor,
12774        editor_snapshot: &EditorSnapshot,
12775        cx: &mut ViewContext<Self>,
12776    ) -> Option<gpui::Point<Pixels>> {
12777        let source_point = source.to_display_point(editor_snapshot);
12778        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12779    }
12780
12781    pub fn display_to_pixel_point(
12782        &mut self,
12783        source: DisplayPoint,
12784        editor_snapshot: &EditorSnapshot,
12785        cx: &mut ViewContext<Self>,
12786    ) -> Option<gpui::Point<Pixels>> {
12787        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12788        let text_layout_details = self.text_layout_details(cx);
12789        let scroll_top = text_layout_details
12790            .scroll_anchor
12791            .scroll_position(editor_snapshot)
12792            .y;
12793
12794        if source.row().as_f32() < scroll_top.floor() {
12795            return None;
12796        }
12797        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12798        let source_y = line_height * (source.row().as_f32() - scroll_top);
12799        Some(gpui::Point::new(source_x, source_y))
12800    }
12801
12802    pub fn has_active_completions_menu(&self) -> bool {
12803        self.context_menu.read().as_ref().map_or(false, |menu| {
12804            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12805        })
12806    }
12807
12808    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12809        self.addons
12810            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12811    }
12812
12813    pub fn unregister_addon<T: Addon>(&mut self) {
12814        self.addons.remove(&std::any::TypeId::of::<T>());
12815    }
12816
12817    pub fn addon<T: Addon>(&self) -> Option<&T> {
12818        let type_id = std::any::TypeId::of::<T>();
12819        self.addons
12820            .get(&type_id)
12821            .and_then(|item| item.to_any().downcast_ref::<T>())
12822    }
12823}
12824
12825fn hunks_for_selections(
12826    multi_buffer_snapshot: &MultiBufferSnapshot,
12827    selections: &[Selection<Anchor>],
12828) -> Vec<MultiBufferDiffHunk> {
12829    let buffer_rows_for_selections = selections.iter().map(|selection| {
12830        let head = selection.head();
12831        let tail = selection.tail();
12832        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12833        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12834        if start > end {
12835            end..start
12836        } else {
12837            start..end
12838        }
12839    });
12840
12841    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12842}
12843
12844pub fn hunks_for_rows(
12845    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12846    multi_buffer_snapshot: &MultiBufferSnapshot,
12847) -> Vec<MultiBufferDiffHunk> {
12848    let mut hunks = Vec::new();
12849    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12850        HashMap::default();
12851    for selected_multi_buffer_rows in rows {
12852        let query_rows =
12853            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12854        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12855            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12856            // when the caret is just above or just below the deleted hunk.
12857            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12858            let related_to_selection = if allow_adjacent {
12859                hunk.row_range.overlaps(&query_rows)
12860                    || hunk.row_range.start == query_rows.end
12861                    || hunk.row_range.end == query_rows.start
12862            } else {
12863                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12864                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12865                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12866                    || selected_multi_buffer_rows.end == hunk.row_range.start
12867            };
12868            if related_to_selection {
12869                if !processed_buffer_rows
12870                    .entry(hunk.buffer_id)
12871                    .or_default()
12872                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12873                {
12874                    continue;
12875                }
12876                hunks.push(hunk);
12877            }
12878        }
12879    }
12880
12881    hunks
12882}
12883
12884pub trait CollaborationHub {
12885    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12886    fn user_participant_indices<'a>(
12887        &self,
12888        cx: &'a AppContext,
12889    ) -> &'a HashMap<u64, ParticipantIndex>;
12890    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12891}
12892
12893impl CollaborationHub for Model<Project> {
12894    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12895        self.read(cx).collaborators()
12896    }
12897
12898    fn user_participant_indices<'a>(
12899        &self,
12900        cx: &'a AppContext,
12901    ) -> &'a HashMap<u64, ParticipantIndex> {
12902        self.read(cx).user_store().read(cx).participant_indices()
12903    }
12904
12905    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12906        let this = self.read(cx);
12907        let user_ids = this.collaborators().values().map(|c| c.user_id);
12908        this.user_store().read_with(cx, |user_store, cx| {
12909            user_store.participant_names(user_ids, cx)
12910        })
12911    }
12912}
12913
12914pub trait CompletionProvider {
12915    fn completions(
12916        &self,
12917        buffer: &Model<Buffer>,
12918        buffer_position: text::Anchor,
12919        trigger: CompletionContext,
12920        cx: &mut ViewContext<Editor>,
12921    ) -> Task<Result<Vec<Completion>>>;
12922
12923    fn resolve_completions(
12924        &self,
12925        buffer: Model<Buffer>,
12926        completion_indices: Vec<usize>,
12927        completions: Arc<RwLock<Box<[Completion]>>>,
12928        cx: &mut ViewContext<Editor>,
12929    ) -> Task<Result<bool>>;
12930
12931    fn apply_additional_edits_for_completion(
12932        &self,
12933        buffer: Model<Buffer>,
12934        completion: Completion,
12935        push_to_history: bool,
12936        cx: &mut ViewContext<Editor>,
12937    ) -> Task<Result<Option<language::Transaction>>>;
12938
12939    fn is_completion_trigger(
12940        &self,
12941        buffer: &Model<Buffer>,
12942        position: language::Anchor,
12943        text: &str,
12944        trigger_in_words: bool,
12945        cx: &mut ViewContext<Editor>,
12946    ) -> bool;
12947
12948    fn sort_completions(&self) -> bool {
12949        true
12950    }
12951}
12952
12953pub trait CodeActionProvider {
12954    fn code_actions(
12955        &self,
12956        buffer: &Model<Buffer>,
12957        range: Range<text::Anchor>,
12958        cx: &mut WindowContext,
12959    ) -> Task<Result<Vec<CodeAction>>>;
12960
12961    fn apply_code_action(
12962        &self,
12963        buffer_handle: Model<Buffer>,
12964        action: CodeAction,
12965        excerpt_id: ExcerptId,
12966        push_to_history: bool,
12967        cx: &mut WindowContext,
12968    ) -> Task<Result<ProjectTransaction>>;
12969}
12970
12971impl CodeActionProvider for Model<Project> {
12972    fn code_actions(
12973        &self,
12974        buffer: &Model<Buffer>,
12975        range: Range<text::Anchor>,
12976        cx: &mut WindowContext,
12977    ) -> Task<Result<Vec<CodeAction>>> {
12978        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12979    }
12980
12981    fn apply_code_action(
12982        &self,
12983        buffer_handle: Model<Buffer>,
12984        action: CodeAction,
12985        _excerpt_id: ExcerptId,
12986        push_to_history: bool,
12987        cx: &mut WindowContext,
12988    ) -> Task<Result<ProjectTransaction>> {
12989        self.update(cx, |project, cx| {
12990            project.apply_code_action(buffer_handle, action, push_to_history, cx)
12991        })
12992    }
12993}
12994
12995fn snippet_completions(
12996    project: &Project,
12997    buffer: &Model<Buffer>,
12998    buffer_position: text::Anchor,
12999    cx: &mut AppContext,
13000) -> Vec<Completion> {
13001    let language = buffer.read(cx).language_at(buffer_position);
13002    let language_name = language.as_ref().map(|language| language.lsp_id());
13003    let snippet_store = project.snippets().read(cx);
13004    let snippets = snippet_store.snippets_for(language_name, cx);
13005
13006    if snippets.is_empty() {
13007        return vec![];
13008    }
13009    let snapshot = buffer.read(cx).text_snapshot();
13010    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
13011
13012    let mut lines = chunks.lines();
13013    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
13014        return vec![];
13015    };
13016
13017    let scope = language.map(|language| language.default_scope());
13018    let classifier = CharClassifier::new(scope).for_completion(true);
13019    let mut last_word = line_at
13020        .chars()
13021        .rev()
13022        .take_while(|c| classifier.is_word(*c))
13023        .collect::<String>();
13024    last_word = last_word.chars().rev().collect();
13025    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13026    let to_lsp = |point: &text::Anchor| {
13027        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13028        point_to_lsp(end)
13029    };
13030    let lsp_end = to_lsp(&buffer_position);
13031    snippets
13032        .into_iter()
13033        .filter_map(|snippet| {
13034            let matching_prefix = snippet
13035                .prefix
13036                .iter()
13037                .find(|prefix| prefix.starts_with(&last_word))?;
13038            let start = as_offset - last_word.len();
13039            let start = snapshot.anchor_before(start);
13040            let range = start..buffer_position;
13041            let lsp_start = to_lsp(&start);
13042            let lsp_range = lsp::Range {
13043                start: lsp_start,
13044                end: lsp_end,
13045            };
13046            Some(Completion {
13047                old_range: range,
13048                new_text: snippet.body.clone(),
13049                label: CodeLabel {
13050                    text: matching_prefix.clone(),
13051                    runs: vec![],
13052                    filter_range: 0..matching_prefix.len(),
13053                },
13054                server_id: LanguageServerId(usize::MAX),
13055                documentation: snippet.description.clone().map(Documentation::SingleLine),
13056                lsp_completion: lsp::CompletionItem {
13057                    label: snippet.prefix.first().unwrap().clone(),
13058                    kind: Some(CompletionItemKind::SNIPPET),
13059                    label_details: snippet.description.as_ref().map(|description| {
13060                        lsp::CompletionItemLabelDetails {
13061                            detail: Some(description.clone()),
13062                            description: None,
13063                        }
13064                    }),
13065                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13066                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13067                        lsp::InsertReplaceEdit {
13068                            new_text: snippet.body.clone(),
13069                            insert: lsp_range,
13070                            replace: lsp_range,
13071                        },
13072                    )),
13073                    filter_text: Some(snippet.body.clone()),
13074                    sort_text: Some(char::MAX.to_string()),
13075                    ..Default::default()
13076                },
13077                confirm: None,
13078            })
13079        })
13080        .collect()
13081}
13082
13083impl CompletionProvider for Model<Project> {
13084    fn completions(
13085        &self,
13086        buffer: &Model<Buffer>,
13087        buffer_position: text::Anchor,
13088        options: CompletionContext,
13089        cx: &mut ViewContext<Editor>,
13090    ) -> Task<Result<Vec<Completion>>> {
13091        self.update(cx, |project, cx| {
13092            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13093            let project_completions = project.completions(buffer, buffer_position, options, cx);
13094            cx.background_executor().spawn(async move {
13095                let mut completions = project_completions.await?;
13096                //let snippets = snippets.into_iter().;
13097                completions.extend(snippets);
13098                Ok(completions)
13099            })
13100        })
13101    }
13102
13103    fn resolve_completions(
13104        &self,
13105        buffer: Model<Buffer>,
13106        completion_indices: Vec<usize>,
13107        completions: Arc<RwLock<Box<[Completion]>>>,
13108        cx: &mut ViewContext<Editor>,
13109    ) -> Task<Result<bool>> {
13110        self.update(cx, |project, cx| {
13111            project.resolve_completions(buffer, completion_indices, completions, cx)
13112        })
13113    }
13114
13115    fn apply_additional_edits_for_completion(
13116        &self,
13117        buffer: Model<Buffer>,
13118        completion: Completion,
13119        push_to_history: bool,
13120        cx: &mut ViewContext<Editor>,
13121    ) -> Task<Result<Option<language::Transaction>>> {
13122        self.update(cx, |project, cx| {
13123            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13124        })
13125    }
13126
13127    fn is_completion_trigger(
13128        &self,
13129        buffer: &Model<Buffer>,
13130        position: language::Anchor,
13131        text: &str,
13132        trigger_in_words: bool,
13133        cx: &mut ViewContext<Editor>,
13134    ) -> bool {
13135        if !EditorSettings::get_global(cx).show_completions_on_input {
13136            return false;
13137        }
13138
13139        let mut chars = text.chars();
13140        let char = if let Some(char) = chars.next() {
13141            char
13142        } else {
13143            return false;
13144        };
13145        if chars.next().is_some() {
13146            return false;
13147        }
13148
13149        let buffer = buffer.read(cx);
13150        let classifier = buffer
13151            .snapshot()
13152            .char_classifier_at(position)
13153            .for_completion(true);
13154        if trigger_in_words && classifier.is_word(char) {
13155            return true;
13156        }
13157
13158        buffer
13159            .completion_triggers()
13160            .iter()
13161            .any(|string| string == text)
13162    }
13163}
13164
13165fn inlay_hint_settings(
13166    location: Anchor,
13167    snapshot: &MultiBufferSnapshot,
13168    cx: &mut ViewContext<'_, Editor>,
13169) -> InlayHintSettings {
13170    let file = snapshot.file_at(location);
13171    let language = snapshot.language_at(location);
13172    let settings = all_language_settings(file, cx);
13173    settings
13174        .language(language.map(|l| l.name()).as_ref())
13175        .inlay_hints
13176}
13177
13178fn consume_contiguous_rows(
13179    contiguous_row_selections: &mut Vec<Selection<Point>>,
13180    selection: &Selection<Point>,
13181    display_map: &DisplaySnapshot,
13182    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13183) -> (MultiBufferRow, MultiBufferRow) {
13184    contiguous_row_selections.push(selection.clone());
13185    let start_row = MultiBufferRow(selection.start.row);
13186    let mut end_row = ending_row(selection, display_map);
13187
13188    while let Some(next_selection) = selections.peek() {
13189        if next_selection.start.row <= end_row.0 {
13190            end_row = ending_row(next_selection, display_map);
13191            contiguous_row_selections.push(selections.next().unwrap().clone());
13192        } else {
13193            break;
13194        }
13195    }
13196    (start_row, end_row)
13197}
13198
13199fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13200    if next_selection.end.column > 0 || next_selection.is_empty() {
13201        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13202    } else {
13203        MultiBufferRow(next_selection.end.row)
13204    }
13205}
13206
13207impl EditorSnapshot {
13208    pub fn remote_selections_in_range<'a>(
13209        &'a self,
13210        range: &'a Range<Anchor>,
13211        collaboration_hub: &dyn CollaborationHub,
13212        cx: &'a AppContext,
13213    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13214        let participant_names = collaboration_hub.user_names(cx);
13215        let participant_indices = collaboration_hub.user_participant_indices(cx);
13216        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13217        let collaborators_by_replica_id = collaborators_by_peer_id
13218            .iter()
13219            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13220            .collect::<HashMap<_, _>>();
13221        self.buffer_snapshot
13222            .selections_in_range(range, false)
13223            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13224                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13225                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13226                let user_name = participant_names.get(&collaborator.user_id).cloned();
13227                Some(RemoteSelection {
13228                    replica_id,
13229                    selection,
13230                    cursor_shape,
13231                    line_mode,
13232                    participant_index,
13233                    peer_id: collaborator.peer_id,
13234                    user_name,
13235                })
13236            })
13237    }
13238
13239    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13240        self.display_snapshot.buffer_snapshot.language_at(position)
13241    }
13242
13243    pub fn is_focused(&self) -> bool {
13244        self.is_focused
13245    }
13246
13247    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13248        self.placeholder_text.as_ref()
13249    }
13250
13251    pub fn scroll_position(&self) -> gpui::Point<f32> {
13252        self.scroll_anchor.scroll_position(&self.display_snapshot)
13253    }
13254
13255    fn gutter_dimensions(
13256        &self,
13257        font_id: FontId,
13258        font_size: Pixels,
13259        em_width: Pixels,
13260        em_advance: Pixels,
13261        max_line_number_width: Pixels,
13262        cx: &AppContext,
13263    ) -> GutterDimensions {
13264        if !self.show_gutter {
13265            return GutterDimensions::default();
13266        }
13267        let descent = cx.text_system().descent(font_id, font_size);
13268
13269        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13270            matches!(
13271                ProjectSettings::get_global(cx).git.git_gutter,
13272                Some(GitGutterSetting::TrackedFiles)
13273            )
13274        });
13275        let gutter_settings = EditorSettings::get_global(cx).gutter;
13276        let show_line_numbers = self
13277            .show_line_numbers
13278            .unwrap_or(gutter_settings.line_numbers);
13279        let line_gutter_width = if show_line_numbers {
13280            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13281            let min_width_for_number_on_gutter = em_advance * 4.0;
13282            max_line_number_width.max(min_width_for_number_on_gutter)
13283        } else {
13284            0.0.into()
13285        };
13286
13287        let show_code_actions = self
13288            .show_code_actions
13289            .unwrap_or(gutter_settings.code_actions);
13290
13291        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13292
13293        let git_blame_entries_width =
13294            self.git_blame_gutter_max_author_length
13295                .map(|max_author_length| {
13296                    // Length of the author name, but also space for the commit hash,
13297                    // the spacing and the timestamp.
13298                    let max_char_count = max_author_length
13299                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13300                        + 7 // length of commit sha
13301                        + 14 // length of max relative timestamp ("60 minutes ago")
13302                        + 4; // gaps and margins
13303
13304                    em_advance * max_char_count
13305                });
13306
13307        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13308        left_padding += if show_code_actions || show_runnables {
13309            em_width * 3.0
13310        } else if show_git_gutter && show_line_numbers {
13311            em_width * 2.0
13312        } else if show_git_gutter || show_line_numbers {
13313            em_width
13314        } else {
13315            px(0.)
13316        };
13317
13318        let right_padding = if gutter_settings.folds && show_line_numbers {
13319            em_width * 4.0
13320        } else if gutter_settings.folds {
13321            em_width * 3.0
13322        } else if show_line_numbers {
13323            em_width
13324        } else {
13325            px(0.)
13326        };
13327
13328        GutterDimensions {
13329            left_padding,
13330            right_padding,
13331            width: line_gutter_width + left_padding + right_padding,
13332            margin: -descent,
13333            git_blame_entries_width,
13334        }
13335    }
13336
13337    pub fn render_fold_toggle(
13338        &self,
13339        buffer_row: MultiBufferRow,
13340        row_contains_cursor: bool,
13341        editor: View<Editor>,
13342        cx: &mut WindowContext,
13343    ) -> Option<AnyElement> {
13344        let folded = self.is_line_folded(buffer_row);
13345
13346        if let Some(crease) = self
13347            .crease_snapshot
13348            .query_row(buffer_row, &self.buffer_snapshot)
13349        {
13350            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13351                if folded {
13352                    editor.update(cx, |editor, cx| {
13353                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13354                    });
13355                } else {
13356                    editor.update(cx, |editor, cx| {
13357                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13358                    });
13359                }
13360            });
13361
13362            Some((crease.render_toggle)(
13363                buffer_row,
13364                folded,
13365                toggle_callback,
13366                cx,
13367            ))
13368        } else if folded
13369            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13370        {
13371            Some(
13372                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13373                    .selected(folded)
13374                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13375                        if folded {
13376                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13377                        } else {
13378                            this.fold_at(&FoldAt { buffer_row }, cx);
13379                        }
13380                    }))
13381                    .into_any_element(),
13382            )
13383        } else {
13384            None
13385        }
13386    }
13387
13388    pub fn render_crease_trailer(
13389        &self,
13390        buffer_row: MultiBufferRow,
13391        cx: &mut WindowContext,
13392    ) -> Option<AnyElement> {
13393        let folded = self.is_line_folded(buffer_row);
13394        let crease = self
13395            .crease_snapshot
13396            .query_row(buffer_row, &self.buffer_snapshot)?;
13397        Some((crease.render_trailer)(buffer_row, folded, cx))
13398    }
13399}
13400
13401impl Deref for EditorSnapshot {
13402    type Target = DisplaySnapshot;
13403
13404    fn deref(&self) -> &Self::Target {
13405        &self.display_snapshot
13406    }
13407}
13408
13409#[derive(Clone, Debug, PartialEq, Eq)]
13410pub enum EditorEvent {
13411    InputIgnored {
13412        text: Arc<str>,
13413    },
13414    InputHandled {
13415        utf16_range_to_replace: Option<Range<isize>>,
13416        text: Arc<str>,
13417    },
13418    ExcerptsAdded {
13419        buffer: Model<Buffer>,
13420        predecessor: ExcerptId,
13421        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13422    },
13423    ExcerptsRemoved {
13424        ids: Vec<ExcerptId>,
13425    },
13426    ExcerptsEdited {
13427        ids: Vec<ExcerptId>,
13428    },
13429    ExcerptsExpanded {
13430        ids: Vec<ExcerptId>,
13431    },
13432    BufferEdited,
13433    Edited {
13434        transaction_id: clock::Lamport,
13435    },
13436    Reparsed(BufferId),
13437    Focused,
13438    FocusedIn,
13439    Blurred,
13440    DirtyChanged,
13441    Saved,
13442    TitleChanged,
13443    DiffBaseChanged,
13444    SelectionsChanged {
13445        local: bool,
13446    },
13447    ScrollPositionChanged {
13448        local: bool,
13449        autoscroll: bool,
13450    },
13451    Closed,
13452    TransactionUndone {
13453        transaction_id: clock::Lamport,
13454    },
13455    TransactionBegun {
13456        transaction_id: clock::Lamport,
13457    },
13458    CursorShapeChanged,
13459}
13460
13461impl EventEmitter<EditorEvent> for Editor {}
13462
13463impl FocusableView for Editor {
13464    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13465        self.focus_handle.clone()
13466    }
13467}
13468
13469impl Render for Editor {
13470    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13471        let settings = ThemeSettings::get_global(cx);
13472
13473        let text_style = match self.mode {
13474            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13475                color: cx.theme().colors().editor_foreground,
13476                font_family: settings.ui_font.family.clone(),
13477                font_features: settings.ui_font.features.clone(),
13478                font_fallbacks: settings.ui_font.fallbacks.clone(),
13479                font_size: rems(0.875).into(),
13480                font_weight: settings.ui_font.weight,
13481                line_height: relative(settings.buffer_line_height.value()),
13482                ..Default::default()
13483            },
13484            EditorMode::Full => TextStyle {
13485                color: cx.theme().colors().editor_foreground,
13486                font_family: settings.buffer_font.family.clone(),
13487                font_features: settings.buffer_font.features.clone(),
13488                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13489                font_size: settings.buffer_font_size(cx).into(),
13490                font_weight: settings.buffer_font.weight,
13491                line_height: relative(settings.buffer_line_height.value()),
13492                ..Default::default()
13493            },
13494        };
13495
13496        let background = match self.mode {
13497            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13498            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13499            EditorMode::Full => cx.theme().colors().editor_background,
13500        };
13501
13502        EditorElement::new(
13503            cx.view(),
13504            EditorStyle {
13505                background,
13506                local_player: cx.theme().players().local(),
13507                text: text_style,
13508                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13509                syntax: cx.theme().syntax().clone(),
13510                status: cx.theme().status().clone(),
13511                inlay_hints_style: make_inlay_hints_style(cx),
13512                suggestions_style: HighlightStyle {
13513                    color: Some(cx.theme().status().predictive),
13514                    ..HighlightStyle::default()
13515                },
13516                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13517            },
13518        )
13519    }
13520}
13521
13522impl ViewInputHandler for Editor {
13523    fn text_for_range(
13524        &mut self,
13525        range_utf16: Range<usize>,
13526        cx: &mut ViewContext<Self>,
13527    ) -> Option<String> {
13528        Some(
13529            self.buffer
13530                .read(cx)
13531                .read(cx)
13532                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13533                .collect(),
13534        )
13535    }
13536
13537    fn selected_text_range(
13538        &mut self,
13539        ignore_disabled_input: bool,
13540        cx: &mut ViewContext<Self>,
13541    ) -> Option<UTF16Selection> {
13542        // Prevent the IME menu from appearing when holding down an alphabetic key
13543        // while input is disabled.
13544        if !ignore_disabled_input && !self.input_enabled {
13545            return None;
13546        }
13547
13548        let selection = self.selections.newest::<OffsetUtf16>(cx);
13549        let range = selection.range();
13550
13551        Some(UTF16Selection {
13552            range: range.start.0..range.end.0,
13553            reversed: selection.reversed,
13554        })
13555    }
13556
13557    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13558        let snapshot = self.buffer.read(cx).read(cx);
13559        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13560        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13561    }
13562
13563    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13564        self.clear_highlights::<InputComposition>(cx);
13565        self.ime_transaction.take();
13566    }
13567
13568    fn replace_text_in_range(
13569        &mut self,
13570        range_utf16: Option<Range<usize>>,
13571        text: &str,
13572        cx: &mut ViewContext<Self>,
13573    ) {
13574        if !self.input_enabled {
13575            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13576            return;
13577        }
13578
13579        self.transact(cx, |this, cx| {
13580            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13581                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13582                Some(this.selection_replacement_ranges(range_utf16, cx))
13583            } else {
13584                this.marked_text_ranges(cx)
13585            };
13586
13587            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13588                let newest_selection_id = this.selections.newest_anchor().id;
13589                this.selections
13590                    .all::<OffsetUtf16>(cx)
13591                    .iter()
13592                    .zip(ranges_to_replace.iter())
13593                    .find_map(|(selection, range)| {
13594                        if selection.id == newest_selection_id {
13595                            Some(
13596                                (range.start.0 as isize - selection.head().0 as isize)
13597                                    ..(range.end.0 as isize - selection.head().0 as isize),
13598                            )
13599                        } else {
13600                            None
13601                        }
13602                    })
13603            });
13604
13605            cx.emit(EditorEvent::InputHandled {
13606                utf16_range_to_replace: range_to_replace,
13607                text: text.into(),
13608            });
13609
13610            if let Some(new_selected_ranges) = new_selected_ranges {
13611                this.change_selections(None, cx, |selections| {
13612                    selections.select_ranges(new_selected_ranges)
13613                });
13614                this.backspace(&Default::default(), cx);
13615            }
13616
13617            this.handle_input(text, cx);
13618        });
13619
13620        if let Some(transaction) = self.ime_transaction {
13621            self.buffer.update(cx, |buffer, cx| {
13622                buffer.group_until_transaction(transaction, cx);
13623            });
13624        }
13625
13626        self.unmark_text(cx);
13627    }
13628
13629    fn replace_and_mark_text_in_range(
13630        &mut self,
13631        range_utf16: Option<Range<usize>>,
13632        text: &str,
13633        new_selected_range_utf16: Option<Range<usize>>,
13634        cx: &mut ViewContext<Self>,
13635    ) {
13636        if !self.input_enabled {
13637            return;
13638        }
13639
13640        let transaction = self.transact(cx, |this, cx| {
13641            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13642                let snapshot = this.buffer.read(cx).read(cx);
13643                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13644                    for marked_range in &mut marked_ranges {
13645                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13646                        marked_range.start.0 += relative_range_utf16.start;
13647                        marked_range.start =
13648                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13649                        marked_range.end =
13650                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13651                    }
13652                }
13653                Some(marked_ranges)
13654            } else if let Some(range_utf16) = range_utf16 {
13655                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13656                Some(this.selection_replacement_ranges(range_utf16, cx))
13657            } else {
13658                None
13659            };
13660
13661            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13662                let newest_selection_id = this.selections.newest_anchor().id;
13663                this.selections
13664                    .all::<OffsetUtf16>(cx)
13665                    .iter()
13666                    .zip(ranges_to_replace.iter())
13667                    .find_map(|(selection, range)| {
13668                        if selection.id == newest_selection_id {
13669                            Some(
13670                                (range.start.0 as isize - selection.head().0 as isize)
13671                                    ..(range.end.0 as isize - selection.head().0 as isize),
13672                            )
13673                        } else {
13674                            None
13675                        }
13676                    })
13677            });
13678
13679            cx.emit(EditorEvent::InputHandled {
13680                utf16_range_to_replace: range_to_replace,
13681                text: text.into(),
13682            });
13683
13684            if let Some(ranges) = ranges_to_replace {
13685                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13686            }
13687
13688            let marked_ranges = {
13689                let snapshot = this.buffer.read(cx).read(cx);
13690                this.selections
13691                    .disjoint_anchors()
13692                    .iter()
13693                    .map(|selection| {
13694                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13695                    })
13696                    .collect::<Vec<_>>()
13697            };
13698
13699            if text.is_empty() {
13700                this.unmark_text(cx);
13701            } else {
13702                this.highlight_text::<InputComposition>(
13703                    marked_ranges.clone(),
13704                    HighlightStyle {
13705                        underline: Some(UnderlineStyle {
13706                            thickness: px(1.),
13707                            color: None,
13708                            wavy: false,
13709                        }),
13710                        ..Default::default()
13711                    },
13712                    cx,
13713                );
13714            }
13715
13716            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13717            let use_autoclose = this.use_autoclose;
13718            let use_auto_surround = this.use_auto_surround;
13719            this.set_use_autoclose(false);
13720            this.set_use_auto_surround(false);
13721            this.handle_input(text, cx);
13722            this.set_use_autoclose(use_autoclose);
13723            this.set_use_auto_surround(use_auto_surround);
13724
13725            if let Some(new_selected_range) = new_selected_range_utf16 {
13726                let snapshot = this.buffer.read(cx).read(cx);
13727                let new_selected_ranges = marked_ranges
13728                    .into_iter()
13729                    .map(|marked_range| {
13730                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13731                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13732                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13733                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13734                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13735                    })
13736                    .collect::<Vec<_>>();
13737
13738                drop(snapshot);
13739                this.change_selections(None, cx, |selections| {
13740                    selections.select_ranges(new_selected_ranges)
13741                });
13742            }
13743        });
13744
13745        self.ime_transaction = self.ime_transaction.or(transaction);
13746        if let Some(transaction) = self.ime_transaction {
13747            self.buffer.update(cx, |buffer, cx| {
13748                buffer.group_until_transaction(transaction, cx);
13749            });
13750        }
13751
13752        if self.text_highlights::<InputComposition>(cx).is_none() {
13753            self.ime_transaction.take();
13754        }
13755    }
13756
13757    fn bounds_for_range(
13758        &mut self,
13759        range_utf16: Range<usize>,
13760        element_bounds: gpui::Bounds<Pixels>,
13761        cx: &mut ViewContext<Self>,
13762    ) -> Option<gpui::Bounds<Pixels>> {
13763        let text_layout_details = self.text_layout_details(cx);
13764        let style = &text_layout_details.editor_style;
13765        let font_id = cx.text_system().resolve_font(&style.text.font());
13766        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13767        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13768
13769        let em_width = cx
13770            .text_system()
13771            .typographic_bounds(font_id, font_size, 'm')
13772            .unwrap()
13773            .size
13774            .width;
13775
13776        let snapshot = self.snapshot(cx);
13777        let scroll_position = snapshot.scroll_position();
13778        let scroll_left = scroll_position.x * em_width;
13779
13780        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13781        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13782            + self.gutter_dimensions.width;
13783        let y = line_height * (start.row().as_f32() - scroll_position.y);
13784
13785        Some(Bounds {
13786            origin: element_bounds.origin + point(x, y),
13787            size: size(em_width, line_height),
13788        })
13789    }
13790}
13791
13792trait SelectionExt {
13793    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13794    fn spanned_rows(
13795        &self,
13796        include_end_if_at_line_start: bool,
13797        map: &DisplaySnapshot,
13798    ) -> Range<MultiBufferRow>;
13799}
13800
13801impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13802    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13803        let start = self
13804            .start
13805            .to_point(&map.buffer_snapshot)
13806            .to_display_point(map);
13807        let end = self
13808            .end
13809            .to_point(&map.buffer_snapshot)
13810            .to_display_point(map);
13811        if self.reversed {
13812            end..start
13813        } else {
13814            start..end
13815        }
13816    }
13817
13818    fn spanned_rows(
13819        &self,
13820        include_end_if_at_line_start: bool,
13821        map: &DisplaySnapshot,
13822    ) -> Range<MultiBufferRow> {
13823        let start = self.start.to_point(&map.buffer_snapshot);
13824        let mut end = self.end.to_point(&map.buffer_snapshot);
13825        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13826            end.row -= 1;
13827        }
13828
13829        let buffer_start = map.prev_line_boundary(start).0;
13830        let buffer_end = map.next_line_boundary(end).0;
13831        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13832    }
13833}
13834
13835impl<T: InvalidationRegion> InvalidationStack<T> {
13836    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13837    where
13838        S: Clone + ToOffset,
13839    {
13840        while let Some(region) = self.last() {
13841            let all_selections_inside_invalidation_ranges =
13842                if selections.len() == region.ranges().len() {
13843                    selections
13844                        .iter()
13845                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13846                        .all(|(selection, invalidation_range)| {
13847                            let head = selection.head().to_offset(buffer);
13848                            invalidation_range.start <= head && invalidation_range.end >= head
13849                        })
13850                } else {
13851                    false
13852                };
13853
13854            if all_selections_inside_invalidation_ranges {
13855                break;
13856            } else {
13857                self.pop();
13858            }
13859        }
13860    }
13861}
13862
13863impl<T> Default for InvalidationStack<T> {
13864    fn default() -> Self {
13865        Self(Default::default())
13866    }
13867}
13868
13869impl<T> Deref for InvalidationStack<T> {
13870    type Target = Vec<T>;
13871
13872    fn deref(&self) -> &Self::Target {
13873        &self.0
13874    }
13875}
13876
13877impl<T> DerefMut for InvalidationStack<T> {
13878    fn deref_mut(&mut self) -> &mut Self::Target {
13879        &mut self.0
13880    }
13881}
13882
13883impl InvalidationRegion for SnippetState {
13884    fn ranges(&self) -> &[Range<Anchor>] {
13885        &self.ranges[self.active_index]
13886    }
13887}
13888
13889pub fn diagnostic_block_renderer(
13890    diagnostic: Diagnostic,
13891    max_message_rows: Option<u8>,
13892    allow_closing: bool,
13893    _is_valid: bool,
13894) -> RenderBlock {
13895    let (text_without_backticks, code_ranges) =
13896        highlight_diagnostic_message(&diagnostic, max_message_rows);
13897
13898    Box::new(move |cx: &mut BlockContext| {
13899        let group_id: SharedString = cx.block_id.to_string().into();
13900
13901        let mut text_style = cx.text_style().clone();
13902        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13903        let theme_settings = ThemeSettings::get_global(cx);
13904        text_style.font_family = theme_settings.buffer_font.family.clone();
13905        text_style.font_style = theme_settings.buffer_font.style;
13906        text_style.font_features = theme_settings.buffer_font.features.clone();
13907        text_style.font_weight = theme_settings.buffer_font.weight;
13908
13909        let multi_line_diagnostic = diagnostic.message.contains('\n');
13910
13911        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13912            if multi_line_diagnostic {
13913                v_flex()
13914            } else {
13915                h_flex()
13916            }
13917            .when(allow_closing, |div| {
13918                div.children(diagnostic.is_primary.then(|| {
13919                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13920                        .icon_color(Color::Muted)
13921                        .size(ButtonSize::Compact)
13922                        .style(ButtonStyle::Transparent)
13923                        .visible_on_hover(group_id.clone())
13924                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13925                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13926                }))
13927            })
13928            .child(
13929                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13930                    .icon_color(Color::Muted)
13931                    .size(ButtonSize::Compact)
13932                    .style(ButtonStyle::Transparent)
13933                    .visible_on_hover(group_id.clone())
13934                    .on_click({
13935                        let message = diagnostic.message.clone();
13936                        move |_click, cx| {
13937                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13938                        }
13939                    })
13940                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13941            )
13942        };
13943
13944        let icon_size = buttons(&diagnostic, cx.block_id)
13945            .into_any_element()
13946            .layout_as_root(AvailableSpace::min_size(), cx);
13947
13948        h_flex()
13949            .id(cx.block_id)
13950            .group(group_id.clone())
13951            .relative()
13952            .size_full()
13953            .pl(cx.gutter_dimensions.width)
13954            .w(cx.max_width + cx.gutter_dimensions.width)
13955            .child(
13956                div()
13957                    .flex()
13958                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13959                    .flex_shrink(),
13960            )
13961            .child(buttons(&diagnostic, cx.block_id))
13962            .child(div().flex().flex_shrink_0().child(
13963                StyledText::new(text_without_backticks.clone()).with_highlights(
13964                    &text_style,
13965                    code_ranges.iter().map(|range| {
13966                        (
13967                            range.clone(),
13968                            HighlightStyle {
13969                                font_weight: Some(FontWeight::BOLD),
13970                                ..Default::default()
13971                            },
13972                        )
13973                    }),
13974                ),
13975            ))
13976            .into_any_element()
13977    })
13978}
13979
13980pub fn highlight_diagnostic_message(
13981    diagnostic: &Diagnostic,
13982    mut max_message_rows: Option<u8>,
13983) -> (SharedString, Vec<Range<usize>>) {
13984    let mut text_without_backticks = String::new();
13985    let mut code_ranges = Vec::new();
13986
13987    if let Some(source) = &diagnostic.source {
13988        text_without_backticks.push_str(source);
13989        code_ranges.push(0..source.len());
13990        text_without_backticks.push_str(": ");
13991    }
13992
13993    let mut prev_offset = 0;
13994    let mut in_code_block = false;
13995    let has_row_limit = max_message_rows.is_some();
13996    let mut newline_indices = diagnostic
13997        .message
13998        .match_indices('\n')
13999        .filter(|_| has_row_limit)
14000        .map(|(ix, _)| ix)
14001        .fuse()
14002        .peekable();
14003
14004    for (quote_ix, _) in diagnostic
14005        .message
14006        .match_indices('`')
14007        .chain([(diagnostic.message.len(), "")])
14008    {
14009        let mut first_newline_ix = None;
14010        let mut last_newline_ix = None;
14011        while let Some(newline_ix) = newline_indices.peek() {
14012            if *newline_ix < quote_ix {
14013                if first_newline_ix.is_none() {
14014                    first_newline_ix = Some(*newline_ix);
14015                }
14016                last_newline_ix = Some(*newline_ix);
14017
14018                if let Some(rows_left) = &mut max_message_rows {
14019                    if *rows_left == 0 {
14020                        break;
14021                    } else {
14022                        *rows_left -= 1;
14023                    }
14024                }
14025                let _ = newline_indices.next();
14026            } else {
14027                break;
14028            }
14029        }
14030        let prev_len = text_without_backticks.len();
14031        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14032        text_without_backticks.push_str(new_text);
14033        if in_code_block {
14034            code_ranges.push(prev_len..text_without_backticks.len());
14035        }
14036        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14037        in_code_block = !in_code_block;
14038        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14039            text_without_backticks.push_str("...");
14040            break;
14041        }
14042    }
14043
14044    (text_without_backticks.into(), code_ranges)
14045}
14046
14047fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14048    match severity {
14049        DiagnosticSeverity::ERROR => colors.error,
14050        DiagnosticSeverity::WARNING => colors.warning,
14051        DiagnosticSeverity::INFORMATION => colors.info,
14052        DiagnosticSeverity::HINT => colors.info,
14053        _ => colors.ignored,
14054    }
14055}
14056
14057pub fn styled_runs_for_code_label<'a>(
14058    label: &'a CodeLabel,
14059    syntax_theme: &'a theme::SyntaxTheme,
14060) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14061    let fade_out = HighlightStyle {
14062        fade_out: Some(0.35),
14063        ..Default::default()
14064    };
14065
14066    let mut prev_end = label.filter_range.end;
14067    label
14068        .runs
14069        .iter()
14070        .enumerate()
14071        .flat_map(move |(ix, (range, highlight_id))| {
14072            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14073                style
14074            } else {
14075                return Default::default();
14076            };
14077            let mut muted_style = style;
14078            muted_style.highlight(fade_out);
14079
14080            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14081            if range.start >= label.filter_range.end {
14082                if range.start > prev_end {
14083                    runs.push((prev_end..range.start, fade_out));
14084                }
14085                runs.push((range.clone(), muted_style));
14086            } else if range.end <= label.filter_range.end {
14087                runs.push((range.clone(), style));
14088            } else {
14089                runs.push((range.start..label.filter_range.end, style));
14090                runs.push((label.filter_range.end..range.end, muted_style));
14091            }
14092            prev_end = cmp::max(prev_end, range.end);
14093
14094            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14095                runs.push((prev_end..label.text.len(), fade_out));
14096            }
14097
14098            runs
14099        })
14100}
14101
14102pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14103    let mut prev_index = 0;
14104    let mut prev_codepoint: Option<char> = None;
14105    text.char_indices()
14106        .chain([(text.len(), '\0')])
14107        .filter_map(move |(index, codepoint)| {
14108            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14109            let is_boundary = index == text.len()
14110                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14111                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14112            if is_boundary {
14113                let chunk = &text[prev_index..index];
14114                prev_index = index;
14115                Some(chunk)
14116            } else {
14117                None
14118            }
14119        })
14120}
14121
14122pub trait RangeToAnchorExt: Sized {
14123    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14124
14125    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14126        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14127        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14128    }
14129}
14130
14131impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14132    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14133        let start_offset = self.start.to_offset(snapshot);
14134        let end_offset = self.end.to_offset(snapshot);
14135        if start_offset == end_offset {
14136            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14137        } else {
14138            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14139        }
14140    }
14141}
14142
14143pub trait RowExt {
14144    fn as_f32(&self) -> f32;
14145
14146    fn next_row(&self) -> Self;
14147
14148    fn previous_row(&self) -> Self;
14149
14150    fn minus(&self, other: Self) -> u32;
14151}
14152
14153impl RowExt for DisplayRow {
14154    fn as_f32(&self) -> f32 {
14155        self.0 as f32
14156    }
14157
14158    fn next_row(&self) -> Self {
14159        Self(self.0 + 1)
14160    }
14161
14162    fn previous_row(&self) -> Self {
14163        Self(self.0.saturating_sub(1))
14164    }
14165
14166    fn minus(&self, other: Self) -> u32 {
14167        self.0 - other.0
14168    }
14169}
14170
14171impl RowExt for MultiBufferRow {
14172    fn as_f32(&self) -> f32 {
14173        self.0 as f32
14174    }
14175
14176    fn next_row(&self) -> Self {
14177        Self(self.0 + 1)
14178    }
14179
14180    fn previous_row(&self) -> Self {
14181        Self(self.0.saturating_sub(1))
14182    }
14183
14184    fn minus(&self, other: Self) -> u32 {
14185        self.0 - other.0
14186    }
14187}
14188
14189trait RowRangeExt {
14190    type Row;
14191
14192    fn len(&self) -> usize;
14193
14194    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14195}
14196
14197impl RowRangeExt for Range<MultiBufferRow> {
14198    type Row = MultiBufferRow;
14199
14200    fn len(&self) -> usize {
14201        (self.end.0 - self.start.0) as usize
14202    }
14203
14204    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14205        (self.start.0..self.end.0).map(MultiBufferRow)
14206    }
14207}
14208
14209impl RowRangeExt for Range<DisplayRow> {
14210    type Row = DisplayRow;
14211
14212    fn len(&self) -> usize {
14213        (self.end.0 - self.start.0) as usize
14214    }
14215
14216    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14217        (self.start.0..self.end.0).map(DisplayRow)
14218    }
14219}
14220
14221fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14222    if hunk.diff_base_byte_range.is_empty() {
14223        DiffHunkStatus::Added
14224    } else if hunk.row_range.is_empty() {
14225        DiffHunkStatus::Removed
14226    } else {
14227        DiffHunkStatus::Modified
14228    }
14229}
14230
14231/// If select range has more than one line, we
14232/// just point the cursor to range.start.
14233fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14234    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14235        range
14236    } else {
14237        range.start..range.start
14238    }
14239}