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;
   51pub(crate) use actions::*;
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use debounced_delay::DebouncedDelay;
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use gpui::{
   74    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   75    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   76    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   77    FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   78    ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   79    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   80    TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   81    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   82};
   83use highlight_matching_bracket::refresh_matching_bracket_highlights;
   84use hover_popover::{hide_hover, HoverState};
   85pub(crate) use hunk_diff::HoveredHunk;
   86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   87use indent_guides::ActiveIndentGuidesState;
   88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   89pub use inline_completion_provider::*;
   90pub use items::MAX_TAB_TITLE_LEN;
   91use itertools::Itertools;
   92use language::{
   93    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   94    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   95    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   96    Point, Selection, SelectionGoal, TransactionId,
   97};
   98use language::{
   99    point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
  100};
  101use linked_editing_ranges::refresh_linked_ranges;
  102pub use proposed_changes_editor::{
  103    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  104};
  105use similar::{ChangeTag, TextDiff};
  106use task::{ResolvedTask, TaskTemplate, TaskVariables};
  107
  108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  109pub use lsp::CompletionContext;
  110use lsp::{
  111    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  112    LanguageServerId,
  113};
  114use mouse_context_menu::MouseContextMenu;
  115use movement::TextLayoutDetails;
  116pub use multi_buffer::{
  117    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  118    ToPoint,
  119};
  120use multi_buffer::{
  121    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  122};
  123use ordered_float::OrderedFloat;
  124use parking_lot::{Mutex, RwLock};
  125use project::{
  126    lsp_store::{FormatTarget, FormatTrigger},
  127    project_settings::{GitGutterSetting, ProjectSettings},
  128    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  129    LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
  130};
  131use rand::prelude::*;
  132use rpc::{proto::*, ErrorExt};
  133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  134use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  135use serde::{Deserialize, Serialize};
  136use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  137use smallvec::SmallVec;
  138use snippet::Snippet;
  139use std::{
  140    any::TypeId,
  141    borrow::Cow,
  142    cell::RefCell,
  143    cmp::{self, Ordering, Reverse},
  144    mem,
  145    num::NonZeroU32,
  146    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  147    path::{Path, PathBuf},
  148    rc::Rc,
  149    sync::Arc,
  150    time::{Duration, Instant},
  151};
  152pub use sum_tree::Bias;
  153use sum_tree::TreeMap;
  154use text::{BufferId, OffsetUtf16, Rope};
  155use theme::{
  156    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  157    ThemeColors, ThemeSettings,
  158};
  159use ui::{
  160    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  161    ListItem, Popover, PopoverMenuHandle, Tooltip,
  162};
  163use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  164use workspace::item::{ItemHandle, PreviewTabsSettings};
  165use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  166use workspace::{
  167    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  168};
  169use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  170
  171use crate::hover_links::find_url;
  172use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  173
  174pub const FILE_HEADER_HEIGHT: u32 = 2;
  175pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  176pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  177pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  178const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  179const MAX_LINE_LEN: usize = 1024;
  180const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  181const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  182pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  183#[doc(hidden)]
  184pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  185#[doc(hidden)]
  186pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  187
  188pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  189pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  190
  191pub fn render_parsed_markdown(
  192    element_id: impl Into<ElementId>,
  193    parsed: &language::ParsedMarkdown,
  194    editor_style: &EditorStyle,
  195    workspace: Option<WeakView<Workspace>>,
  196    cx: &mut WindowContext,
  197) -> InteractiveText {
  198    let code_span_background_color = cx
  199        .theme()
  200        .colors()
  201        .editor_document_highlight_read_background;
  202
  203    let highlights = gpui::combine_highlights(
  204        parsed.highlights.iter().filter_map(|(range, highlight)| {
  205            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  206            Some((range.clone(), highlight))
  207        }),
  208        parsed
  209            .regions
  210            .iter()
  211            .zip(&parsed.region_ranges)
  212            .filter_map(|(region, range)| {
  213                if region.code {
  214                    Some((
  215                        range.clone(),
  216                        HighlightStyle {
  217                            background_color: Some(code_span_background_color),
  218                            ..Default::default()
  219                        },
  220                    ))
  221                } else {
  222                    None
  223                }
  224            }),
  225    );
  226
  227    let mut links = Vec::new();
  228    let mut link_ranges = Vec::new();
  229    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  230        if let Some(link) = region.link.clone() {
  231            links.push(link);
  232            link_ranges.push(range.clone());
  233        }
  234    }
  235
  236    InteractiveText::new(
  237        element_id,
  238        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  239    )
  240    .on_click(link_ranges, move |clicked_range_ix, cx| {
  241        match &links[clicked_range_ix] {
  242            markdown::Link::Web { url } => cx.open_url(url),
  243            markdown::Link::Path { path } => {
  244                if let Some(workspace) = &workspace {
  245                    _ = workspace.update(cx, |workspace, cx| {
  246                        workspace.open_abs_path(path.clone(), false, cx).detach();
  247                    });
  248                }
  249            }
  250        }
  251    })
  252}
  253
  254#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  255pub(crate) enum InlayId {
  256    Suggestion(usize),
  257    Hint(usize),
  258}
  259
  260impl InlayId {
  261    fn id(&self) -> usize {
  262        match self {
  263            Self::Suggestion(id) => *id,
  264            Self::Hint(id) => *id,
  265        }
  266    }
  267}
  268
  269enum DiffRowHighlight {}
  270enum DocumentHighlightRead {}
  271enum DocumentHighlightWrite {}
  272enum InputComposition {}
  273
  274#[derive(Copy, Clone, PartialEq, Eq)]
  275pub enum Direction {
  276    Prev,
  277    Next,
  278}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334}
  335
  336pub struct SearchWithinRange;
  337
  338trait InvalidationRegion {
  339    fn ranges(&self) -> &[Range<Anchor>];
  340}
  341
  342#[derive(Clone, Debug, PartialEq)]
  343pub enum SelectPhase {
  344    Begin {
  345        position: DisplayPoint,
  346        add: bool,
  347        click_count: usize,
  348    },
  349    BeginColumnar {
  350        position: DisplayPoint,
  351        reset: bool,
  352        goal_column: u32,
  353    },
  354    Extend {
  355        position: DisplayPoint,
  356        click_count: usize,
  357    },
  358    Update {
  359        position: DisplayPoint,
  360        goal_column: u32,
  361        scroll_delta: gpui::Point<f32>,
  362    },
  363    End,
  364}
  365
  366#[derive(Clone, Debug)]
  367pub enum SelectMode {
  368    Character,
  369    Word(Range<Anchor>),
  370    Line(Range<Anchor>),
  371    All,
  372}
  373
  374#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  375pub enum EditorMode {
  376    SingleLine { auto_width: bool },
  377    AutoHeight { max_lines: usize },
  378    Full,
  379}
  380
  381#[derive(Copy, Clone, Debug)]
  382pub enum SoftWrap {
  383    /// Prefer not to wrap at all.
  384    ///
  385    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  386    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  387    GitDiff,
  388    /// Prefer a single line generally, unless an overly long line is encountered.
  389    None,
  390    /// Soft wrap lines that exceed the editor width.
  391    EditorWidth,
  392    /// Soft wrap lines at the preferred line length.
  393    Column(u32),
  394    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  395    Bounded(u32),
  396}
  397
  398#[derive(Clone)]
  399pub struct EditorStyle {
  400    pub background: Hsla,
  401    pub local_player: PlayerColor,
  402    pub text: TextStyle,
  403    pub scrollbar_width: Pixels,
  404    pub syntax: Arc<SyntaxTheme>,
  405    pub status: StatusColors,
  406    pub inlay_hints_style: HighlightStyle,
  407    pub suggestions_style: HighlightStyle,
  408    pub unnecessary_code_fade: f32,
  409}
  410
  411impl Default for EditorStyle {
  412    fn default() -> Self {
  413        Self {
  414            background: Hsla::default(),
  415            local_player: PlayerColor::default(),
  416            text: TextStyle::default(),
  417            scrollbar_width: Pixels::default(),
  418            syntax: Default::default(),
  419            // HACK: Status colors don't have a real default.
  420            // We should look into removing the status colors from the editor
  421            // style and retrieve them directly from the theme.
  422            status: StatusColors::dark(),
  423            inlay_hints_style: HighlightStyle::default(),
  424            suggestions_style: HighlightStyle::default(),
  425            unnecessary_code_fade: Default::default(),
  426        }
  427    }
  428}
  429
  430pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  431    let show_background = language_settings::language_settings(None, None, cx)
  432        .inlay_hints
  433        .show_background;
  434
  435    HighlightStyle {
  436        color: Some(cx.theme().status().hint),
  437        background_color: show_background.then(|| cx.theme().status().hint_background),
  438        ..HighlightStyle::default()
  439    }
  440}
  441
  442type CompletionId = usize;
  443
  444#[derive(Clone, Debug)]
  445struct CompletionState {
  446    // render_inlay_ids represents the inlay hints that are inserted
  447    // for rendering the inline completions. They may be discontinuous
  448    // in the event that the completion provider returns some intersection
  449    // with the existing content.
  450    render_inlay_ids: Vec<InlayId>,
  451    // text is the resulting rope that is inserted when the user accepts a completion.
  452    text: Rope,
  453    // position is the position of the cursor when the completion was triggered.
  454    position: multi_buffer::Anchor,
  455    // delete_range is the range of text that this completion state covers.
  456    // if the completion is accepted, this range should be deleted.
  457    delete_range: Option<Range<multi_buffer::Anchor>>,
  458}
  459
  460#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  461struct EditorActionId(usize);
  462
  463impl EditorActionId {
  464    pub fn post_inc(&mut self) -> Self {
  465        let answer = self.0;
  466
  467        *self = Self(answer + 1);
  468
  469        Self(answer)
  470    }
  471}
  472
  473// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  474// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  475
  476type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  477type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  478
  479#[derive(Default)]
  480struct ScrollbarMarkerState {
  481    scrollbar_size: Size<Pixels>,
  482    dirty: bool,
  483    markers: Arc<[PaintQuad]>,
  484    pending_refresh: Option<Task<Result<()>>>,
  485}
  486
  487impl ScrollbarMarkerState {
  488    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  489        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  490    }
  491}
  492
  493#[derive(Clone, Debug)]
  494struct RunnableTasks {
  495    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  496    offset: MultiBufferOffset,
  497    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  498    column: u32,
  499    // Values of all named captures, including those starting with '_'
  500    extra_variables: HashMap<String, String>,
  501    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  502    context_range: Range<BufferOffset>,
  503}
  504
  505#[derive(Clone)]
  506struct ResolvedTasks {
  507    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  508    position: Anchor,
  509}
  510#[derive(Copy, Clone, Debug)]
  511struct MultiBufferOffset(usize);
  512#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  513struct BufferOffset(usize);
  514
  515// Addons allow storing per-editor state in other crates (e.g. Vim)
  516pub trait Addon: 'static {
  517    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  518
  519    fn to_any(&self) -> &dyn std::any::Any;
  520}
  521
  522/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  523///
  524/// See the [module level documentation](self) for more information.
  525pub struct Editor {
  526    focus_handle: FocusHandle,
  527    last_focused_descendant: Option<WeakFocusHandle>,
  528    /// The text buffer being edited
  529    buffer: Model<MultiBuffer>,
  530    /// Map of how text in the buffer should be displayed.
  531    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  532    pub display_map: Model<DisplayMap>,
  533    pub selections: SelectionsCollection,
  534    pub scroll_manager: ScrollManager,
  535    /// When inline assist editors are linked, they all render cursors because
  536    /// typing enters text into each of them, even the ones that aren't focused.
  537    pub(crate) show_cursor_when_unfocused: bool,
  538    columnar_selection_tail: Option<Anchor>,
  539    add_selections_state: Option<AddSelectionsState>,
  540    select_next_state: Option<SelectNextState>,
  541    select_prev_state: Option<SelectNextState>,
  542    selection_history: SelectionHistory,
  543    autoclose_regions: Vec<AutocloseRegion>,
  544    snippet_stack: InvalidationStack<SnippetState>,
  545    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  546    ime_transaction: Option<TransactionId>,
  547    active_diagnostics: Option<ActiveDiagnosticGroup>,
  548    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  549
  550    project: Option<Model<Project>>,
  551    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  552    completion_provider: Option<Box<dyn CompletionProvider>>,
  553    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  554    blink_manager: Model<BlinkManager>,
  555    show_cursor_names: bool,
  556    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  557    pub show_local_selections: bool,
  558    mode: EditorMode,
  559    show_breadcrumbs: bool,
  560    show_gutter: bool,
  561    show_line_numbers: Option<bool>,
  562    use_relative_line_numbers: Option<bool>,
  563    show_git_diff_gutter: Option<bool>,
  564    show_code_actions: Option<bool>,
  565    show_runnables: Option<bool>,
  566    show_wrap_guides: Option<bool>,
  567    show_indent_guides: Option<bool>,
  568    placeholder_text: Option<Arc<str>>,
  569    highlight_order: usize,
  570    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  571    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  572    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  573    scrollbar_marker_state: ScrollbarMarkerState,
  574    active_indent_guides_state: ActiveIndentGuidesState,
  575    nav_history: Option<ItemNavHistory>,
  576    context_menu: RwLock<Option<ContextMenu>>,
  577    mouse_context_menu: Option<MouseContextMenu>,
  578    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  579    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  580    signature_help_state: SignatureHelpState,
  581    auto_signature_help: Option<bool>,
  582    find_all_references_task_sources: Vec<Anchor>,
  583    next_completion_id: CompletionId,
  584    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  585    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  586    code_actions_task: Option<Task<Result<()>>>,
  587    document_highlights_task: Option<Task<()>>,
  588    linked_editing_range_task: Option<Task<Option<()>>>,
  589    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  590    pending_rename: Option<RenameState>,
  591    searchable: bool,
  592    cursor_shape: CursorShape,
  593    current_line_highlight: Option<CurrentLineHighlight>,
  594    collapse_matches: bool,
  595    autoindent_mode: Option<AutoindentMode>,
  596    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  597    input_enabled: bool,
  598    use_modal_editing: bool,
  599    read_only: bool,
  600    leader_peer_id: Option<PeerId>,
  601    remote_id: Option<ViewId>,
  602    hover_state: HoverState,
  603    gutter_hovered: bool,
  604    hovered_link_state: Option<HoveredLinkState>,
  605    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  606    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  607    active_inline_completion: Option<CompletionState>,
  608    // enable_inline_completions is a switch that Vim can use to disable
  609    // inline completions based on its mode.
  610    enable_inline_completions: bool,
  611    show_inline_completions_override: Option<bool>,
  612    inlay_hint_cache: InlayHintCache,
  613    expanded_hunks: ExpandedHunks,
  614    next_inlay_id: usize,
  615    _subscriptions: Vec<Subscription>,
  616    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  617    gutter_dimensions: GutterDimensions,
  618    style: Option<EditorStyle>,
  619    text_style_refinement: Option<TextStyleRefinement>,
  620    next_editor_action_id: EditorActionId,
  621    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  622    use_autoclose: bool,
  623    use_auto_surround: bool,
  624    auto_replace_emoji_shortcode: bool,
  625    show_git_blame_gutter: bool,
  626    show_git_blame_inline: bool,
  627    show_git_blame_inline_delay_task: Option<Task<()>>,
  628    git_blame_inline_enabled: bool,
  629    serialize_dirty_buffers: bool,
  630    show_selection_menu: Option<bool>,
  631    blame: Option<Model<GitBlame>>,
  632    blame_subscription: Option<Subscription>,
  633    custom_context_menu: Option<
  634        Box<
  635            dyn 'static
  636                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  637        >,
  638    >,
  639    last_bounds: Option<Bounds<Pixels>>,
  640    expect_bounds_change: Option<Bounds<Pixels>>,
  641    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  642    tasks_update_task: Option<Task<()>>,
  643    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  644    breadcrumb_header: Option<String>,
  645    focused_block: Option<FocusedBlock>,
  646    next_scroll_position: NextScrollCursorCenterTopBottom,
  647    addons: HashMap<TypeId, Box<dyn Addon>>,
  648    _scroll_cursor_center_top_bottom_task: Task<()>,
  649}
  650
  651#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  652enum NextScrollCursorCenterTopBottom {
  653    #[default]
  654    Center,
  655    Top,
  656    Bottom,
  657}
  658
  659impl NextScrollCursorCenterTopBottom {
  660    fn next(&self) -> Self {
  661        match self {
  662            Self::Center => Self::Top,
  663            Self::Top => Self::Bottom,
  664            Self::Bottom => Self::Center,
  665        }
  666    }
  667}
  668
  669#[derive(Clone)]
  670pub struct EditorSnapshot {
  671    pub mode: EditorMode,
  672    show_gutter: bool,
  673    show_line_numbers: Option<bool>,
  674    show_git_diff_gutter: Option<bool>,
  675    show_code_actions: Option<bool>,
  676    show_runnables: Option<bool>,
  677    git_blame_gutter_max_author_length: Option<usize>,
  678    pub display_snapshot: DisplaySnapshot,
  679    pub placeholder_text: Option<Arc<str>>,
  680    is_focused: bool,
  681    scroll_anchor: ScrollAnchor,
  682    ongoing_scroll: OngoingScroll,
  683    current_line_highlight: CurrentLineHighlight,
  684    gutter_hovered: bool,
  685}
  686
  687const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  688
  689#[derive(Default, Debug, Clone, Copy)]
  690pub struct GutterDimensions {
  691    pub left_padding: Pixels,
  692    pub right_padding: Pixels,
  693    pub width: Pixels,
  694    pub margin: Pixels,
  695    pub git_blame_entries_width: Option<Pixels>,
  696}
  697
  698impl GutterDimensions {
  699    /// The full width of the space taken up by the gutter.
  700    pub fn full_width(&self) -> Pixels {
  701        self.margin + self.width
  702    }
  703
  704    /// The width of the space reserved for the fold indicators,
  705    /// use alongside 'justify_end' and `gutter_width` to
  706    /// right align content with the line numbers
  707    pub fn fold_area_width(&self) -> Pixels {
  708        self.margin + self.right_padding
  709    }
  710}
  711
  712#[derive(Debug)]
  713pub struct RemoteSelection {
  714    pub replica_id: ReplicaId,
  715    pub selection: Selection<Anchor>,
  716    pub cursor_shape: CursorShape,
  717    pub peer_id: PeerId,
  718    pub line_mode: bool,
  719    pub participant_index: Option<ParticipantIndex>,
  720    pub user_name: Option<SharedString>,
  721}
  722
  723#[derive(Clone, Debug)]
  724struct SelectionHistoryEntry {
  725    selections: Arc<[Selection<Anchor>]>,
  726    select_next_state: Option<SelectNextState>,
  727    select_prev_state: Option<SelectNextState>,
  728    add_selections_state: Option<AddSelectionsState>,
  729}
  730
  731enum SelectionHistoryMode {
  732    Normal,
  733    Undoing,
  734    Redoing,
  735}
  736
  737#[derive(Clone, PartialEq, Eq, Hash)]
  738struct HoveredCursor {
  739    replica_id: u16,
  740    selection_id: usize,
  741}
  742
  743impl Default for SelectionHistoryMode {
  744    fn default() -> Self {
  745        Self::Normal
  746    }
  747}
  748
  749#[derive(Default)]
  750struct SelectionHistory {
  751    #[allow(clippy::type_complexity)]
  752    selections_by_transaction:
  753        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  754    mode: SelectionHistoryMode,
  755    undo_stack: VecDeque<SelectionHistoryEntry>,
  756    redo_stack: VecDeque<SelectionHistoryEntry>,
  757}
  758
  759impl SelectionHistory {
  760    fn insert_transaction(
  761        &mut self,
  762        transaction_id: TransactionId,
  763        selections: Arc<[Selection<Anchor>]>,
  764    ) {
  765        self.selections_by_transaction
  766            .insert(transaction_id, (selections, None));
  767    }
  768
  769    #[allow(clippy::type_complexity)]
  770    fn transaction(
  771        &self,
  772        transaction_id: TransactionId,
  773    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  774        self.selections_by_transaction.get(&transaction_id)
  775    }
  776
  777    #[allow(clippy::type_complexity)]
  778    fn transaction_mut(
  779        &mut self,
  780        transaction_id: TransactionId,
  781    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  782        self.selections_by_transaction.get_mut(&transaction_id)
  783    }
  784
  785    fn push(&mut self, entry: SelectionHistoryEntry) {
  786        if !entry.selections.is_empty() {
  787            match self.mode {
  788                SelectionHistoryMode::Normal => {
  789                    self.push_undo(entry);
  790                    self.redo_stack.clear();
  791                }
  792                SelectionHistoryMode::Undoing => self.push_redo(entry),
  793                SelectionHistoryMode::Redoing => self.push_undo(entry),
  794            }
  795        }
  796    }
  797
  798    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  799        if self
  800            .undo_stack
  801            .back()
  802            .map_or(true, |e| e.selections != entry.selections)
  803        {
  804            self.undo_stack.push_back(entry);
  805            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  806                self.undo_stack.pop_front();
  807            }
  808        }
  809    }
  810
  811    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  812        if self
  813            .redo_stack
  814            .back()
  815            .map_or(true, |e| e.selections != entry.selections)
  816        {
  817            self.redo_stack.push_back(entry);
  818            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  819                self.redo_stack.pop_front();
  820            }
  821        }
  822    }
  823}
  824
  825struct RowHighlight {
  826    index: usize,
  827    range: Range<Anchor>,
  828    color: Hsla,
  829    should_autoscroll: bool,
  830}
  831
  832#[derive(Clone, Debug)]
  833struct AddSelectionsState {
  834    above: bool,
  835    stack: Vec<usize>,
  836}
  837
  838#[derive(Clone)]
  839struct SelectNextState {
  840    query: AhoCorasick,
  841    wordwise: bool,
  842    done: bool,
  843}
  844
  845impl std::fmt::Debug for SelectNextState {
  846    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  847        f.debug_struct(std::any::type_name::<Self>())
  848            .field("wordwise", &self.wordwise)
  849            .field("done", &self.done)
  850            .finish()
  851    }
  852}
  853
  854#[derive(Debug)]
  855struct AutocloseRegion {
  856    selection_id: usize,
  857    range: Range<Anchor>,
  858    pair: BracketPair,
  859}
  860
  861#[derive(Debug)]
  862struct SnippetState {
  863    ranges: Vec<Vec<Range<Anchor>>>,
  864    active_index: usize,
  865}
  866
  867#[doc(hidden)]
  868pub struct RenameState {
  869    pub range: Range<Anchor>,
  870    pub old_name: Arc<str>,
  871    pub editor: View<Editor>,
  872    block_id: CustomBlockId,
  873}
  874
  875struct InvalidationStack<T>(Vec<T>);
  876
  877struct RegisteredInlineCompletionProvider {
  878    provider: Arc<dyn InlineCompletionProviderHandle>,
  879    _subscription: Subscription,
  880}
  881
  882enum ContextMenu {
  883    Completions(CompletionsMenu),
  884    CodeActions(CodeActionsMenu),
  885}
  886
  887impl ContextMenu {
  888    fn select_first(
  889        &mut self,
  890        provider: Option<&dyn CompletionProvider>,
  891        cx: &mut ViewContext<Editor>,
  892    ) -> bool {
  893        if self.visible() {
  894            match self {
  895                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  896                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  897            }
  898            true
  899        } else {
  900            false
  901        }
  902    }
  903
  904    fn select_prev(
  905        &mut self,
  906        provider: Option<&dyn CompletionProvider>,
  907        cx: &mut ViewContext<Editor>,
  908    ) -> bool {
  909        if self.visible() {
  910            match self {
  911                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  912                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  913            }
  914            true
  915        } else {
  916            false
  917        }
  918    }
  919
  920    fn select_next(
  921        &mut self,
  922        provider: Option<&dyn CompletionProvider>,
  923        cx: &mut ViewContext<Editor>,
  924    ) -> bool {
  925        if self.visible() {
  926            match self {
  927                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  928                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  929            }
  930            true
  931        } else {
  932            false
  933        }
  934    }
  935
  936    fn select_last(
  937        &mut self,
  938        provider: Option<&dyn CompletionProvider>,
  939        cx: &mut ViewContext<Editor>,
  940    ) -> bool {
  941        if self.visible() {
  942            match self {
  943                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  944                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  945            }
  946            true
  947        } else {
  948            false
  949        }
  950    }
  951
  952    fn visible(&self) -> bool {
  953        match self {
  954            ContextMenu::Completions(menu) => menu.visible(),
  955            ContextMenu::CodeActions(menu) => menu.visible(),
  956        }
  957    }
  958
  959    fn render(
  960        &self,
  961        cursor_position: DisplayPoint,
  962        style: &EditorStyle,
  963        max_height: Pixels,
  964        workspace: Option<WeakView<Workspace>>,
  965        cx: &mut ViewContext<Editor>,
  966    ) -> (ContextMenuOrigin, AnyElement) {
  967        match self {
  968            ContextMenu::Completions(menu) => (
  969                ContextMenuOrigin::EditorPoint(cursor_position),
  970                menu.render(style, max_height, workspace, cx),
  971            ),
  972            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  973        }
  974    }
  975}
  976
  977enum ContextMenuOrigin {
  978    EditorPoint(DisplayPoint),
  979    GutterIndicator(DisplayRow),
  980}
  981
  982#[derive(Clone)]
  983struct CompletionsMenu {
  984    id: CompletionId,
  985    sort_completions: bool,
  986    initial_position: Anchor,
  987    buffer: Model<Buffer>,
  988    completions: Arc<RwLock<Box<[Completion]>>>,
  989    match_candidates: Arc<[StringMatchCandidate]>,
  990    matches: Arc<[StringMatch]>,
  991    selected_item: usize,
  992    scroll_handle: UniformListScrollHandle,
  993    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  994}
  995
  996impl CompletionsMenu {
  997    fn select_first(
  998        &mut self,
  999        provider: Option<&dyn CompletionProvider>,
 1000        cx: &mut ViewContext<Editor>,
 1001    ) {
 1002        self.selected_item = 0;
 1003        self.scroll_handle.scroll_to_item(self.selected_item);
 1004        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1005        cx.notify();
 1006    }
 1007
 1008    fn select_prev(
 1009        &mut self,
 1010        provider: Option<&dyn CompletionProvider>,
 1011        cx: &mut ViewContext<Editor>,
 1012    ) {
 1013        if self.selected_item > 0 {
 1014            self.selected_item -= 1;
 1015        } else {
 1016            self.selected_item = self.matches.len() - 1;
 1017        }
 1018        self.scroll_handle.scroll_to_item(self.selected_item);
 1019        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1020        cx.notify();
 1021    }
 1022
 1023    fn select_next(
 1024        &mut self,
 1025        provider: Option<&dyn CompletionProvider>,
 1026        cx: &mut ViewContext<Editor>,
 1027    ) {
 1028        if self.selected_item + 1 < self.matches.len() {
 1029            self.selected_item += 1;
 1030        } else {
 1031            self.selected_item = 0;
 1032        }
 1033        self.scroll_handle.scroll_to_item(self.selected_item);
 1034        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1035        cx.notify();
 1036    }
 1037
 1038    fn select_last(
 1039        &mut self,
 1040        provider: Option<&dyn CompletionProvider>,
 1041        cx: &mut ViewContext<Editor>,
 1042    ) {
 1043        self.selected_item = self.matches.len() - 1;
 1044        self.scroll_handle.scroll_to_item(self.selected_item);
 1045        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1046        cx.notify();
 1047    }
 1048
 1049    fn pre_resolve_completion_documentation(
 1050        buffer: Model<Buffer>,
 1051        completions: Arc<RwLock<Box<[Completion]>>>,
 1052        matches: Arc<[StringMatch]>,
 1053        editor: &Editor,
 1054        cx: &mut ViewContext<Editor>,
 1055    ) -> Task<()> {
 1056        let settings = EditorSettings::get_global(cx);
 1057        if !settings.show_completion_documentation {
 1058            return Task::ready(());
 1059        }
 1060
 1061        let Some(provider) = editor.completion_provider.as_ref() else {
 1062            return Task::ready(());
 1063        };
 1064
 1065        let resolve_task = provider.resolve_completions(
 1066            buffer,
 1067            matches.iter().map(|m| m.candidate_id).collect(),
 1068            completions.clone(),
 1069            cx,
 1070        );
 1071
 1072        cx.spawn(move |this, mut cx| async move {
 1073            if let Some(true) = resolve_task.await.log_err() {
 1074                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1075            }
 1076        })
 1077    }
 1078
 1079    fn attempt_resolve_selected_completion_documentation(
 1080        &mut self,
 1081        provider: Option<&dyn CompletionProvider>,
 1082        cx: &mut ViewContext<Editor>,
 1083    ) {
 1084        let settings = EditorSettings::get_global(cx);
 1085        if !settings.show_completion_documentation {
 1086            return;
 1087        }
 1088
 1089        let completion_index = self.matches[self.selected_item].candidate_id;
 1090        let Some(provider) = provider else {
 1091            return;
 1092        };
 1093
 1094        let resolve_task = provider.resolve_completions(
 1095            self.buffer.clone(),
 1096            vec![completion_index],
 1097            self.completions.clone(),
 1098            cx,
 1099        );
 1100
 1101        let delay_ms =
 1102            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1103        let delay = Duration::from_millis(delay_ms);
 1104
 1105        self.selected_completion_documentation_resolve_debounce
 1106            .lock()
 1107            .fire_new(delay, cx, |_, cx| {
 1108                cx.spawn(move |this, mut cx| async move {
 1109                    if let Some(true) = resolve_task.await.log_err() {
 1110                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1111                    }
 1112                })
 1113            });
 1114    }
 1115
 1116    fn visible(&self) -> bool {
 1117        !self.matches.is_empty()
 1118    }
 1119
 1120    fn render(
 1121        &self,
 1122        style: &EditorStyle,
 1123        max_height: Pixels,
 1124        workspace: Option<WeakView<Workspace>>,
 1125        cx: &mut ViewContext<Editor>,
 1126    ) -> AnyElement {
 1127        let settings = EditorSettings::get_global(cx);
 1128        let show_completion_documentation = settings.show_completion_documentation;
 1129
 1130        let widest_completion_ix = self
 1131            .matches
 1132            .iter()
 1133            .enumerate()
 1134            .max_by_key(|(_, mat)| {
 1135                let completions = self.completions.read();
 1136                let completion = &completions[mat.candidate_id];
 1137                let documentation = &completion.documentation;
 1138
 1139                let mut len = completion.label.text.chars().count();
 1140                if let Some(Documentation::SingleLine(text)) = documentation {
 1141                    if show_completion_documentation {
 1142                        len += text.chars().count();
 1143                    }
 1144                }
 1145
 1146                len
 1147            })
 1148            .map(|(ix, _)| ix);
 1149
 1150        let completions = self.completions.clone();
 1151        let matches = self.matches.clone();
 1152        let selected_item = self.selected_item;
 1153        let style = style.clone();
 1154
 1155        let multiline_docs = if show_completion_documentation {
 1156            let mat = &self.matches[selected_item];
 1157            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1158                Some(Documentation::MultiLinePlainText(text)) => {
 1159                    Some(div().child(SharedString::from(text.clone())))
 1160                }
 1161                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1162                    Some(div().child(render_parsed_markdown(
 1163                        "completions_markdown",
 1164                        parsed,
 1165                        &style,
 1166                        workspace,
 1167                        cx,
 1168                    )))
 1169                }
 1170                _ => None,
 1171            };
 1172            multiline_docs.map(|div| {
 1173                div.id("multiline_docs")
 1174                    .max_h(max_height)
 1175                    .flex_1()
 1176                    .px_1p5()
 1177                    .py_1()
 1178                    .min_w(px(260.))
 1179                    .max_w(px(640.))
 1180                    .w(px(500.))
 1181                    .overflow_y_scroll()
 1182                    .occlude()
 1183            })
 1184        } else {
 1185            None
 1186        };
 1187
 1188        let list = uniform_list(
 1189            cx.view().clone(),
 1190            "completions",
 1191            matches.len(),
 1192            move |_editor, range, cx| {
 1193                let start_ix = range.start;
 1194                let completions_guard = completions.read();
 1195
 1196                matches[range]
 1197                    .iter()
 1198                    .enumerate()
 1199                    .map(|(ix, mat)| {
 1200                        let item_ix = start_ix + ix;
 1201                        let candidate_id = mat.candidate_id;
 1202                        let completion = &completions_guard[candidate_id];
 1203
 1204                        let documentation = if show_completion_documentation {
 1205                            &completion.documentation
 1206                        } else {
 1207                            &None
 1208                        };
 1209
 1210                        let highlights = gpui::combine_highlights(
 1211                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1212                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1213                                |(range, mut highlight)| {
 1214                                    // Ignore font weight for syntax highlighting, as we'll use it
 1215                                    // for fuzzy matches.
 1216                                    highlight.font_weight = None;
 1217
 1218                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1219                                        highlight.strikethrough = Some(StrikethroughStyle {
 1220                                            thickness: 1.0.into(),
 1221                                            ..Default::default()
 1222                                        });
 1223                                        highlight.color = Some(cx.theme().colors().text_muted);
 1224                                    }
 1225
 1226                                    (range, highlight)
 1227                                },
 1228                            ),
 1229                        );
 1230                        let completion_label = StyledText::new(completion.label.text.clone())
 1231                            .with_highlights(&style.text, highlights);
 1232                        let documentation_label =
 1233                            if let Some(Documentation::SingleLine(text)) = documentation {
 1234                                if text.trim().is_empty() {
 1235                                    None
 1236                                } else {
 1237                                    Some(
 1238                                        Label::new(text.clone())
 1239                                            .ml_4()
 1240                                            .size(LabelSize::Small)
 1241                                            .color(Color::Muted),
 1242                                    )
 1243                                }
 1244                            } else {
 1245                                None
 1246                            };
 1247
 1248                        let color_swatch = completion
 1249                            .color()
 1250                            .map(|color| div().size_4().bg(color).rounded_sm());
 1251
 1252                        div().min_w(px(220.)).max_w(px(540.)).child(
 1253                            ListItem::new(mat.candidate_id)
 1254                                .inset(true)
 1255                                .selected(item_ix == selected_item)
 1256                                .on_click(cx.listener(move |editor, _event, cx| {
 1257                                    cx.stop_propagation();
 1258                                    if let Some(task) = editor.confirm_completion(
 1259                                        &ConfirmCompletion {
 1260                                            item_ix: Some(item_ix),
 1261                                        },
 1262                                        cx,
 1263                                    ) {
 1264                                        task.detach_and_log_err(cx)
 1265                                    }
 1266                                }))
 1267                                .start_slot::<Div>(color_swatch)
 1268                                .child(h_flex().overflow_hidden().child(completion_label))
 1269                                .end_slot::<Label>(documentation_label),
 1270                        )
 1271                    })
 1272                    .collect()
 1273            },
 1274        )
 1275        .occlude()
 1276        .max_h(max_height)
 1277        .track_scroll(self.scroll_handle.clone())
 1278        .with_width_from_item(widest_completion_ix)
 1279        .with_sizing_behavior(ListSizingBehavior::Infer);
 1280
 1281        Popover::new()
 1282            .child(list)
 1283            .when_some(multiline_docs, |popover, multiline_docs| {
 1284                popover.aside(multiline_docs)
 1285            })
 1286            .into_any_element()
 1287    }
 1288
 1289    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1290        let mut matches = if let Some(query) = query {
 1291            fuzzy::match_strings(
 1292                &self.match_candidates,
 1293                query,
 1294                query.chars().any(|c| c.is_uppercase()),
 1295                100,
 1296                &Default::default(),
 1297                executor,
 1298            )
 1299            .await
 1300        } else {
 1301            self.match_candidates
 1302                .iter()
 1303                .enumerate()
 1304                .map(|(candidate_id, candidate)| StringMatch {
 1305                    candidate_id,
 1306                    score: Default::default(),
 1307                    positions: Default::default(),
 1308                    string: candidate.string.clone(),
 1309                })
 1310                .collect()
 1311        };
 1312
 1313        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1314        if let Some(query) = query {
 1315            if let Some(query_start) = query.chars().next() {
 1316                matches.retain(|string_match| {
 1317                    split_words(&string_match.string).any(|word| {
 1318                        // Check that the first codepoint of the word as lowercase matches the first
 1319                        // codepoint of the query as lowercase
 1320                        word.chars()
 1321                            .flat_map(|codepoint| codepoint.to_lowercase())
 1322                            .zip(query_start.to_lowercase())
 1323                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1324                    })
 1325                });
 1326            }
 1327        }
 1328
 1329        let completions = self.completions.read();
 1330        if self.sort_completions {
 1331            matches.sort_unstable_by_key(|mat| {
 1332                // We do want to strike a balance here between what the language server tells us
 1333                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1334                // `Creat` and there is a local variable called `CreateComponent`).
 1335                // So what we do is: we bucket all matches into two buckets
 1336                // - Strong matches
 1337                // - Weak matches
 1338                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1339                // and the Weak matches are the rest.
 1340                //
 1341                // For the strong matches, we sort by the language-servers score first and for the weak
 1342                // matches, we prefer our fuzzy finder first.
 1343                //
 1344                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1345                // us into account when it's obviously a bad match.
 1346
 1347                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1348                enum MatchScore<'a> {
 1349                    Strong {
 1350                        sort_text: Option<&'a str>,
 1351                        score: Reverse<OrderedFloat<f64>>,
 1352                        sort_key: (usize, &'a str),
 1353                    },
 1354                    Weak {
 1355                        score: Reverse<OrderedFloat<f64>>,
 1356                        sort_text: Option<&'a str>,
 1357                        sort_key: (usize, &'a str),
 1358                    },
 1359                }
 1360
 1361                let completion = &completions[mat.candidate_id];
 1362                let sort_key = completion.sort_key();
 1363                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1364                let score = Reverse(OrderedFloat(mat.score));
 1365
 1366                if mat.score >= 0.2 {
 1367                    MatchScore::Strong {
 1368                        sort_text,
 1369                        score,
 1370                        sort_key,
 1371                    }
 1372                } else {
 1373                    MatchScore::Weak {
 1374                        score,
 1375                        sort_text,
 1376                        sort_key,
 1377                    }
 1378                }
 1379            });
 1380        }
 1381
 1382        for mat in &mut matches {
 1383            let completion = &completions[mat.candidate_id];
 1384            mat.string.clone_from(&completion.label.text);
 1385            for position in &mut mat.positions {
 1386                *position += completion.label.filter_range.start;
 1387            }
 1388        }
 1389        drop(completions);
 1390
 1391        self.matches = matches.into();
 1392        self.selected_item = 0;
 1393    }
 1394}
 1395
 1396struct AvailableCodeAction {
 1397    excerpt_id: ExcerptId,
 1398    action: CodeAction,
 1399    provider: Arc<dyn CodeActionProvider>,
 1400}
 1401
 1402#[derive(Clone)]
 1403struct CodeActionContents {
 1404    tasks: Option<Arc<ResolvedTasks>>,
 1405    actions: Option<Arc<[AvailableCodeAction]>>,
 1406}
 1407
 1408impl CodeActionContents {
 1409    fn len(&self) -> usize {
 1410        match (&self.tasks, &self.actions) {
 1411            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1412            (Some(tasks), None) => tasks.templates.len(),
 1413            (None, Some(actions)) => actions.len(),
 1414            (None, None) => 0,
 1415        }
 1416    }
 1417
 1418    fn is_empty(&self) -> bool {
 1419        match (&self.tasks, &self.actions) {
 1420            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1421            (Some(tasks), None) => tasks.templates.is_empty(),
 1422            (None, Some(actions)) => actions.is_empty(),
 1423            (None, None) => true,
 1424        }
 1425    }
 1426
 1427    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1428        self.tasks
 1429            .iter()
 1430            .flat_map(|tasks| {
 1431                tasks
 1432                    .templates
 1433                    .iter()
 1434                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1435            })
 1436            .chain(self.actions.iter().flat_map(|actions| {
 1437                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1438                    excerpt_id: available.excerpt_id,
 1439                    action: available.action.clone(),
 1440                    provider: available.provider.clone(),
 1441                })
 1442            }))
 1443    }
 1444    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1445        match (&self.tasks, &self.actions) {
 1446            (Some(tasks), Some(actions)) => {
 1447                if index < tasks.templates.len() {
 1448                    tasks
 1449                        .templates
 1450                        .get(index)
 1451                        .cloned()
 1452                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1453                } else {
 1454                    actions.get(index - tasks.templates.len()).map(|available| {
 1455                        CodeActionsItem::CodeAction {
 1456                            excerpt_id: available.excerpt_id,
 1457                            action: available.action.clone(),
 1458                            provider: available.provider.clone(),
 1459                        }
 1460                    })
 1461                }
 1462            }
 1463            (Some(tasks), None) => tasks
 1464                .templates
 1465                .get(index)
 1466                .cloned()
 1467                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1468            (None, Some(actions)) => {
 1469                actions
 1470                    .get(index)
 1471                    .map(|available| CodeActionsItem::CodeAction {
 1472                        excerpt_id: available.excerpt_id,
 1473                        action: available.action.clone(),
 1474                        provider: available.provider.clone(),
 1475                    })
 1476            }
 1477            (None, None) => None,
 1478        }
 1479    }
 1480}
 1481
 1482#[allow(clippy::large_enum_variant)]
 1483#[derive(Clone)]
 1484enum CodeActionsItem {
 1485    Task(TaskSourceKind, ResolvedTask),
 1486    CodeAction {
 1487        excerpt_id: ExcerptId,
 1488        action: CodeAction,
 1489        provider: Arc<dyn CodeActionProvider>,
 1490    },
 1491}
 1492
 1493impl CodeActionsItem {
 1494    fn as_task(&self) -> Option<&ResolvedTask> {
 1495        let Self::Task(_, task) = self else {
 1496            return None;
 1497        };
 1498        Some(task)
 1499    }
 1500    fn as_code_action(&self) -> Option<&CodeAction> {
 1501        let Self::CodeAction { action, .. } = self else {
 1502            return None;
 1503        };
 1504        Some(action)
 1505    }
 1506    fn label(&self) -> String {
 1507        match self {
 1508            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1509            Self::Task(_, task) => task.resolved_label.clone(),
 1510        }
 1511    }
 1512}
 1513
 1514struct CodeActionsMenu {
 1515    actions: CodeActionContents,
 1516    buffer: Model<Buffer>,
 1517    selected_item: usize,
 1518    scroll_handle: UniformListScrollHandle,
 1519    deployed_from_indicator: Option<DisplayRow>,
 1520}
 1521
 1522impl CodeActionsMenu {
 1523    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1524        self.selected_item = 0;
 1525        self.scroll_handle.scroll_to_item(self.selected_item);
 1526        cx.notify()
 1527    }
 1528
 1529    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1530        if self.selected_item > 0 {
 1531            self.selected_item -= 1;
 1532        } else {
 1533            self.selected_item = self.actions.len() - 1;
 1534        }
 1535        self.scroll_handle.scroll_to_item(self.selected_item);
 1536        cx.notify();
 1537    }
 1538
 1539    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1540        if self.selected_item + 1 < self.actions.len() {
 1541            self.selected_item += 1;
 1542        } else {
 1543            self.selected_item = 0;
 1544        }
 1545        self.scroll_handle.scroll_to_item(self.selected_item);
 1546        cx.notify();
 1547    }
 1548
 1549    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1550        self.selected_item = self.actions.len() - 1;
 1551        self.scroll_handle.scroll_to_item(self.selected_item);
 1552        cx.notify()
 1553    }
 1554
 1555    fn visible(&self) -> bool {
 1556        !self.actions.is_empty()
 1557    }
 1558
 1559    fn render(
 1560        &self,
 1561        cursor_position: DisplayPoint,
 1562        _style: &EditorStyle,
 1563        max_height: Pixels,
 1564        cx: &mut ViewContext<Editor>,
 1565    ) -> (ContextMenuOrigin, AnyElement) {
 1566        let actions = self.actions.clone();
 1567        let selected_item = self.selected_item;
 1568        let element = uniform_list(
 1569            cx.view().clone(),
 1570            "code_actions_menu",
 1571            self.actions.len(),
 1572            move |_this, range, cx| {
 1573                actions
 1574                    .iter()
 1575                    .skip(range.start)
 1576                    .take(range.end - range.start)
 1577                    .enumerate()
 1578                    .map(|(ix, action)| {
 1579                        let item_ix = range.start + ix;
 1580                        let selected = selected_item == item_ix;
 1581                        let colors = cx.theme().colors();
 1582                        div()
 1583                            .px_1()
 1584                            .rounded_md()
 1585                            .text_color(colors.text)
 1586                            .when(selected, |style| {
 1587                                style
 1588                                    .bg(colors.element_active)
 1589                                    .text_color(colors.text_accent)
 1590                            })
 1591                            .hover(|style| {
 1592                                style
 1593                                    .bg(colors.element_hover)
 1594                                    .text_color(colors.text_accent)
 1595                            })
 1596                            .whitespace_nowrap()
 1597                            .when_some(action.as_code_action(), |this, action| {
 1598                                this.on_mouse_down(
 1599                                    MouseButton::Left,
 1600                                    cx.listener(move |editor, _, cx| {
 1601                                        cx.stop_propagation();
 1602                                        if let Some(task) = editor.confirm_code_action(
 1603                                            &ConfirmCodeAction {
 1604                                                item_ix: Some(item_ix),
 1605                                            },
 1606                                            cx,
 1607                                        ) {
 1608                                            task.detach_and_log_err(cx)
 1609                                        }
 1610                                    }),
 1611                                )
 1612                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1613                                .child(SharedString::from(action.lsp_action.title.clone()))
 1614                            })
 1615                            .when_some(action.as_task(), |this, task| {
 1616                                this.on_mouse_down(
 1617                                    MouseButton::Left,
 1618                                    cx.listener(move |editor, _, cx| {
 1619                                        cx.stop_propagation();
 1620                                        if let Some(task) = editor.confirm_code_action(
 1621                                            &ConfirmCodeAction {
 1622                                                item_ix: Some(item_ix),
 1623                                            },
 1624                                            cx,
 1625                                        ) {
 1626                                            task.detach_and_log_err(cx)
 1627                                        }
 1628                                    }),
 1629                                )
 1630                                .child(SharedString::from(task.resolved_label.clone()))
 1631                            })
 1632                    })
 1633                    .collect()
 1634            },
 1635        )
 1636        .elevation_1(cx)
 1637        .p_1()
 1638        .max_h(max_height)
 1639        .occlude()
 1640        .track_scroll(self.scroll_handle.clone())
 1641        .with_width_from_item(
 1642            self.actions
 1643                .iter()
 1644                .enumerate()
 1645                .max_by_key(|(_, action)| match action {
 1646                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1647                    CodeActionsItem::CodeAction { action, .. } => {
 1648                        action.lsp_action.title.chars().count()
 1649                    }
 1650                })
 1651                .map(|(ix, _)| ix),
 1652        )
 1653        .with_sizing_behavior(ListSizingBehavior::Infer)
 1654        .into_any_element();
 1655
 1656        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1657            ContextMenuOrigin::GutterIndicator(row)
 1658        } else {
 1659            ContextMenuOrigin::EditorPoint(cursor_position)
 1660        };
 1661
 1662        (cursor_position, element)
 1663    }
 1664}
 1665
 1666#[derive(Debug)]
 1667struct ActiveDiagnosticGroup {
 1668    primary_range: Range<Anchor>,
 1669    primary_message: String,
 1670    group_id: usize,
 1671    blocks: HashMap<CustomBlockId, Diagnostic>,
 1672    is_valid: bool,
 1673}
 1674
 1675#[derive(Serialize, Deserialize, Clone, Debug)]
 1676pub struct ClipboardSelection {
 1677    pub len: usize,
 1678    pub is_entire_line: bool,
 1679    pub first_line_indent: u32,
 1680}
 1681
 1682#[derive(Debug)]
 1683pub(crate) struct NavigationData {
 1684    cursor_anchor: Anchor,
 1685    cursor_position: Point,
 1686    scroll_anchor: ScrollAnchor,
 1687    scroll_top_row: u32,
 1688}
 1689
 1690#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1691pub enum GotoDefinitionKind {
 1692    Symbol,
 1693    Declaration,
 1694    Type,
 1695    Implementation,
 1696}
 1697
 1698#[derive(Debug, Clone)]
 1699enum InlayHintRefreshReason {
 1700    Toggle(bool),
 1701    SettingsChange(InlayHintSettings),
 1702    NewLinesShown,
 1703    BufferEdited(HashSet<Arc<Language>>),
 1704    RefreshRequested,
 1705    ExcerptsRemoved(Vec<ExcerptId>),
 1706}
 1707
 1708impl InlayHintRefreshReason {
 1709    fn description(&self) -> &'static str {
 1710        match self {
 1711            Self::Toggle(_) => "toggle",
 1712            Self::SettingsChange(_) => "settings change",
 1713            Self::NewLinesShown => "new lines shown",
 1714            Self::BufferEdited(_) => "buffer edited",
 1715            Self::RefreshRequested => "refresh requested",
 1716            Self::ExcerptsRemoved(_) => "excerpts removed",
 1717        }
 1718    }
 1719}
 1720
 1721pub(crate) struct FocusedBlock {
 1722    id: BlockId,
 1723    focus_handle: WeakFocusHandle,
 1724}
 1725
 1726impl Editor {
 1727    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1728        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1729        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1730        Self::new(
 1731            EditorMode::SingleLine { auto_width: false },
 1732            buffer,
 1733            None,
 1734            false,
 1735            cx,
 1736        )
 1737    }
 1738
 1739    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1740        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1741        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1742        Self::new(EditorMode::Full, buffer, None, false, cx)
 1743    }
 1744
 1745    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1746        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1747        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1748        Self::new(
 1749            EditorMode::SingleLine { auto_width: true },
 1750            buffer,
 1751            None,
 1752            false,
 1753            cx,
 1754        )
 1755    }
 1756
 1757    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1758        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1759        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1760        Self::new(
 1761            EditorMode::AutoHeight { max_lines },
 1762            buffer,
 1763            None,
 1764            false,
 1765            cx,
 1766        )
 1767    }
 1768
 1769    pub fn for_buffer(
 1770        buffer: Model<Buffer>,
 1771        project: Option<Model<Project>>,
 1772        cx: &mut ViewContext<Self>,
 1773    ) -> Self {
 1774        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1775        Self::new(EditorMode::Full, buffer, project, false, cx)
 1776    }
 1777
 1778    pub fn for_multibuffer(
 1779        buffer: Model<MultiBuffer>,
 1780        project: Option<Model<Project>>,
 1781        show_excerpt_controls: bool,
 1782        cx: &mut ViewContext<Self>,
 1783    ) -> Self {
 1784        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1785    }
 1786
 1787    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1788        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1789        let mut clone = Self::new(
 1790            self.mode,
 1791            self.buffer.clone(),
 1792            self.project.clone(),
 1793            show_excerpt_controls,
 1794            cx,
 1795        );
 1796        self.display_map.update(cx, |display_map, cx| {
 1797            let snapshot = display_map.snapshot(cx);
 1798            clone.display_map.update(cx, |display_map, cx| {
 1799                display_map.set_state(&snapshot, cx);
 1800            });
 1801        });
 1802        clone.selections.clone_state(&self.selections);
 1803        clone.scroll_manager.clone_state(&self.scroll_manager);
 1804        clone.searchable = self.searchable;
 1805        clone
 1806    }
 1807
 1808    pub fn new(
 1809        mode: EditorMode,
 1810        buffer: Model<MultiBuffer>,
 1811        project: Option<Model<Project>>,
 1812        show_excerpt_controls: bool,
 1813        cx: &mut ViewContext<Self>,
 1814    ) -> Self {
 1815        let style = cx.text_style();
 1816        let font_size = style.font_size.to_pixels(cx.rem_size());
 1817        let editor = cx.view().downgrade();
 1818        let fold_placeholder = FoldPlaceholder {
 1819            constrain_width: true,
 1820            render: Arc::new(move |fold_id, fold_range, cx| {
 1821                let editor = editor.clone();
 1822                div()
 1823                    .id(fold_id)
 1824                    .bg(cx.theme().colors().ghost_element_background)
 1825                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1826                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1827                    .rounded_sm()
 1828                    .size_full()
 1829                    .cursor_pointer()
 1830                    .child("")
 1831                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1832                    .on_click(move |_, cx| {
 1833                        editor
 1834                            .update(cx, |editor, cx| {
 1835                                editor.unfold_ranges(
 1836                                    [fold_range.start..fold_range.end],
 1837                                    true,
 1838                                    false,
 1839                                    cx,
 1840                                );
 1841                                cx.stop_propagation();
 1842                            })
 1843                            .ok();
 1844                    })
 1845                    .into_any()
 1846            }),
 1847            merge_adjacent: true,
 1848        };
 1849        let display_map = cx.new_model(|cx| {
 1850            DisplayMap::new(
 1851                buffer.clone(),
 1852                style.font(),
 1853                font_size,
 1854                None,
 1855                show_excerpt_controls,
 1856                FILE_HEADER_HEIGHT,
 1857                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1858                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1859                fold_placeholder,
 1860                cx,
 1861            )
 1862        });
 1863
 1864        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1865
 1866        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1867
 1868        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1869            .then(|| language_settings::SoftWrap::None);
 1870
 1871        let mut project_subscriptions = Vec::new();
 1872        if mode == EditorMode::Full {
 1873            if let Some(project) = project.as_ref() {
 1874                if buffer.read(cx).is_singleton() {
 1875                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1876                        cx.emit(EditorEvent::TitleChanged);
 1877                    }));
 1878                }
 1879                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1880                    if let project::Event::RefreshInlayHints = event {
 1881                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1882                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1883                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1884                            let focus_handle = editor.focus_handle(cx);
 1885                            if focus_handle.is_focused(cx) {
 1886                                let snapshot = buffer.read(cx).snapshot();
 1887                                for (range, snippet) in snippet_edits {
 1888                                    let editor_range =
 1889                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1890                                    editor
 1891                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1892                                        .ok();
 1893                                }
 1894                            }
 1895                        }
 1896                    }
 1897                }));
 1898                if let Some(task_inventory) = project
 1899                    .read(cx)
 1900                    .task_store()
 1901                    .read(cx)
 1902                    .task_inventory()
 1903                    .cloned()
 1904                {
 1905                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1906                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1907                    }));
 1908                }
 1909            }
 1910        }
 1911
 1912        let inlay_hint_settings = inlay_hint_settings(
 1913            selections.newest_anchor().head(),
 1914            &buffer.read(cx).snapshot(cx),
 1915            cx,
 1916        );
 1917        let focus_handle = cx.focus_handle();
 1918        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1919        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1920            .detach();
 1921        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1922            .detach();
 1923        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1924
 1925        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1926            Some(false)
 1927        } else {
 1928            None
 1929        };
 1930
 1931        let mut code_action_providers = Vec::new();
 1932        if let Some(project) = project.clone() {
 1933            code_action_providers.push(Arc::new(project) as Arc<_>);
 1934        }
 1935
 1936        let mut this = Self {
 1937            focus_handle,
 1938            show_cursor_when_unfocused: false,
 1939            last_focused_descendant: None,
 1940            buffer: buffer.clone(),
 1941            display_map: display_map.clone(),
 1942            selections,
 1943            scroll_manager: ScrollManager::new(cx),
 1944            columnar_selection_tail: None,
 1945            add_selections_state: None,
 1946            select_next_state: None,
 1947            select_prev_state: None,
 1948            selection_history: Default::default(),
 1949            autoclose_regions: Default::default(),
 1950            snippet_stack: Default::default(),
 1951            select_larger_syntax_node_stack: Vec::new(),
 1952            ime_transaction: Default::default(),
 1953            active_diagnostics: None,
 1954            soft_wrap_mode_override,
 1955            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1956            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1957            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1958            project,
 1959            blink_manager: blink_manager.clone(),
 1960            show_local_selections: true,
 1961            mode,
 1962            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1963            show_gutter: mode == EditorMode::Full,
 1964            show_line_numbers: None,
 1965            use_relative_line_numbers: None,
 1966            show_git_diff_gutter: None,
 1967            show_code_actions: None,
 1968            show_runnables: None,
 1969            show_wrap_guides: None,
 1970            show_indent_guides,
 1971            placeholder_text: None,
 1972            highlight_order: 0,
 1973            highlighted_rows: HashMap::default(),
 1974            background_highlights: Default::default(),
 1975            gutter_highlights: TreeMap::default(),
 1976            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1977            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1978            nav_history: None,
 1979            context_menu: RwLock::new(None),
 1980            mouse_context_menu: None,
 1981            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1982            completion_tasks: Default::default(),
 1983            signature_help_state: SignatureHelpState::default(),
 1984            auto_signature_help: None,
 1985            find_all_references_task_sources: Vec::new(),
 1986            next_completion_id: 0,
 1987            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1988            next_inlay_id: 0,
 1989            code_action_providers,
 1990            available_code_actions: Default::default(),
 1991            code_actions_task: Default::default(),
 1992            document_highlights_task: Default::default(),
 1993            linked_editing_range_task: Default::default(),
 1994            pending_rename: Default::default(),
 1995            searchable: true,
 1996            cursor_shape: EditorSettings::get_global(cx)
 1997                .cursor_shape
 1998                .unwrap_or_default(),
 1999            current_line_highlight: None,
 2000            autoindent_mode: Some(AutoindentMode::EachLine),
 2001            collapse_matches: false,
 2002            workspace: None,
 2003            input_enabled: true,
 2004            use_modal_editing: mode == EditorMode::Full,
 2005            read_only: false,
 2006            use_autoclose: true,
 2007            use_auto_surround: true,
 2008            auto_replace_emoji_shortcode: false,
 2009            leader_peer_id: None,
 2010            remote_id: None,
 2011            hover_state: Default::default(),
 2012            hovered_link_state: Default::default(),
 2013            inline_completion_provider: None,
 2014            active_inline_completion: None,
 2015            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2016            expanded_hunks: ExpandedHunks::default(),
 2017            gutter_hovered: false,
 2018            pixel_position_of_newest_cursor: None,
 2019            last_bounds: None,
 2020            expect_bounds_change: None,
 2021            gutter_dimensions: GutterDimensions::default(),
 2022            style: None,
 2023            show_cursor_names: false,
 2024            hovered_cursors: Default::default(),
 2025            next_editor_action_id: EditorActionId::default(),
 2026            editor_actions: Rc::default(),
 2027            show_inline_completions_override: None,
 2028            enable_inline_completions: true,
 2029            custom_context_menu: None,
 2030            show_git_blame_gutter: false,
 2031            show_git_blame_inline: false,
 2032            show_selection_menu: None,
 2033            show_git_blame_inline_delay_task: None,
 2034            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2035            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2036                .session
 2037                .restore_unsaved_buffers,
 2038            blame: None,
 2039            blame_subscription: None,
 2040            tasks: Default::default(),
 2041            _subscriptions: vec![
 2042                cx.observe(&buffer, Self::on_buffer_changed),
 2043                cx.subscribe(&buffer, Self::on_buffer_event),
 2044                cx.observe(&display_map, Self::on_display_map_changed),
 2045                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2046                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2047                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2048                cx.observe_window_activation(|editor, cx| {
 2049                    let active = cx.is_window_active();
 2050                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2051                        if active {
 2052                            blink_manager.enable(cx);
 2053                        } else {
 2054                            blink_manager.disable(cx);
 2055                        }
 2056                    });
 2057                }),
 2058            ],
 2059            tasks_update_task: None,
 2060            linked_edit_ranges: Default::default(),
 2061            previous_search_ranges: None,
 2062            breadcrumb_header: None,
 2063            focused_block: None,
 2064            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2065            addons: HashMap::default(),
 2066            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2067            text_style_refinement: None,
 2068        };
 2069        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2070        this._subscriptions.extend(project_subscriptions);
 2071
 2072        this.end_selection(cx);
 2073        this.scroll_manager.show_scrollbar(cx);
 2074
 2075        if mode == EditorMode::Full {
 2076            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2077            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2078
 2079            if this.git_blame_inline_enabled {
 2080                this.git_blame_inline_enabled = true;
 2081                this.start_git_blame_inline(false, cx);
 2082            }
 2083        }
 2084
 2085        this.report_editor_event("open", None, cx);
 2086        this
 2087    }
 2088
 2089    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2090        self.mouse_context_menu
 2091            .as_ref()
 2092            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2093    }
 2094
 2095    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2096        let mut key_context = KeyContext::new_with_defaults();
 2097        key_context.add("Editor");
 2098        let mode = match self.mode {
 2099            EditorMode::SingleLine { .. } => "single_line",
 2100            EditorMode::AutoHeight { .. } => "auto_height",
 2101            EditorMode::Full => "full",
 2102        };
 2103
 2104        if EditorSettings::jupyter_enabled(cx) {
 2105            key_context.add("jupyter");
 2106        }
 2107
 2108        key_context.set("mode", mode);
 2109        if self.pending_rename.is_some() {
 2110            key_context.add("renaming");
 2111        }
 2112        if self.context_menu_visible() {
 2113            match self.context_menu.read().as_ref() {
 2114                Some(ContextMenu::Completions(_)) => {
 2115                    key_context.add("menu");
 2116                    key_context.add("showing_completions")
 2117                }
 2118                Some(ContextMenu::CodeActions(_)) => {
 2119                    key_context.add("menu");
 2120                    key_context.add("showing_code_actions")
 2121                }
 2122                None => {}
 2123            }
 2124        }
 2125
 2126        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2127        if !self.focus_handle(cx).contains_focused(cx)
 2128            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2129        {
 2130            for addon in self.addons.values() {
 2131                addon.extend_key_context(&mut key_context, cx)
 2132            }
 2133        }
 2134
 2135        if let Some(extension) = self
 2136            .buffer
 2137            .read(cx)
 2138            .as_singleton()
 2139            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2140        {
 2141            key_context.set("extension", extension.to_string());
 2142        }
 2143
 2144        if self.has_active_inline_completion(cx) {
 2145            key_context.add("copilot_suggestion");
 2146            key_context.add("inline_completion");
 2147        }
 2148
 2149        key_context
 2150    }
 2151
 2152    pub fn new_file(
 2153        workspace: &mut Workspace,
 2154        _: &workspace::NewFile,
 2155        cx: &mut ViewContext<Workspace>,
 2156    ) {
 2157        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2158            "Failed to create buffer",
 2159            cx,
 2160            |e, _| match e.error_code() {
 2161                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2162                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2163                e.error_tag("required").unwrap_or("the latest version")
 2164            )),
 2165                _ => None,
 2166            },
 2167        );
 2168    }
 2169
 2170    pub fn new_in_workspace(
 2171        workspace: &mut Workspace,
 2172        cx: &mut ViewContext<Workspace>,
 2173    ) -> Task<Result<View<Editor>>> {
 2174        let project = workspace.project().clone();
 2175        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2176
 2177        cx.spawn(|workspace, mut cx| async move {
 2178            let buffer = create.await?;
 2179            workspace.update(&mut cx, |workspace, cx| {
 2180                let editor =
 2181                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2182                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2183                editor
 2184            })
 2185        })
 2186    }
 2187
 2188    fn new_file_vertical(
 2189        workspace: &mut Workspace,
 2190        _: &workspace::NewFileSplitVertical,
 2191        cx: &mut ViewContext<Workspace>,
 2192    ) {
 2193        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2194    }
 2195
 2196    fn new_file_horizontal(
 2197        workspace: &mut Workspace,
 2198        _: &workspace::NewFileSplitHorizontal,
 2199        cx: &mut ViewContext<Workspace>,
 2200    ) {
 2201        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2202    }
 2203
 2204    fn new_file_in_direction(
 2205        workspace: &mut Workspace,
 2206        direction: SplitDirection,
 2207        cx: &mut ViewContext<Workspace>,
 2208    ) {
 2209        let project = workspace.project().clone();
 2210        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2211
 2212        cx.spawn(|workspace, mut cx| async move {
 2213            let buffer = create.await?;
 2214            workspace.update(&mut cx, move |workspace, cx| {
 2215                workspace.split_item(
 2216                    direction,
 2217                    Box::new(
 2218                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2219                    ),
 2220                    cx,
 2221                )
 2222            })?;
 2223            anyhow::Ok(())
 2224        })
 2225        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2226            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2227                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2228                e.error_tag("required").unwrap_or("the latest version")
 2229            )),
 2230            _ => None,
 2231        });
 2232    }
 2233
 2234    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2235        self.leader_peer_id
 2236    }
 2237
 2238    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2239        &self.buffer
 2240    }
 2241
 2242    pub fn workspace(&self) -> Option<View<Workspace>> {
 2243        self.workspace.as_ref()?.0.upgrade()
 2244    }
 2245
 2246    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2247        self.buffer().read(cx).title(cx)
 2248    }
 2249
 2250    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2251        let git_blame_gutter_max_author_length = self
 2252            .render_git_blame_gutter(cx)
 2253            .then(|| {
 2254                if let Some(blame) = self.blame.as_ref() {
 2255                    let max_author_length =
 2256                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2257                    Some(max_author_length)
 2258                } else {
 2259                    None
 2260                }
 2261            })
 2262            .flatten();
 2263
 2264        EditorSnapshot {
 2265            mode: self.mode,
 2266            show_gutter: self.show_gutter,
 2267            show_line_numbers: self.show_line_numbers,
 2268            show_git_diff_gutter: self.show_git_diff_gutter,
 2269            show_code_actions: self.show_code_actions,
 2270            show_runnables: self.show_runnables,
 2271            git_blame_gutter_max_author_length,
 2272            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2273            scroll_anchor: self.scroll_manager.anchor(),
 2274            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2275            placeholder_text: self.placeholder_text.clone(),
 2276            is_focused: self.focus_handle.is_focused(cx),
 2277            current_line_highlight: self
 2278                .current_line_highlight
 2279                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2280            gutter_hovered: self.gutter_hovered,
 2281        }
 2282    }
 2283
 2284    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2285        self.buffer.read(cx).language_at(point, cx)
 2286    }
 2287
 2288    pub fn file_at<T: ToOffset>(
 2289        &self,
 2290        point: T,
 2291        cx: &AppContext,
 2292    ) -> Option<Arc<dyn language::File>> {
 2293        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2294    }
 2295
 2296    pub fn active_excerpt(
 2297        &self,
 2298        cx: &AppContext,
 2299    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2300        self.buffer
 2301            .read(cx)
 2302            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2303    }
 2304
 2305    pub fn mode(&self) -> EditorMode {
 2306        self.mode
 2307    }
 2308
 2309    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2310        self.collaboration_hub.as_deref()
 2311    }
 2312
 2313    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2314        self.collaboration_hub = Some(hub);
 2315    }
 2316
 2317    pub fn set_custom_context_menu(
 2318        &mut self,
 2319        f: impl 'static
 2320            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2321    ) {
 2322        self.custom_context_menu = Some(Box::new(f))
 2323    }
 2324
 2325    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2326        self.completion_provider = provider;
 2327    }
 2328
 2329    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2330        self.semantics_provider.clone()
 2331    }
 2332
 2333    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2334        self.semantics_provider = provider;
 2335    }
 2336
 2337    pub fn set_inline_completion_provider<T>(
 2338        &mut self,
 2339        provider: Option<Model<T>>,
 2340        cx: &mut ViewContext<Self>,
 2341    ) where
 2342        T: InlineCompletionProvider,
 2343    {
 2344        self.inline_completion_provider =
 2345            provider.map(|provider| RegisteredInlineCompletionProvider {
 2346                _subscription: cx.observe(&provider, |this, _, cx| {
 2347                    if this.focus_handle.is_focused(cx) {
 2348                        this.update_visible_inline_completion(cx);
 2349                    }
 2350                }),
 2351                provider: Arc::new(provider),
 2352            });
 2353        self.refresh_inline_completion(false, false, cx);
 2354    }
 2355
 2356    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2357        self.placeholder_text.as_deref()
 2358    }
 2359
 2360    pub fn set_placeholder_text(
 2361        &mut self,
 2362        placeholder_text: impl Into<Arc<str>>,
 2363        cx: &mut ViewContext<Self>,
 2364    ) {
 2365        let placeholder_text = Some(placeholder_text.into());
 2366        if self.placeholder_text != placeholder_text {
 2367            self.placeholder_text = placeholder_text;
 2368            cx.notify();
 2369        }
 2370    }
 2371
 2372    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2373        self.cursor_shape = cursor_shape;
 2374
 2375        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2376        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2377
 2378        cx.notify();
 2379    }
 2380
 2381    pub fn set_current_line_highlight(
 2382        &mut self,
 2383        current_line_highlight: Option<CurrentLineHighlight>,
 2384    ) {
 2385        self.current_line_highlight = current_line_highlight;
 2386    }
 2387
 2388    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2389        self.collapse_matches = collapse_matches;
 2390    }
 2391
 2392    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2393        if self.collapse_matches {
 2394            return range.start..range.start;
 2395        }
 2396        range.clone()
 2397    }
 2398
 2399    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2400        if self.display_map.read(cx).clip_at_line_ends != clip {
 2401            self.display_map
 2402                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2403        }
 2404    }
 2405
 2406    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2407        self.input_enabled = input_enabled;
 2408    }
 2409
 2410    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2411        self.enable_inline_completions = enabled;
 2412    }
 2413
 2414    pub fn set_autoindent(&mut self, autoindent: bool) {
 2415        if autoindent {
 2416            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2417        } else {
 2418            self.autoindent_mode = None;
 2419        }
 2420    }
 2421
 2422    pub fn read_only(&self, cx: &AppContext) -> bool {
 2423        self.read_only || self.buffer.read(cx).read_only()
 2424    }
 2425
 2426    pub fn set_read_only(&mut self, read_only: bool) {
 2427        self.read_only = read_only;
 2428    }
 2429
 2430    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2431        self.use_autoclose = autoclose;
 2432    }
 2433
 2434    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2435        self.use_auto_surround = auto_surround;
 2436    }
 2437
 2438    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2439        self.auto_replace_emoji_shortcode = auto_replace;
 2440    }
 2441
 2442    pub fn toggle_inline_completions(
 2443        &mut self,
 2444        _: &ToggleInlineCompletions,
 2445        cx: &mut ViewContext<Self>,
 2446    ) {
 2447        if self.show_inline_completions_override.is_some() {
 2448            self.set_show_inline_completions(None, cx);
 2449        } else {
 2450            let cursor = self.selections.newest_anchor().head();
 2451            if let Some((buffer, cursor_buffer_position)) =
 2452                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2453            {
 2454                let show_inline_completions =
 2455                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2456                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2457            }
 2458        }
 2459    }
 2460
 2461    pub fn set_show_inline_completions(
 2462        &mut self,
 2463        show_inline_completions: Option<bool>,
 2464        cx: &mut ViewContext<Self>,
 2465    ) {
 2466        self.show_inline_completions_override = show_inline_completions;
 2467        self.refresh_inline_completion(false, true, cx);
 2468    }
 2469
 2470    fn should_show_inline_completions(
 2471        &self,
 2472        buffer: &Model<Buffer>,
 2473        buffer_position: language::Anchor,
 2474        cx: &AppContext,
 2475    ) -> bool {
 2476        if let Some(provider) = self.inline_completion_provider() {
 2477            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2478                show_inline_completions
 2479            } else {
 2480                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2481            }
 2482        } else {
 2483            false
 2484        }
 2485    }
 2486
 2487    pub fn set_use_modal_editing(&mut self, to: bool) {
 2488        self.use_modal_editing = to;
 2489    }
 2490
 2491    pub fn use_modal_editing(&self) -> bool {
 2492        self.use_modal_editing
 2493    }
 2494
 2495    fn selections_did_change(
 2496        &mut self,
 2497        local: bool,
 2498        old_cursor_position: &Anchor,
 2499        show_completions: bool,
 2500        cx: &mut ViewContext<Self>,
 2501    ) {
 2502        cx.invalidate_character_coordinates();
 2503
 2504        // Copy selections to primary selection buffer
 2505        #[cfg(target_os = "linux")]
 2506        if local {
 2507            let selections = self.selections.all::<usize>(cx);
 2508            let buffer_handle = self.buffer.read(cx).read(cx);
 2509
 2510            let mut text = String::new();
 2511            for (index, selection) in selections.iter().enumerate() {
 2512                let text_for_selection = buffer_handle
 2513                    .text_for_range(selection.start..selection.end)
 2514                    .collect::<String>();
 2515
 2516                text.push_str(&text_for_selection);
 2517                if index != selections.len() - 1 {
 2518                    text.push('\n');
 2519                }
 2520            }
 2521
 2522            if !text.is_empty() {
 2523                cx.write_to_primary(ClipboardItem::new_string(text));
 2524            }
 2525        }
 2526
 2527        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2528            self.buffer.update(cx, |buffer, cx| {
 2529                buffer.set_active_selections(
 2530                    &self.selections.disjoint_anchors(),
 2531                    self.selections.line_mode,
 2532                    self.cursor_shape,
 2533                    cx,
 2534                )
 2535            });
 2536        }
 2537        let display_map = self
 2538            .display_map
 2539            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2540        let buffer = &display_map.buffer_snapshot;
 2541        self.add_selections_state = None;
 2542        self.select_next_state = None;
 2543        self.select_prev_state = None;
 2544        self.select_larger_syntax_node_stack.clear();
 2545        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2546        self.snippet_stack
 2547            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2548        self.take_rename(false, cx);
 2549
 2550        let new_cursor_position = self.selections.newest_anchor().head();
 2551
 2552        self.push_to_nav_history(
 2553            *old_cursor_position,
 2554            Some(new_cursor_position.to_point(buffer)),
 2555            cx,
 2556        );
 2557
 2558        if local {
 2559            let new_cursor_position = self.selections.newest_anchor().head();
 2560            let mut context_menu = self.context_menu.write();
 2561            let completion_menu = match context_menu.as_ref() {
 2562                Some(ContextMenu::Completions(menu)) => Some(menu),
 2563
 2564                _ => {
 2565                    *context_menu = None;
 2566                    None
 2567                }
 2568            };
 2569
 2570            if let Some(completion_menu) = completion_menu {
 2571                let cursor_position = new_cursor_position.to_offset(buffer);
 2572                let (word_range, kind) =
 2573                    buffer.surrounding_word(completion_menu.initial_position, true);
 2574                if kind == Some(CharKind::Word)
 2575                    && word_range.to_inclusive().contains(&cursor_position)
 2576                {
 2577                    let mut completion_menu = completion_menu.clone();
 2578                    drop(context_menu);
 2579
 2580                    let query = Self::completion_query(buffer, cursor_position);
 2581                    cx.spawn(move |this, mut cx| async move {
 2582                        completion_menu
 2583                            .filter(query.as_deref(), cx.background_executor().clone())
 2584                            .await;
 2585
 2586                        this.update(&mut cx, |this, cx| {
 2587                            let mut context_menu = this.context_menu.write();
 2588                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2589                                return;
 2590                            };
 2591
 2592                            if menu.id > completion_menu.id {
 2593                                return;
 2594                            }
 2595
 2596                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2597                            drop(context_menu);
 2598                            cx.notify();
 2599                        })
 2600                    })
 2601                    .detach();
 2602
 2603                    if show_completions {
 2604                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2605                    }
 2606                } else {
 2607                    drop(context_menu);
 2608                    self.hide_context_menu(cx);
 2609                }
 2610            } else {
 2611                drop(context_menu);
 2612            }
 2613
 2614            hide_hover(self, cx);
 2615
 2616            if old_cursor_position.to_display_point(&display_map).row()
 2617                != new_cursor_position.to_display_point(&display_map).row()
 2618            {
 2619                self.available_code_actions.take();
 2620            }
 2621            self.refresh_code_actions(cx);
 2622            self.refresh_document_highlights(cx);
 2623            refresh_matching_bracket_highlights(self, cx);
 2624            self.discard_inline_completion(false, cx);
 2625            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2626            if self.git_blame_inline_enabled {
 2627                self.start_inline_blame_timer(cx);
 2628            }
 2629        }
 2630
 2631        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2632        cx.emit(EditorEvent::SelectionsChanged { local });
 2633
 2634        if self.selections.disjoint_anchors().len() == 1 {
 2635            cx.emit(SearchEvent::ActiveMatchChanged)
 2636        }
 2637        cx.notify();
 2638    }
 2639
 2640    pub fn change_selections<R>(
 2641        &mut self,
 2642        autoscroll: Option<Autoscroll>,
 2643        cx: &mut ViewContext<Self>,
 2644        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2645    ) -> R {
 2646        self.change_selections_inner(autoscroll, true, cx, change)
 2647    }
 2648
 2649    pub fn change_selections_inner<R>(
 2650        &mut self,
 2651        autoscroll: Option<Autoscroll>,
 2652        request_completions: bool,
 2653        cx: &mut ViewContext<Self>,
 2654        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2655    ) -> R {
 2656        let old_cursor_position = self.selections.newest_anchor().head();
 2657        self.push_to_selection_history();
 2658
 2659        let (changed, result) = self.selections.change_with(cx, change);
 2660
 2661        if changed {
 2662            if let Some(autoscroll) = autoscroll {
 2663                self.request_autoscroll(autoscroll, cx);
 2664            }
 2665            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2666
 2667            if self.should_open_signature_help_automatically(
 2668                &old_cursor_position,
 2669                self.signature_help_state.backspace_pressed(),
 2670                cx,
 2671            ) {
 2672                self.show_signature_help(&ShowSignatureHelp, cx);
 2673            }
 2674            self.signature_help_state.set_backspace_pressed(false);
 2675        }
 2676
 2677        result
 2678    }
 2679
 2680    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2681    where
 2682        I: IntoIterator<Item = (Range<S>, T)>,
 2683        S: ToOffset,
 2684        T: Into<Arc<str>>,
 2685    {
 2686        if self.read_only(cx) {
 2687            return;
 2688        }
 2689
 2690        self.buffer
 2691            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2692    }
 2693
 2694    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2695    where
 2696        I: IntoIterator<Item = (Range<S>, T)>,
 2697        S: ToOffset,
 2698        T: Into<Arc<str>>,
 2699    {
 2700        if self.read_only(cx) {
 2701            return;
 2702        }
 2703
 2704        self.buffer.update(cx, |buffer, cx| {
 2705            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2706        });
 2707    }
 2708
 2709    pub fn edit_with_block_indent<I, S, T>(
 2710        &mut self,
 2711        edits: I,
 2712        original_indent_columns: Vec<u32>,
 2713        cx: &mut ViewContext<Self>,
 2714    ) where
 2715        I: IntoIterator<Item = (Range<S>, T)>,
 2716        S: ToOffset,
 2717        T: Into<Arc<str>>,
 2718    {
 2719        if self.read_only(cx) {
 2720            return;
 2721        }
 2722
 2723        self.buffer.update(cx, |buffer, cx| {
 2724            buffer.edit(
 2725                edits,
 2726                Some(AutoindentMode::Block {
 2727                    original_indent_columns,
 2728                }),
 2729                cx,
 2730            )
 2731        });
 2732    }
 2733
 2734    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2735        self.hide_context_menu(cx);
 2736
 2737        match phase {
 2738            SelectPhase::Begin {
 2739                position,
 2740                add,
 2741                click_count,
 2742            } => self.begin_selection(position, add, click_count, cx),
 2743            SelectPhase::BeginColumnar {
 2744                position,
 2745                goal_column,
 2746                reset,
 2747            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2748            SelectPhase::Extend {
 2749                position,
 2750                click_count,
 2751            } => self.extend_selection(position, click_count, cx),
 2752            SelectPhase::Update {
 2753                position,
 2754                goal_column,
 2755                scroll_delta,
 2756            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2757            SelectPhase::End => self.end_selection(cx),
 2758        }
 2759    }
 2760
 2761    fn extend_selection(
 2762        &mut self,
 2763        position: DisplayPoint,
 2764        click_count: usize,
 2765        cx: &mut ViewContext<Self>,
 2766    ) {
 2767        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2768        let tail = self.selections.newest::<usize>(cx).tail();
 2769        self.begin_selection(position, false, click_count, cx);
 2770
 2771        let position = position.to_offset(&display_map, Bias::Left);
 2772        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2773
 2774        let mut pending_selection = self
 2775            .selections
 2776            .pending_anchor()
 2777            .expect("extend_selection not called with pending selection");
 2778        if position >= tail {
 2779            pending_selection.start = tail_anchor;
 2780        } else {
 2781            pending_selection.end = tail_anchor;
 2782            pending_selection.reversed = true;
 2783        }
 2784
 2785        let mut pending_mode = self.selections.pending_mode().unwrap();
 2786        match &mut pending_mode {
 2787            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2788            _ => {}
 2789        }
 2790
 2791        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2792            s.set_pending(pending_selection, pending_mode)
 2793        });
 2794    }
 2795
 2796    fn begin_selection(
 2797        &mut self,
 2798        position: DisplayPoint,
 2799        add: bool,
 2800        click_count: usize,
 2801        cx: &mut ViewContext<Self>,
 2802    ) {
 2803        if !self.focus_handle.is_focused(cx) {
 2804            self.last_focused_descendant = None;
 2805            cx.focus(&self.focus_handle);
 2806        }
 2807
 2808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2809        let buffer = &display_map.buffer_snapshot;
 2810        let newest_selection = self.selections.newest_anchor().clone();
 2811        let position = display_map.clip_point(position, Bias::Left);
 2812
 2813        let start;
 2814        let end;
 2815        let mode;
 2816        let auto_scroll;
 2817        match click_count {
 2818            1 => {
 2819                start = buffer.anchor_before(position.to_point(&display_map));
 2820                end = start;
 2821                mode = SelectMode::Character;
 2822                auto_scroll = true;
 2823            }
 2824            2 => {
 2825                let range = movement::surrounding_word(&display_map, position);
 2826                start = buffer.anchor_before(range.start.to_point(&display_map));
 2827                end = buffer.anchor_before(range.end.to_point(&display_map));
 2828                mode = SelectMode::Word(start..end);
 2829                auto_scroll = true;
 2830            }
 2831            3 => {
 2832                let position = display_map
 2833                    .clip_point(position, Bias::Left)
 2834                    .to_point(&display_map);
 2835                let line_start = display_map.prev_line_boundary(position).0;
 2836                let next_line_start = buffer.clip_point(
 2837                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2838                    Bias::Left,
 2839                );
 2840                start = buffer.anchor_before(line_start);
 2841                end = buffer.anchor_before(next_line_start);
 2842                mode = SelectMode::Line(start..end);
 2843                auto_scroll = true;
 2844            }
 2845            _ => {
 2846                start = buffer.anchor_before(0);
 2847                end = buffer.anchor_before(buffer.len());
 2848                mode = SelectMode::All;
 2849                auto_scroll = false;
 2850            }
 2851        }
 2852
 2853        let point_to_delete: Option<usize> = {
 2854            let selected_points: Vec<Selection<Point>> =
 2855                self.selections.disjoint_in_range(start..end, cx);
 2856
 2857            if !add || click_count > 1 {
 2858                None
 2859            } else if !selected_points.is_empty() {
 2860                Some(selected_points[0].id)
 2861            } else {
 2862                let clicked_point_already_selected =
 2863                    self.selections.disjoint.iter().find(|selection| {
 2864                        selection.start.to_point(buffer) == start.to_point(buffer)
 2865                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2866                    });
 2867
 2868                clicked_point_already_selected.map(|selection| selection.id)
 2869            }
 2870        };
 2871
 2872        let selections_count = self.selections.count();
 2873
 2874        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2875            if let Some(point_to_delete) = point_to_delete {
 2876                s.delete(point_to_delete);
 2877
 2878                if selections_count == 1 {
 2879                    s.set_pending_anchor_range(start..end, mode);
 2880                }
 2881            } else {
 2882                if !add {
 2883                    s.clear_disjoint();
 2884                } else if click_count > 1 {
 2885                    s.delete(newest_selection.id)
 2886                }
 2887
 2888                s.set_pending_anchor_range(start..end, mode);
 2889            }
 2890        });
 2891    }
 2892
 2893    fn begin_columnar_selection(
 2894        &mut self,
 2895        position: DisplayPoint,
 2896        goal_column: u32,
 2897        reset: bool,
 2898        cx: &mut ViewContext<Self>,
 2899    ) {
 2900        if !self.focus_handle.is_focused(cx) {
 2901            self.last_focused_descendant = None;
 2902            cx.focus(&self.focus_handle);
 2903        }
 2904
 2905        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2906
 2907        if reset {
 2908            let pointer_position = display_map
 2909                .buffer_snapshot
 2910                .anchor_before(position.to_point(&display_map));
 2911
 2912            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2913                s.clear_disjoint();
 2914                s.set_pending_anchor_range(
 2915                    pointer_position..pointer_position,
 2916                    SelectMode::Character,
 2917                );
 2918            });
 2919        }
 2920
 2921        let tail = self.selections.newest::<Point>(cx).tail();
 2922        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2923
 2924        if !reset {
 2925            self.select_columns(
 2926                tail.to_display_point(&display_map),
 2927                position,
 2928                goal_column,
 2929                &display_map,
 2930                cx,
 2931            );
 2932        }
 2933    }
 2934
 2935    fn update_selection(
 2936        &mut self,
 2937        position: DisplayPoint,
 2938        goal_column: u32,
 2939        scroll_delta: gpui::Point<f32>,
 2940        cx: &mut ViewContext<Self>,
 2941    ) {
 2942        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2943
 2944        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2945            let tail = tail.to_display_point(&display_map);
 2946            self.select_columns(tail, position, goal_column, &display_map, cx);
 2947        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2948            let buffer = self.buffer.read(cx).snapshot(cx);
 2949            let head;
 2950            let tail;
 2951            let mode = self.selections.pending_mode().unwrap();
 2952            match &mode {
 2953                SelectMode::Character => {
 2954                    head = position.to_point(&display_map);
 2955                    tail = pending.tail().to_point(&buffer);
 2956                }
 2957                SelectMode::Word(original_range) => {
 2958                    let original_display_range = original_range.start.to_display_point(&display_map)
 2959                        ..original_range.end.to_display_point(&display_map);
 2960                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2961                        ..original_display_range.end.to_point(&display_map);
 2962                    if movement::is_inside_word(&display_map, position)
 2963                        || original_display_range.contains(&position)
 2964                    {
 2965                        let word_range = movement::surrounding_word(&display_map, position);
 2966                        if word_range.start < original_display_range.start {
 2967                            head = word_range.start.to_point(&display_map);
 2968                        } else {
 2969                            head = word_range.end.to_point(&display_map);
 2970                        }
 2971                    } else {
 2972                        head = position.to_point(&display_map);
 2973                    }
 2974
 2975                    if head <= original_buffer_range.start {
 2976                        tail = original_buffer_range.end;
 2977                    } else {
 2978                        tail = original_buffer_range.start;
 2979                    }
 2980                }
 2981                SelectMode::Line(original_range) => {
 2982                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2983
 2984                    let position = display_map
 2985                        .clip_point(position, Bias::Left)
 2986                        .to_point(&display_map);
 2987                    let line_start = display_map.prev_line_boundary(position).0;
 2988                    let next_line_start = buffer.clip_point(
 2989                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2990                        Bias::Left,
 2991                    );
 2992
 2993                    if line_start < original_range.start {
 2994                        head = line_start
 2995                    } else {
 2996                        head = next_line_start
 2997                    }
 2998
 2999                    if head <= original_range.start {
 3000                        tail = original_range.end;
 3001                    } else {
 3002                        tail = original_range.start;
 3003                    }
 3004                }
 3005                SelectMode::All => {
 3006                    return;
 3007                }
 3008            };
 3009
 3010            if head < tail {
 3011                pending.start = buffer.anchor_before(head);
 3012                pending.end = buffer.anchor_before(tail);
 3013                pending.reversed = true;
 3014            } else {
 3015                pending.start = buffer.anchor_before(tail);
 3016                pending.end = buffer.anchor_before(head);
 3017                pending.reversed = false;
 3018            }
 3019
 3020            self.change_selections(None, cx, |s| {
 3021                s.set_pending(pending, mode);
 3022            });
 3023        } else {
 3024            log::error!("update_selection dispatched with no pending selection");
 3025            return;
 3026        }
 3027
 3028        self.apply_scroll_delta(scroll_delta, cx);
 3029        cx.notify();
 3030    }
 3031
 3032    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3033        self.columnar_selection_tail.take();
 3034        if self.selections.pending_anchor().is_some() {
 3035            let selections = self.selections.all::<usize>(cx);
 3036            self.change_selections(None, cx, |s| {
 3037                s.select(selections);
 3038                s.clear_pending();
 3039            });
 3040        }
 3041    }
 3042
 3043    fn select_columns(
 3044        &mut self,
 3045        tail: DisplayPoint,
 3046        head: DisplayPoint,
 3047        goal_column: u32,
 3048        display_map: &DisplaySnapshot,
 3049        cx: &mut ViewContext<Self>,
 3050    ) {
 3051        let start_row = cmp::min(tail.row(), head.row());
 3052        let end_row = cmp::max(tail.row(), head.row());
 3053        let start_column = cmp::min(tail.column(), goal_column);
 3054        let end_column = cmp::max(tail.column(), goal_column);
 3055        let reversed = start_column < tail.column();
 3056
 3057        let selection_ranges = (start_row.0..=end_row.0)
 3058            .map(DisplayRow)
 3059            .filter_map(|row| {
 3060                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3061                    let start = display_map
 3062                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3063                        .to_point(display_map);
 3064                    let end = display_map
 3065                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3066                        .to_point(display_map);
 3067                    if reversed {
 3068                        Some(end..start)
 3069                    } else {
 3070                        Some(start..end)
 3071                    }
 3072                } else {
 3073                    None
 3074                }
 3075            })
 3076            .collect::<Vec<_>>();
 3077
 3078        self.change_selections(None, cx, |s| {
 3079            s.select_ranges(selection_ranges);
 3080        });
 3081        cx.notify();
 3082    }
 3083
 3084    pub fn has_pending_nonempty_selection(&self) -> bool {
 3085        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3086            Some(Selection { start, end, .. }) => start != end,
 3087            None => false,
 3088        };
 3089
 3090        pending_nonempty_selection
 3091            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3092    }
 3093
 3094    pub fn has_pending_selection(&self) -> bool {
 3095        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3096    }
 3097
 3098    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3099        if self.clear_expanded_diff_hunks(cx) {
 3100            cx.notify();
 3101            return;
 3102        }
 3103        if self.dismiss_menus_and_popups(true, cx) {
 3104            return;
 3105        }
 3106
 3107        if self.mode == EditorMode::Full
 3108            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3109        {
 3110            return;
 3111        }
 3112
 3113        cx.propagate();
 3114    }
 3115
 3116    pub fn dismiss_menus_and_popups(
 3117        &mut self,
 3118        should_report_inline_completion_event: bool,
 3119        cx: &mut ViewContext<Self>,
 3120    ) -> bool {
 3121        if self.take_rename(false, cx).is_some() {
 3122            return true;
 3123        }
 3124
 3125        if hide_hover(self, cx) {
 3126            return true;
 3127        }
 3128
 3129        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3130            return true;
 3131        }
 3132
 3133        if self.hide_context_menu(cx).is_some() {
 3134            return true;
 3135        }
 3136
 3137        if self.mouse_context_menu.take().is_some() {
 3138            return true;
 3139        }
 3140
 3141        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3142            return true;
 3143        }
 3144
 3145        if self.snippet_stack.pop().is_some() {
 3146            return true;
 3147        }
 3148
 3149        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3150            self.dismiss_diagnostics(cx);
 3151            return true;
 3152        }
 3153
 3154        false
 3155    }
 3156
 3157    fn linked_editing_ranges_for(
 3158        &self,
 3159        selection: Range<text::Anchor>,
 3160        cx: &AppContext,
 3161    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3162        if self.linked_edit_ranges.is_empty() {
 3163            return None;
 3164        }
 3165        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3166            selection.end.buffer_id.and_then(|end_buffer_id| {
 3167                if selection.start.buffer_id != Some(end_buffer_id) {
 3168                    return None;
 3169                }
 3170                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3171                let snapshot = buffer.read(cx).snapshot();
 3172                self.linked_edit_ranges
 3173                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3174                    .map(|ranges| (ranges, snapshot, buffer))
 3175            })?;
 3176        use text::ToOffset as TO;
 3177        // find offset from the start of current range to current cursor position
 3178        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3179
 3180        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3181        let start_difference = start_offset - start_byte_offset;
 3182        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3183        let end_difference = end_offset - start_byte_offset;
 3184        // Current range has associated linked ranges.
 3185        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3186        for range in linked_ranges.iter() {
 3187            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3188            let end_offset = start_offset + end_difference;
 3189            let start_offset = start_offset + start_difference;
 3190            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3191                continue;
 3192            }
 3193            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3194                if s.start.buffer_id != selection.start.buffer_id
 3195                    || s.end.buffer_id != selection.end.buffer_id
 3196                {
 3197                    return false;
 3198                }
 3199                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3200                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3201            }) {
 3202                continue;
 3203            }
 3204            let start = buffer_snapshot.anchor_after(start_offset);
 3205            let end = buffer_snapshot.anchor_after(end_offset);
 3206            linked_edits
 3207                .entry(buffer.clone())
 3208                .or_default()
 3209                .push(start..end);
 3210        }
 3211        Some(linked_edits)
 3212    }
 3213
 3214    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3215        let text: Arc<str> = text.into();
 3216
 3217        if self.read_only(cx) {
 3218            return;
 3219        }
 3220
 3221        let selections = self.selections.all_adjusted(cx);
 3222        let mut bracket_inserted = false;
 3223        let mut edits = Vec::new();
 3224        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3225        let mut new_selections = Vec::with_capacity(selections.len());
 3226        let mut new_autoclose_regions = Vec::new();
 3227        let snapshot = self.buffer.read(cx).read(cx);
 3228
 3229        for (selection, autoclose_region) in
 3230            self.selections_with_autoclose_regions(selections, &snapshot)
 3231        {
 3232            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3233                // Determine if the inserted text matches the opening or closing
 3234                // bracket of any of this language's bracket pairs.
 3235                let mut bracket_pair = None;
 3236                let mut is_bracket_pair_start = false;
 3237                let mut is_bracket_pair_end = false;
 3238                if !text.is_empty() {
 3239                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3240                    //  and they are removing the character that triggered IME popup.
 3241                    for (pair, enabled) in scope.brackets() {
 3242                        if !pair.close && !pair.surround {
 3243                            continue;
 3244                        }
 3245
 3246                        if enabled && pair.start.ends_with(text.as_ref()) {
 3247                            bracket_pair = Some(pair.clone());
 3248                            is_bracket_pair_start = true;
 3249                            break;
 3250                        }
 3251                        if pair.end.as_str() == text.as_ref() {
 3252                            bracket_pair = Some(pair.clone());
 3253                            is_bracket_pair_end = true;
 3254                            break;
 3255                        }
 3256                    }
 3257                }
 3258
 3259                if let Some(bracket_pair) = bracket_pair {
 3260                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3261                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3262                    let auto_surround =
 3263                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3264                    if selection.is_empty() {
 3265                        if is_bracket_pair_start {
 3266                            let prefix_len = bracket_pair.start.len() - text.len();
 3267
 3268                            // If the inserted text is a suffix of an opening bracket and the
 3269                            // selection is preceded by the rest of the opening bracket, then
 3270                            // insert the closing bracket.
 3271                            let following_text_allows_autoclose = snapshot
 3272                                .chars_at(selection.start)
 3273                                .next()
 3274                                .map_or(true, |c| scope.should_autoclose_before(c));
 3275                            let preceding_text_matches_prefix = prefix_len == 0
 3276                                || (selection.start.column >= (prefix_len as u32)
 3277                                    && snapshot.contains_str_at(
 3278                                        Point::new(
 3279                                            selection.start.row,
 3280                                            selection.start.column - (prefix_len as u32),
 3281                                        ),
 3282                                        &bracket_pair.start[..prefix_len],
 3283                                    ));
 3284
 3285                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3286                                && bracket_pair.start.len() == 1
 3287                            {
 3288                                let target = bracket_pair.start.chars().next().unwrap();
 3289                                let current_line_count = snapshot
 3290                                    .reversed_chars_at(selection.start)
 3291                                    .take_while(|&c| c != '\n')
 3292                                    .filter(|&c| c == target)
 3293                                    .count();
 3294                                current_line_count % 2 == 1
 3295                            } else {
 3296                                false
 3297                            };
 3298
 3299                            if autoclose
 3300                                && bracket_pair.close
 3301                                && following_text_allows_autoclose
 3302                                && preceding_text_matches_prefix
 3303                                && !is_closing_quote
 3304                            {
 3305                                let anchor = snapshot.anchor_before(selection.end);
 3306                                new_selections.push((selection.map(|_| anchor), text.len()));
 3307                                new_autoclose_regions.push((
 3308                                    anchor,
 3309                                    text.len(),
 3310                                    selection.id,
 3311                                    bracket_pair.clone(),
 3312                                ));
 3313                                edits.push((
 3314                                    selection.range(),
 3315                                    format!("{}{}", text, bracket_pair.end).into(),
 3316                                ));
 3317                                bracket_inserted = true;
 3318                                continue;
 3319                            }
 3320                        }
 3321
 3322                        if let Some(region) = autoclose_region {
 3323                            // If the selection is followed by an auto-inserted closing bracket,
 3324                            // then don't insert that closing bracket again; just move the selection
 3325                            // past the closing bracket.
 3326                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3327                                && text.as_ref() == region.pair.end.as_str();
 3328                            if should_skip {
 3329                                let anchor = snapshot.anchor_after(selection.end);
 3330                                new_selections
 3331                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3332                                continue;
 3333                            }
 3334                        }
 3335
 3336                        let always_treat_brackets_as_autoclosed = snapshot
 3337                            .settings_at(selection.start, cx)
 3338                            .always_treat_brackets_as_autoclosed;
 3339                        if always_treat_brackets_as_autoclosed
 3340                            && is_bracket_pair_end
 3341                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3342                        {
 3343                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3344                            // and the inserted text is a closing bracket and the selection is followed
 3345                            // by the closing bracket then move the selection past the closing bracket.
 3346                            let anchor = snapshot.anchor_after(selection.end);
 3347                            new_selections.push((selection.map(|_| anchor), text.len()));
 3348                            continue;
 3349                        }
 3350                    }
 3351                    // If an opening bracket is 1 character long and is typed while
 3352                    // text is selected, then surround that text with the bracket pair.
 3353                    else if auto_surround
 3354                        && bracket_pair.surround
 3355                        && is_bracket_pair_start
 3356                        && bracket_pair.start.chars().count() == 1
 3357                    {
 3358                        edits.push((selection.start..selection.start, text.clone()));
 3359                        edits.push((
 3360                            selection.end..selection.end,
 3361                            bracket_pair.end.as_str().into(),
 3362                        ));
 3363                        bracket_inserted = true;
 3364                        new_selections.push((
 3365                            Selection {
 3366                                id: selection.id,
 3367                                start: snapshot.anchor_after(selection.start),
 3368                                end: snapshot.anchor_before(selection.end),
 3369                                reversed: selection.reversed,
 3370                                goal: selection.goal,
 3371                            },
 3372                            0,
 3373                        ));
 3374                        continue;
 3375                    }
 3376                }
 3377            }
 3378
 3379            if self.auto_replace_emoji_shortcode
 3380                && selection.is_empty()
 3381                && text.as_ref().ends_with(':')
 3382            {
 3383                if let Some(possible_emoji_short_code) =
 3384                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3385                {
 3386                    if !possible_emoji_short_code.is_empty() {
 3387                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3388                            let emoji_shortcode_start = Point::new(
 3389                                selection.start.row,
 3390                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3391                            );
 3392
 3393                            // Remove shortcode from buffer
 3394                            edits.push((
 3395                                emoji_shortcode_start..selection.start,
 3396                                "".to_string().into(),
 3397                            ));
 3398                            new_selections.push((
 3399                                Selection {
 3400                                    id: selection.id,
 3401                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3402                                    end: snapshot.anchor_before(selection.start),
 3403                                    reversed: selection.reversed,
 3404                                    goal: selection.goal,
 3405                                },
 3406                                0,
 3407                            ));
 3408
 3409                            // Insert emoji
 3410                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3411                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3412                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3413
 3414                            continue;
 3415                        }
 3416                    }
 3417                }
 3418            }
 3419
 3420            // If not handling any auto-close operation, then just replace the selected
 3421            // text with the given input and move the selection to the end of the
 3422            // newly inserted text.
 3423            let anchor = snapshot.anchor_after(selection.end);
 3424            if !self.linked_edit_ranges.is_empty() {
 3425                let start_anchor = snapshot.anchor_before(selection.start);
 3426
 3427                let is_word_char = text.chars().next().map_or(true, |char| {
 3428                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3429                    classifier.is_word(char)
 3430                });
 3431
 3432                if is_word_char {
 3433                    if let Some(ranges) = self
 3434                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3435                    {
 3436                        for (buffer, edits) in ranges {
 3437                            linked_edits
 3438                                .entry(buffer.clone())
 3439                                .or_default()
 3440                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3441                        }
 3442                    }
 3443                }
 3444            }
 3445
 3446            new_selections.push((selection.map(|_| anchor), 0));
 3447            edits.push((selection.start..selection.end, text.clone()));
 3448        }
 3449
 3450        drop(snapshot);
 3451
 3452        self.transact(cx, |this, cx| {
 3453            this.buffer.update(cx, |buffer, cx| {
 3454                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3455            });
 3456            for (buffer, edits) in linked_edits {
 3457                buffer.update(cx, |buffer, cx| {
 3458                    let snapshot = buffer.snapshot();
 3459                    let edits = edits
 3460                        .into_iter()
 3461                        .map(|(range, text)| {
 3462                            use text::ToPoint as TP;
 3463                            let end_point = TP::to_point(&range.end, &snapshot);
 3464                            let start_point = TP::to_point(&range.start, &snapshot);
 3465                            (start_point..end_point, text)
 3466                        })
 3467                        .sorted_by_key(|(range, _)| range.start)
 3468                        .collect::<Vec<_>>();
 3469                    buffer.edit(edits, None, cx);
 3470                })
 3471            }
 3472            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3473            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3474            let snapshot = this.buffer.read(cx).read(cx);
 3475            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3476                .zip(new_selection_deltas)
 3477                .map(|(selection, delta)| Selection {
 3478                    id: selection.id,
 3479                    start: selection.start + delta,
 3480                    end: selection.end + delta,
 3481                    reversed: selection.reversed,
 3482                    goal: SelectionGoal::None,
 3483                })
 3484                .collect::<Vec<_>>();
 3485
 3486            let mut i = 0;
 3487            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3488                let position = position.to_offset(&snapshot) + delta;
 3489                let start = snapshot.anchor_before(position);
 3490                let end = snapshot.anchor_after(position);
 3491                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3492                    match existing_state.range.start.cmp(&start, &snapshot) {
 3493                        Ordering::Less => i += 1,
 3494                        Ordering::Greater => break,
 3495                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3496                            Ordering::Less => i += 1,
 3497                            Ordering::Equal => break,
 3498                            Ordering::Greater => break,
 3499                        },
 3500                    }
 3501                }
 3502                this.autoclose_regions.insert(
 3503                    i,
 3504                    AutocloseRegion {
 3505                        selection_id,
 3506                        range: start..end,
 3507                        pair,
 3508                    },
 3509                );
 3510            }
 3511
 3512            drop(snapshot);
 3513            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3514            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3515                s.select(new_selections)
 3516            });
 3517
 3518            if !bracket_inserted {
 3519                if let Some(on_type_format_task) =
 3520                    this.trigger_on_type_formatting(text.to_string(), cx)
 3521                {
 3522                    on_type_format_task.detach_and_log_err(cx);
 3523                }
 3524            }
 3525
 3526            let editor_settings = EditorSettings::get_global(cx);
 3527            if bracket_inserted
 3528                && (editor_settings.auto_signature_help
 3529                    || editor_settings.show_signature_help_after_edits)
 3530            {
 3531                this.show_signature_help(&ShowSignatureHelp, cx);
 3532            }
 3533
 3534            let trigger_in_words = !had_active_inline_completion;
 3535            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3536            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3537            this.refresh_inline_completion(true, false, cx);
 3538        });
 3539    }
 3540
 3541    fn find_possible_emoji_shortcode_at_position(
 3542        snapshot: &MultiBufferSnapshot,
 3543        position: Point,
 3544    ) -> Option<String> {
 3545        let mut chars = Vec::new();
 3546        let mut found_colon = false;
 3547        for char in snapshot.reversed_chars_at(position).take(100) {
 3548            // Found a possible emoji shortcode in the middle of the buffer
 3549            if found_colon {
 3550                if char.is_whitespace() {
 3551                    chars.reverse();
 3552                    return Some(chars.iter().collect());
 3553                }
 3554                // If the previous character is not a whitespace, we are in the middle of a word
 3555                // and we only want to complete the shortcode if the word is made up of other emojis
 3556                let mut containing_word = String::new();
 3557                for ch in snapshot
 3558                    .reversed_chars_at(position)
 3559                    .skip(chars.len() + 1)
 3560                    .take(100)
 3561                {
 3562                    if ch.is_whitespace() {
 3563                        break;
 3564                    }
 3565                    containing_word.push(ch);
 3566                }
 3567                let containing_word = containing_word.chars().rev().collect::<String>();
 3568                if util::word_consists_of_emojis(containing_word.as_str()) {
 3569                    chars.reverse();
 3570                    return Some(chars.iter().collect());
 3571                }
 3572            }
 3573
 3574            if char.is_whitespace() || !char.is_ascii() {
 3575                return None;
 3576            }
 3577            if char == ':' {
 3578                found_colon = true;
 3579            } else {
 3580                chars.push(char);
 3581            }
 3582        }
 3583        // Found a possible emoji shortcode at the beginning of the buffer
 3584        chars.reverse();
 3585        Some(chars.iter().collect())
 3586    }
 3587
 3588    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3589        self.transact(cx, |this, cx| {
 3590            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3591                let selections = this.selections.all::<usize>(cx);
 3592                let multi_buffer = this.buffer.read(cx);
 3593                let buffer = multi_buffer.snapshot(cx);
 3594                selections
 3595                    .iter()
 3596                    .map(|selection| {
 3597                        let start_point = selection.start.to_point(&buffer);
 3598                        let mut indent =
 3599                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3600                        indent.len = cmp::min(indent.len, start_point.column);
 3601                        let start = selection.start;
 3602                        let end = selection.end;
 3603                        let selection_is_empty = start == end;
 3604                        let language_scope = buffer.language_scope_at(start);
 3605                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3606                            &language_scope
 3607                        {
 3608                            let leading_whitespace_len = buffer
 3609                                .reversed_chars_at(start)
 3610                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3611                                .map(|c| c.len_utf8())
 3612                                .sum::<usize>();
 3613
 3614                            let trailing_whitespace_len = buffer
 3615                                .chars_at(end)
 3616                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3617                                .map(|c| c.len_utf8())
 3618                                .sum::<usize>();
 3619
 3620                            let insert_extra_newline =
 3621                                language.brackets().any(|(pair, enabled)| {
 3622                                    let pair_start = pair.start.trim_end();
 3623                                    let pair_end = pair.end.trim_start();
 3624
 3625                                    enabled
 3626                                        && pair.newline
 3627                                        && buffer.contains_str_at(
 3628                                            end + trailing_whitespace_len,
 3629                                            pair_end,
 3630                                        )
 3631                                        && buffer.contains_str_at(
 3632                                            (start - leading_whitespace_len)
 3633                                                .saturating_sub(pair_start.len()),
 3634                                            pair_start,
 3635                                        )
 3636                                });
 3637
 3638                            // Comment extension on newline is allowed only for cursor selections
 3639                            let comment_delimiter = maybe!({
 3640                                if !selection_is_empty {
 3641                                    return None;
 3642                                }
 3643
 3644                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3645                                    return None;
 3646                                }
 3647
 3648                                let delimiters = language.line_comment_prefixes();
 3649                                let max_len_of_delimiter =
 3650                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3651                                let (snapshot, range) =
 3652                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3653
 3654                                let mut index_of_first_non_whitespace = 0;
 3655                                let comment_candidate = snapshot
 3656                                    .chars_for_range(range)
 3657                                    .skip_while(|c| {
 3658                                        let should_skip = c.is_whitespace();
 3659                                        if should_skip {
 3660                                            index_of_first_non_whitespace += 1;
 3661                                        }
 3662                                        should_skip
 3663                                    })
 3664                                    .take(max_len_of_delimiter)
 3665                                    .collect::<String>();
 3666                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3667                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3668                                })?;
 3669                                let cursor_is_placed_after_comment_marker =
 3670                                    index_of_first_non_whitespace + comment_prefix.len()
 3671                                        <= start_point.column as usize;
 3672                                if cursor_is_placed_after_comment_marker {
 3673                                    Some(comment_prefix.clone())
 3674                                } else {
 3675                                    None
 3676                                }
 3677                            });
 3678                            (comment_delimiter, insert_extra_newline)
 3679                        } else {
 3680                            (None, false)
 3681                        };
 3682
 3683                        let capacity_for_delimiter = comment_delimiter
 3684                            .as_deref()
 3685                            .map(str::len)
 3686                            .unwrap_or_default();
 3687                        let mut new_text =
 3688                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3689                        new_text.push('\n');
 3690                        new_text.extend(indent.chars());
 3691                        if let Some(delimiter) = &comment_delimiter {
 3692                            new_text.push_str(delimiter);
 3693                        }
 3694                        if insert_extra_newline {
 3695                            new_text = new_text.repeat(2);
 3696                        }
 3697
 3698                        let anchor = buffer.anchor_after(end);
 3699                        let new_selection = selection.map(|_| anchor);
 3700                        (
 3701                            (start..end, new_text),
 3702                            (insert_extra_newline, new_selection),
 3703                        )
 3704                    })
 3705                    .unzip()
 3706            };
 3707
 3708            this.edit_with_autoindent(edits, cx);
 3709            let buffer = this.buffer.read(cx).snapshot(cx);
 3710            let new_selections = selection_fixup_info
 3711                .into_iter()
 3712                .map(|(extra_newline_inserted, new_selection)| {
 3713                    let mut cursor = new_selection.end.to_point(&buffer);
 3714                    if extra_newline_inserted {
 3715                        cursor.row -= 1;
 3716                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3717                    }
 3718                    new_selection.map(|_| cursor)
 3719                })
 3720                .collect();
 3721
 3722            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3723            this.refresh_inline_completion(true, false, cx);
 3724        });
 3725    }
 3726
 3727    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3728        let buffer = self.buffer.read(cx);
 3729        let snapshot = buffer.snapshot(cx);
 3730
 3731        let mut edits = Vec::new();
 3732        let mut rows = Vec::new();
 3733
 3734        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3735            let cursor = selection.head();
 3736            let row = cursor.row;
 3737
 3738            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3739
 3740            let newline = "\n".to_string();
 3741            edits.push((start_of_line..start_of_line, newline));
 3742
 3743            rows.push(row + rows_inserted as u32);
 3744        }
 3745
 3746        self.transact(cx, |editor, cx| {
 3747            editor.edit(edits, cx);
 3748
 3749            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3750                let mut index = 0;
 3751                s.move_cursors_with(|map, _, _| {
 3752                    let row = rows[index];
 3753                    index += 1;
 3754
 3755                    let point = Point::new(row, 0);
 3756                    let boundary = map.next_line_boundary(point).1;
 3757                    let clipped = map.clip_point(boundary, Bias::Left);
 3758
 3759                    (clipped, SelectionGoal::None)
 3760                });
 3761            });
 3762
 3763            let mut indent_edits = Vec::new();
 3764            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3765            for row in rows {
 3766                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3767                for (row, indent) in indents {
 3768                    if indent.len == 0 {
 3769                        continue;
 3770                    }
 3771
 3772                    let text = match indent.kind {
 3773                        IndentKind::Space => " ".repeat(indent.len as usize),
 3774                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3775                    };
 3776                    let point = Point::new(row.0, 0);
 3777                    indent_edits.push((point..point, text));
 3778                }
 3779            }
 3780            editor.edit(indent_edits, cx);
 3781        });
 3782    }
 3783
 3784    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3785        let buffer = self.buffer.read(cx);
 3786        let snapshot = buffer.snapshot(cx);
 3787
 3788        let mut edits = Vec::new();
 3789        let mut rows = Vec::new();
 3790        let mut rows_inserted = 0;
 3791
 3792        for selection in self.selections.all_adjusted(cx) {
 3793            let cursor = selection.head();
 3794            let row = cursor.row;
 3795
 3796            let point = Point::new(row + 1, 0);
 3797            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3798
 3799            let newline = "\n".to_string();
 3800            edits.push((start_of_line..start_of_line, newline));
 3801
 3802            rows_inserted += 1;
 3803            rows.push(row + rows_inserted);
 3804        }
 3805
 3806        self.transact(cx, |editor, cx| {
 3807            editor.edit(edits, cx);
 3808
 3809            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3810                let mut index = 0;
 3811                s.move_cursors_with(|map, _, _| {
 3812                    let row = rows[index];
 3813                    index += 1;
 3814
 3815                    let point = Point::new(row, 0);
 3816                    let boundary = map.next_line_boundary(point).1;
 3817                    let clipped = map.clip_point(boundary, Bias::Left);
 3818
 3819                    (clipped, SelectionGoal::None)
 3820                });
 3821            });
 3822
 3823            let mut indent_edits = Vec::new();
 3824            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3825            for row in rows {
 3826                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3827                for (row, indent) in indents {
 3828                    if indent.len == 0 {
 3829                        continue;
 3830                    }
 3831
 3832                    let text = match indent.kind {
 3833                        IndentKind::Space => " ".repeat(indent.len as usize),
 3834                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3835                    };
 3836                    let point = Point::new(row.0, 0);
 3837                    indent_edits.push((point..point, text));
 3838                }
 3839            }
 3840            editor.edit(indent_edits, cx);
 3841        });
 3842    }
 3843
 3844    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3845        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3846            original_indent_columns: Vec::new(),
 3847        });
 3848        self.insert_with_autoindent_mode(text, autoindent, cx);
 3849    }
 3850
 3851    fn insert_with_autoindent_mode(
 3852        &mut self,
 3853        text: &str,
 3854        autoindent_mode: Option<AutoindentMode>,
 3855        cx: &mut ViewContext<Self>,
 3856    ) {
 3857        if self.read_only(cx) {
 3858            return;
 3859        }
 3860
 3861        let text: Arc<str> = text.into();
 3862        self.transact(cx, |this, cx| {
 3863            let old_selections = this.selections.all_adjusted(cx);
 3864            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3865                let anchors = {
 3866                    let snapshot = buffer.read(cx);
 3867                    old_selections
 3868                        .iter()
 3869                        .map(|s| {
 3870                            let anchor = snapshot.anchor_after(s.head());
 3871                            s.map(|_| anchor)
 3872                        })
 3873                        .collect::<Vec<_>>()
 3874                };
 3875                buffer.edit(
 3876                    old_selections
 3877                        .iter()
 3878                        .map(|s| (s.start..s.end, text.clone())),
 3879                    autoindent_mode,
 3880                    cx,
 3881                );
 3882                anchors
 3883            });
 3884
 3885            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3886                s.select_anchors(selection_anchors);
 3887            })
 3888        });
 3889    }
 3890
 3891    fn trigger_completion_on_input(
 3892        &mut self,
 3893        text: &str,
 3894        trigger_in_words: bool,
 3895        cx: &mut ViewContext<Self>,
 3896    ) {
 3897        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3898            self.show_completions(
 3899                &ShowCompletions {
 3900                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3901                },
 3902                cx,
 3903            );
 3904        } else {
 3905            self.hide_context_menu(cx);
 3906        }
 3907    }
 3908
 3909    fn is_completion_trigger(
 3910        &self,
 3911        text: &str,
 3912        trigger_in_words: bool,
 3913        cx: &mut ViewContext<Self>,
 3914    ) -> bool {
 3915        let position = self.selections.newest_anchor().head();
 3916        let multibuffer = self.buffer.read(cx);
 3917        let Some(buffer) = position
 3918            .buffer_id
 3919            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3920        else {
 3921            return false;
 3922        };
 3923
 3924        if let Some(completion_provider) = &self.completion_provider {
 3925            completion_provider.is_completion_trigger(
 3926                &buffer,
 3927                position.text_anchor,
 3928                text,
 3929                trigger_in_words,
 3930                cx,
 3931            )
 3932        } else {
 3933            false
 3934        }
 3935    }
 3936
 3937    /// If any empty selections is touching the start of its innermost containing autoclose
 3938    /// region, expand it to select the brackets.
 3939    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3940        let selections = self.selections.all::<usize>(cx);
 3941        let buffer = self.buffer.read(cx).read(cx);
 3942        let new_selections = self
 3943            .selections_with_autoclose_regions(selections, &buffer)
 3944            .map(|(mut selection, region)| {
 3945                if !selection.is_empty() {
 3946                    return selection;
 3947                }
 3948
 3949                if let Some(region) = region {
 3950                    let mut range = region.range.to_offset(&buffer);
 3951                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3952                        range.start -= region.pair.start.len();
 3953                        if buffer.contains_str_at(range.start, &region.pair.start)
 3954                            && buffer.contains_str_at(range.end, &region.pair.end)
 3955                        {
 3956                            range.end += region.pair.end.len();
 3957                            selection.start = range.start;
 3958                            selection.end = range.end;
 3959
 3960                            return selection;
 3961                        }
 3962                    }
 3963                }
 3964
 3965                let always_treat_brackets_as_autoclosed = buffer
 3966                    .settings_at(selection.start, cx)
 3967                    .always_treat_brackets_as_autoclosed;
 3968
 3969                if !always_treat_brackets_as_autoclosed {
 3970                    return selection;
 3971                }
 3972
 3973                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3974                    for (pair, enabled) in scope.brackets() {
 3975                        if !enabled || !pair.close {
 3976                            continue;
 3977                        }
 3978
 3979                        if buffer.contains_str_at(selection.start, &pair.end) {
 3980                            let pair_start_len = pair.start.len();
 3981                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3982                            {
 3983                                selection.start -= pair_start_len;
 3984                                selection.end += pair.end.len();
 3985
 3986                                return selection;
 3987                            }
 3988                        }
 3989                    }
 3990                }
 3991
 3992                selection
 3993            })
 3994            .collect();
 3995
 3996        drop(buffer);
 3997        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3998    }
 3999
 4000    /// Iterate the given selections, and for each one, find the smallest surrounding
 4001    /// autoclose region. This uses the ordering of the selections and the autoclose
 4002    /// regions to avoid repeated comparisons.
 4003    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4004        &'a self,
 4005        selections: impl IntoIterator<Item = Selection<D>>,
 4006        buffer: &'a MultiBufferSnapshot,
 4007    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4008        let mut i = 0;
 4009        let mut regions = self.autoclose_regions.as_slice();
 4010        selections.into_iter().map(move |selection| {
 4011            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4012
 4013            let mut enclosing = None;
 4014            while let Some(pair_state) = regions.get(i) {
 4015                if pair_state.range.end.to_offset(buffer) < range.start {
 4016                    regions = &regions[i + 1..];
 4017                    i = 0;
 4018                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4019                    break;
 4020                } else {
 4021                    if pair_state.selection_id == selection.id {
 4022                        enclosing = Some(pair_state);
 4023                    }
 4024                    i += 1;
 4025                }
 4026            }
 4027
 4028            (selection.clone(), enclosing)
 4029        })
 4030    }
 4031
 4032    /// Remove any autoclose regions that no longer contain their selection.
 4033    fn invalidate_autoclose_regions(
 4034        &mut self,
 4035        mut selections: &[Selection<Anchor>],
 4036        buffer: &MultiBufferSnapshot,
 4037    ) {
 4038        self.autoclose_regions.retain(|state| {
 4039            let mut i = 0;
 4040            while let Some(selection) = selections.get(i) {
 4041                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4042                    selections = &selections[1..];
 4043                    continue;
 4044                }
 4045                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4046                    break;
 4047                }
 4048                if selection.id == state.selection_id {
 4049                    return true;
 4050                } else {
 4051                    i += 1;
 4052                }
 4053            }
 4054            false
 4055        });
 4056    }
 4057
 4058    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4059        let offset = position.to_offset(buffer);
 4060        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4061        if offset > word_range.start && kind == Some(CharKind::Word) {
 4062            Some(
 4063                buffer
 4064                    .text_for_range(word_range.start..offset)
 4065                    .collect::<String>(),
 4066            )
 4067        } else {
 4068            None
 4069        }
 4070    }
 4071
 4072    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4073        self.refresh_inlay_hints(
 4074            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4075            cx,
 4076        );
 4077    }
 4078
 4079    pub fn inlay_hints_enabled(&self) -> bool {
 4080        self.inlay_hint_cache.enabled
 4081    }
 4082
 4083    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4084        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4085            return;
 4086        }
 4087
 4088        let reason_description = reason.description();
 4089        let ignore_debounce = matches!(
 4090            reason,
 4091            InlayHintRefreshReason::SettingsChange(_)
 4092                | InlayHintRefreshReason::Toggle(_)
 4093                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4094        );
 4095        let (invalidate_cache, required_languages) = match reason {
 4096            InlayHintRefreshReason::Toggle(enabled) => {
 4097                self.inlay_hint_cache.enabled = enabled;
 4098                if enabled {
 4099                    (InvalidationStrategy::RefreshRequested, None)
 4100                } else {
 4101                    self.inlay_hint_cache.clear();
 4102                    self.splice_inlays(
 4103                        self.visible_inlay_hints(cx)
 4104                            .iter()
 4105                            .map(|inlay| inlay.id)
 4106                            .collect(),
 4107                        Vec::new(),
 4108                        cx,
 4109                    );
 4110                    return;
 4111                }
 4112            }
 4113            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4114                match self.inlay_hint_cache.update_settings(
 4115                    &self.buffer,
 4116                    new_settings,
 4117                    self.visible_inlay_hints(cx),
 4118                    cx,
 4119                ) {
 4120                    ControlFlow::Break(Some(InlaySplice {
 4121                        to_remove,
 4122                        to_insert,
 4123                    })) => {
 4124                        self.splice_inlays(to_remove, to_insert, cx);
 4125                        return;
 4126                    }
 4127                    ControlFlow::Break(None) => return,
 4128                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4129                }
 4130            }
 4131            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4132                if let Some(InlaySplice {
 4133                    to_remove,
 4134                    to_insert,
 4135                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4136                {
 4137                    self.splice_inlays(to_remove, to_insert, cx);
 4138                }
 4139                return;
 4140            }
 4141            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4142            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4143                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4144            }
 4145            InlayHintRefreshReason::RefreshRequested => {
 4146                (InvalidationStrategy::RefreshRequested, None)
 4147            }
 4148        };
 4149
 4150        if let Some(InlaySplice {
 4151            to_remove,
 4152            to_insert,
 4153        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4154            reason_description,
 4155            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4156            invalidate_cache,
 4157            ignore_debounce,
 4158            cx,
 4159        ) {
 4160            self.splice_inlays(to_remove, to_insert, cx);
 4161        }
 4162    }
 4163
 4164    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4165        self.display_map
 4166            .read(cx)
 4167            .current_inlays()
 4168            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4169            .cloned()
 4170            .collect()
 4171    }
 4172
 4173    pub fn excerpts_for_inlay_hints_query(
 4174        &self,
 4175        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4176        cx: &mut ViewContext<Editor>,
 4177    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4178        let Some(project) = self.project.as_ref() else {
 4179            return HashMap::default();
 4180        };
 4181        let project = project.read(cx);
 4182        let multi_buffer = self.buffer().read(cx);
 4183        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4184        let multi_buffer_visible_start = self
 4185            .scroll_manager
 4186            .anchor()
 4187            .anchor
 4188            .to_point(&multi_buffer_snapshot);
 4189        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4190            multi_buffer_visible_start
 4191                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4192            Bias::Left,
 4193        );
 4194        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4195        multi_buffer
 4196            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4197            .into_iter()
 4198            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4199            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4200                let buffer = buffer_handle.read(cx);
 4201                let buffer_file = project::File::from_dyn(buffer.file())?;
 4202                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4203                let worktree_entry = buffer_worktree
 4204                    .read(cx)
 4205                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4206                if worktree_entry.is_ignored {
 4207                    return None;
 4208                }
 4209
 4210                let language = buffer.language()?;
 4211                if let Some(restrict_to_languages) = restrict_to_languages {
 4212                    if !restrict_to_languages.contains(language) {
 4213                        return None;
 4214                    }
 4215                }
 4216                Some((
 4217                    excerpt_id,
 4218                    (
 4219                        buffer_handle,
 4220                        buffer.version().clone(),
 4221                        excerpt_visible_range,
 4222                    ),
 4223                ))
 4224            })
 4225            .collect()
 4226    }
 4227
 4228    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4229        TextLayoutDetails {
 4230            text_system: cx.text_system().clone(),
 4231            editor_style: self.style.clone().unwrap(),
 4232            rem_size: cx.rem_size(),
 4233            scroll_anchor: self.scroll_manager.anchor(),
 4234            visible_rows: self.visible_line_count(),
 4235            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4236        }
 4237    }
 4238
 4239    fn splice_inlays(
 4240        &self,
 4241        to_remove: Vec<InlayId>,
 4242        to_insert: Vec<Inlay>,
 4243        cx: &mut ViewContext<Self>,
 4244    ) {
 4245        self.display_map.update(cx, |display_map, cx| {
 4246            display_map.splice_inlays(to_remove, to_insert, cx);
 4247        });
 4248        cx.notify();
 4249    }
 4250
 4251    fn trigger_on_type_formatting(
 4252        &self,
 4253        input: String,
 4254        cx: &mut ViewContext<Self>,
 4255    ) -> Option<Task<Result<()>>> {
 4256        if input.len() != 1 {
 4257            return None;
 4258        }
 4259
 4260        let project = self.project.as_ref()?;
 4261        let position = self.selections.newest_anchor().head();
 4262        let (buffer, buffer_position) = self
 4263            .buffer
 4264            .read(cx)
 4265            .text_anchor_for_position(position, cx)?;
 4266
 4267        let settings = language_settings::language_settings(
 4268            buffer
 4269                .read(cx)
 4270                .language_at(buffer_position)
 4271                .map(|l| l.name()),
 4272            buffer.read(cx).file(),
 4273            cx,
 4274        );
 4275        if !settings.use_on_type_format {
 4276            return None;
 4277        }
 4278
 4279        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4280        // hence we do LSP request & edit on host side only — add formats to host's history.
 4281        let push_to_lsp_host_history = true;
 4282        // If this is not the host, append its history with new edits.
 4283        let push_to_client_history = project.read(cx).is_via_collab();
 4284
 4285        let on_type_formatting = project.update(cx, |project, cx| {
 4286            project.on_type_format(
 4287                buffer.clone(),
 4288                buffer_position,
 4289                input,
 4290                push_to_lsp_host_history,
 4291                cx,
 4292            )
 4293        });
 4294        Some(cx.spawn(|editor, mut cx| async move {
 4295            if let Some(transaction) = on_type_formatting.await? {
 4296                if push_to_client_history {
 4297                    buffer
 4298                        .update(&mut cx, |buffer, _| {
 4299                            buffer.push_transaction(transaction, Instant::now());
 4300                        })
 4301                        .ok();
 4302                }
 4303                editor.update(&mut cx, |editor, cx| {
 4304                    editor.refresh_document_highlights(cx);
 4305                })?;
 4306            }
 4307            Ok(())
 4308        }))
 4309    }
 4310
 4311    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4312        if self.pending_rename.is_some() {
 4313            return;
 4314        }
 4315
 4316        let Some(provider) = self.completion_provider.as_ref() else {
 4317            return;
 4318        };
 4319
 4320        let position = self.selections.newest_anchor().head();
 4321        let (buffer, buffer_position) =
 4322            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4323                output
 4324            } else {
 4325                return;
 4326            };
 4327
 4328        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4329        let is_followup_invoke = {
 4330            let context_menu_state = self.context_menu.read();
 4331            matches!(
 4332                context_menu_state.deref(),
 4333                Some(ContextMenu::Completions(_))
 4334            )
 4335        };
 4336        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4337            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4338            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4339                CompletionTriggerKind::TRIGGER_CHARACTER
 4340            }
 4341
 4342            _ => CompletionTriggerKind::INVOKED,
 4343        };
 4344        let completion_context = CompletionContext {
 4345            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4346                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4347                    Some(String::from(trigger))
 4348                } else {
 4349                    None
 4350                }
 4351            }),
 4352            trigger_kind,
 4353        };
 4354        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4355        let sort_completions = provider.sort_completions();
 4356
 4357        let id = post_inc(&mut self.next_completion_id);
 4358        let task = cx.spawn(|this, mut cx| {
 4359            async move {
 4360                this.update(&mut cx, |this, _| {
 4361                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4362                })?;
 4363                let completions = completions.await.log_err();
 4364                let menu = if let Some(completions) = completions {
 4365                    let mut menu = CompletionsMenu {
 4366                        id,
 4367                        sort_completions,
 4368                        initial_position: position,
 4369                        match_candidates: completions
 4370                            .iter()
 4371                            .enumerate()
 4372                            .map(|(id, completion)| {
 4373                                StringMatchCandidate::new(
 4374                                    id,
 4375                                    completion.label.text[completion.label.filter_range.clone()]
 4376                                        .into(),
 4377                                )
 4378                            })
 4379                            .collect(),
 4380                        buffer: buffer.clone(),
 4381                        completions: Arc::new(RwLock::new(completions.into())),
 4382                        matches: Vec::new().into(),
 4383                        selected_item: 0,
 4384                        scroll_handle: UniformListScrollHandle::new(),
 4385                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4386                            DebouncedDelay::new(),
 4387                        )),
 4388                    };
 4389                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4390                        .await;
 4391
 4392                    if menu.matches.is_empty() {
 4393                        None
 4394                    } else {
 4395                        this.update(&mut cx, |editor, cx| {
 4396                            let completions = menu.completions.clone();
 4397                            let matches = menu.matches.clone();
 4398
 4399                            let delay_ms = EditorSettings::get_global(cx)
 4400                                .completion_documentation_secondary_query_debounce;
 4401                            let delay = Duration::from_millis(delay_ms);
 4402                            editor
 4403                                .completion_documentation_pre_resolve_debounce
 4404                                .fire_new(delay, cx, |editor, cx| {
 4405                                    CompletionsMenu::pre_resolve_completion_documentation(
 4406                                        buffer,
 4407                                        completions,
 4408                                        matches,
 4409                                        editor,
 4410                                        cx,
 4411                                    )
 4412                                });
 4413                        })
 4414                        .ok();
 4415                        Some(menu)
 4416                    }
 4417                } else {
 4418                    None
 4419                };
 4420
 4421                this.update(&mut cx, |this, cx| {
 4422                    let mut context_menu = this.context_menu.write();
 4423                    match context_menu.as_ref() {
 4424                        None => {}
 4425
 4426                        Some(ContextMenu::Completions(prev_menu)) => {
 4427                            if prev_menu.id > id {
 4428                                return;
 4429                            }
 4430                        }
 4431
 4432                        _ => return,
 4433                    }
 4434
 4435                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4436                        let menu = menu.unwrap();
 4437                        *context_menu = Some(ContextMenu::Completions(menu));
 4438                        drop(context_menu);
 4439                        this.discard_inline_completion(false, cx);
 4440                        cx.notify();
 4441                    } else if this.completion_tasks.len() <= 1 {
 4442                        // If there are no more completion tasks and the last menu was
 4443                        // empty, we should hide it. If it was already hidden, we should
 4444                        // also show the copilot completion when available.
 4445                        drop(context_menu);
 4446                        if this.hide_context_menu(cx).is_none() {
 4447                            this.update_visible_inline_completion(cx);
 4448                        }
 4449                    }
 4450                })?;
 4451
 4452                Ok::<_, anyhow::Error>(())
 4453            }
 4454            .log_err()
 4455        });
 4456
 4457        self.completion_tasks.push((id, task));
 4458    }
 4459
 4460    pub fn confirm_completion(
 4461        &mut self,
 4462        action: &ConfirmCompletion,
 4463        cx: &mut ViewContext<Self>,
 4464    ) -> Option<Task<Result<()>>> {
 4465        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4466    }
 4467
 4468    pub fn compose_completion(
 4469        &mut self,
 4470        action: &ComposeCompletion,
 4471        cx: &mut ViewContext<Self>,
 4472    ) -> Option<Task<Result<()>>> {
 4473        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4474    }
 4475
 4476    fn do_completion(
 4477        &mut self,
 4478        item_ix: Option<usize>,
 4479        intent: CompletionIntent,
 4480        cx: &mut ViewContext<Editor>,
 4481    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4482        use language::ToOffset as _;
 4483
 4484        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4485            menu
 4486        } else {
 4487            return None;
 4488        };
 4489
 4490        let mat = completions_menu
 4491            .matches
 4492            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4493        let buffer_handle = completions_menu.buffer;
 4494        let completions = completions_menu.completions.read();
 4495        let completion = completions.get(mat.candidate_id)?;
 4496        cx.stop_propagation();
 4497
 4498        let snippet;
 4499        let text;
 4500
 4501        if completion.is_snippet() {
 4502            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4503            text = snippet.as_ref().unwrap().text.clone();
 4504        } else {
 4505            snippet = None;
 4506            text = completion.new_text.clone();
 4507        };
 4508        let selections = self.selections.all::<usize>(cx);
 4509        let buffer = buffer_handle.read(cx);
 4510        let old_range = completion.old_range.to_offset(buffer);
 4511        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4512
 4513        let newest_selection = self.selections.newest_anchor();
 4514        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4515            return None;
 4516        }
 4517
 4518        let lookbehind = newest_selection
 4519            .start
 4520            .text_anchor
 4521            .to_offset(buffer)
 4522            .saturating_sub(old_range.start);
 4523        let lookahead = old_range
 4524            .end
 4525            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4526        let mut common_prefix_len = old_text
 4527            .bytes()
 4528            .zip(text.bytes())
 4529            .take_while(|(a, b)| a == b)
 4530            .count();
 4531
 4532        let snapshot = self.buffer.read(cx).snapshot(cx);
 4533        let mut range_to_replace: Option<Range<isize>> = None;
 4534        let mut ranges = Vec::new();
 4535        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4536        for selection in &selections {
 4537            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4538                let start = selection.start.saturating_sub(lookbehind);
 4539                let end = selection.end + lookahead;
 4540                if selection.id == newest_selection.id {
 4541                    range_to_replace = Some(
 4542                        ((start + common_prefix_len) as isize - selection.start as isize)
 4543                            ..(end as isize - selection.start as isize),
 4544                    );
 4545                }
 4546                ranges.push(start + common_prefix_len..end);
 4547            } else {
 4548                common_prefix_len = 0;
 4549                ranges.clear();
 4550                ranges.extend(selections.iter().map(|s| {
 4551                    if s.id == newest_selection.id {
 4552                        range_to_replace = Some(
 4553                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4554                                - selection.start as isize
 4555                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4556                                    - selection.start as isize,
 4557                        );
 4558                        old_range.clone()
 4559                    } else {
 4560                        s.start..s.end
 4561                    }
 4562                }));
 4563                break;
 4564            }
 4565            if !self.linked_edit_ranges.is_empty() {
 4566                let start_anchor = snapshot.anchor_before(selection.head());
 4567                let end_anchor = snapshot.anchor_after(selection.tail());
 4568                if let Some(ranges) = self
 4569                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4570                {
 4571                    for (buffer, edits) in ranges {
 4572                        linked_edits.entry(buffer.clone()).or_default().extend(
 4573                            edits
 4574                                .into_iter()
 4575                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4576                        );
 4577                    }
 4578                }
 4579            }
 4580        }
 4581        let text = &text[common_prefix_len..];
 4582
 4583        cx.emit(EditorEvent::InputHandled {
 4584            utf16_range_to_replace: range_to_replace,
 4585            text: text.into(),
 4586        });
 4587
 4588        self.transact(cx, |this, cx| {
 4589            if let Some(mut snippet) = snippet {
 4590                snippet.text = text.to_string();
 4591                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4592                    tabstop.start -= common_prefix_len as isize;
 4593                    tabstop.end -= common_prefix_len as isize;
 4594                }
 4595
 4596                this.insert_snippet(&ranges, snippet, cx).log_err();
 4597            } else {
 4598                this.buffer.update(cx, |buffer, cx| {
 4599                    buffer.edit(
 4600                        ranges.iter().map(|range| (range.clone(), text)),
 4601                        this.autoindent_mode.clone(),
 4602                        cx,
 4603                    );
 4604                });
 4605            }
 4606            for (buffer, edits) in linked_edits {
 4607                buffer.update(cx, |buffer, cx| {
 4608                    let snapshot = buffer.snapshot();
 4609                    let edits = edits
 4610                        .into_iter()
 4611                        .map(|(range, text)| {
 4612                            use text::ToPoint as TP;
 4613                            let end_point = TP::to_point(&range.end, &snapshot);
 4614                            let start_point = TP::to_point(&range.start, &snapshot);
 4615                            (start_point..end_point, text)
 4616                        })
 4617                        .sorted_by_key(|(range, _)| range.start)
 4618                        .collect::<Vec<_>>();
 4619                    buffer.edit(edits, None, cx);
 4620                })
 4621            }
 4622
 4623            this.refresh_inline_completion(true, false, cx);
 4624        });
 4625
 4626        let show_new_completions_on_confirm = completion
 4627            .confirm
 4628            .as_ref()
 4629            .map_or(false, |confirm| confirm(intent, cx));
 4630        if show_new_completions_on_confirm {
 4631            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4632        }
 4633
 4634        let provider = self.completion_provider.as_ref()?;
 4635        let apply_edits = provider.apply_additional_edits_for_completion(
 4636            buffer_handle,
 4637            completion.clone(),
 4638            true,
 4639            cx,
 4640        );
 4641
 4642        let editor_settings = EditorSettings::get_global(cx);
 4643        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4644            // After the code completion is finished, users often want to know what signatures are needed.
 4645            // so we should automatically call signature_help
 4646            self.show_signature_help(&ShowSignatureHelp, cx);
 4647        }
 4648
 4649        Some(cx.foreground_executor().spawn(async move {
 4650            apply_edits.await?;
 4651            Ok(())
 4652        }))
 4653    }
 4654
 4655    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4656        let mut context_menu = self.context_menu.write();
 4657        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4658            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4659                // Toggle if we're selecting the same one
 4660                *context_menu = None;
 4661                cx.notify();
 4662                return;
 4663            } else {
 4664                // Otherwise, clear it and start a new one
 4665                *context_menu = None;
 4666                cx.notify();
 4667            }
 4668        }
 4669        drop(context_menu);
 4670        let snapshot = self.snapshot(cx);
 4671        let deployed_from_indicator = action.deployed_from_indicator;
 4672        let mut task = self.code_actions_task.take();
 4673        let action = action.clone();
 4674        cx.spawn(|editor, mut cx| async move {
 4675            while let Some(prev_task) = task {
 4676                prev_task.await.log_err();
 4677                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4678            }
 4679
 4680            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4681                if editor.focus_handle.is_focused(cx) {
 4682                    let multibuffer_point = action
 4683                        .deployed_from_indicator
 4684                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4685                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4686                    let (buffer, buffer_row) = snapshot
 4687                        .buffer_snapshot
 4688                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4689                        .and_then(|(buffer_snapshot, range)| {
 4690                            editor
 4691                                .buffer
 4692                                .read(cx)
 4693                                .buffer(buffer_snapshot.remote_id())
 4694                                .map(|buffer| (buffer, range.start.row))
 4695                        })?;
 4696                    let (_, code_actions) = editor
 4697                        .available_code_actions
 4698                        .clone()
 4699                        .and_then(|(location, code_actions)| {
 4700                            let snapshot = location.buffer.read(cx).snapshot();
 4701                            let point_range = location.range.to_point(&snapshot);
 4702                            let point_range = point_range.start.row..=point_range.end.row;
 4703                            if point_range.contains(&buffer_row) {
 4704                                Some((location, code_actions))
 4705                            } else {
 4706                                None
 4707                            }
 4708                        })
 4709                        .unzip();
 4710                    let buffer_id = buffer.read(cx).remote_id();
 4711                    let tasks = editor
 4712                        .tasks
 4713                        .get(&(buffer_id, buffer_row))
 4714                        .map(|t| Arc::new(t.to_owned()));
 4715                    if tasks.is_none() && code_actions.is_none() {
 4716                        return None;
 4717                    }
 4718
 4719                    editor.completion_tasks.clear();
 4720                    editor.discard_inline_completion(false, cx);
 4721                    let task_context =
 4722                        tasks
 4723                            .as_ref()
 4724                            .zip(editor.project.clone())
 4725                            .map(|(tasks, project)| {
 4726                                let position = Point::new(buffer_row, tasks.column);
 4727                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4728                                let location = Location {
 4729                                    buffer: buffer.clone(),
 4730                                    range: range_start..range_start,
 4731                                };
 4732                                // Fill in the environmental variables from the tree-sitter captures
 4733                                let mut captured_task_variables = TaskVariables::default();
 4734                                for (capture_name, value) in tasks.extra_variables.clone() {
 4735                                    captured_task_variables.insert(
 4736                                        task::VariableName::Custom(capture_name.into()),
 4737                                        value.clone(),
 4738                                    );
 4739                                }
 4740                                project.update(cx, |project, cx| {
 4741                                    project.task_store().update(cx, |task_store, cx| {
 4742                                        task_store.task_context_for_location(
 4743                                            captured_task_variables,
 4744                                            location,
 4745                                            cx,
 4746                                        )
 4747                                    })
 4748                                })
 4749                            });
 4750
 4751                    Some(cx.spawn(|editor, mut cx| async move {
 4752                        let task_context = match task_context {
 4753                            Some(task_context) => task_context.await,
 4754                            None => None,
 4755                        };
 4756                        let resolved_tasks =
 4757                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4758                                Arc::new(ResolvedTasks {
 4759                                    templates: tasks
 4760                                        .templates
 4761                                        .iter()
 4762                                        .filter_map(|(kind, template)| {
 4763                                            template
 4764                                                .resolve_task(&kind.to_id_base(), &task_context)
 4765                                                .map(|task| (kind.clone(), task))
 4766                                        })
 4767                                        .collect(),
 4768                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4769                                        multibuffer_point.row,
 4770                                        tasks.column,
 4771                                    )),
 4772                                })
 4773                            });
 4774                        let spawn_straight_away = resolved_tasks
 4775                            .as_ref()
 4776                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4777                            && code_actions
 4778                                .as_ref()
 4779                                .map_or(true, |actions| actions.is_empty());
 4780                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4781                            *editor.context_menu.write() =
 4782                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4783                                    buffer,
 4784                                    actions: CodeActionContents {
 4785                                        tasks: resolved_tasks,
 4786                                        actions: code_actions,
 4787                                    },
 4788                                    selected_item: Default::default(),
 4789                                    scroll_handle: UniformListScrollHandle::default(),
 4790                                    deployed_from_indicator,
 4791                                }));
 4792                            if spawn_straight_away {
 4793                                if let Some(task) = editor.confirm_code_action(
 4794                                    &ConfirmCodeAction { item_ix: Some(0) },
 4795                                    cx,
 4796                                ) {
 4797                                    cx.notify();
 4798                                    return task;
 4799                                }
 4800                            }
 4801                            cx.notify();
 4802                            Task::ready(Ok(()))
 4803                        }) {
 4804                            task.await
 4805                        } else {
 4806                            Ok(())
 4807                        }
 4808                    }))
 4809                } else {
 4810                    Some(Task::ready(Ok(())))
 4811                }
 4812            })?;
 4813            if let Some(task) = spawned_test_task {
 4814                task.await?;
 4815            }
 4816
 4817            Ok::<_, anyhow::Error>(())
 4818        })
 4819        .detach_and_log_err(cx);
 4820    }
 4821
 4822    pub fn confirm_code_action(
 4823        &mut self,
 4824        action: &ConfirmCodeAction,
 4825        cx: &mut ViewContext<Self>,
 4826    ) -> Option<Task<Result<()>>> {
 4827        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4828            menu
 4829        } else {
 4830            return None;
 4831        };
 4832        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4833        let action = actions_menu.actions.get(action_ix)?;
 4834        let title = action.label();
 4835        let buffer = actions_menu.buffer;
 4836        let workspace = self.workspace()?;
 4837
 4838        match action {
 4839            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4840                workspace.update(cx, |workspace, cx| {
 4841                    workspace::tasks::schedule_resolved_task(
 4842                        workspace,
 4843                        task_source_kind,
 4844                        resolved_task,
 4845                        false,
 4846                        cx,
 4847                    );
 4848
 4849                    Some(Task::ready(Ok(())))
 4850                })
 4851            }
 4852            CodeActionsItem::CodeAction {
 4853                excerpt_id,
 4854                action,
 4855                provider,
 4856            } => {
 4857                let apply_code_action =
 4858                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4859                let workspace = workspace.downgrade();
 4860                Some(cx.spawn(|editor, cx| async move {
 4861                    let project_transaction = apply_code_action.await?;
 4862                    Self::open_project_transaction(
 4863                        &editor,
 4864                        workspace,
 4865                        project_transaction,
 4866                        title,
 4867                        cx,
 4868                    )
 4869                    .await
 4870                }))
 4871            }
 4872        }
 4873    }
 4874
 4875    pub async fn open_project_transaction(
 4876        this: &WeakView<Editor>,
 4877        workspace: WeakView<Workspace>,
 4878        transaction: ProjectTransaction,
 4879        title: String,
 4880        mut cx: AsyncWindowContext,
 4881    ) -> Result<()> {
 4882        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4883        cx.update(|cx| {
 4884            entries.sort_unstable_by_key(|(buffer, _)| {
 4885                buffer.read(cx).file().map(|f| f.path().clone())
 4886            });
 4887        })?;
 4888
 4889        // If the project transaction's edits are all contained within this editor, then
 4890        // avoid opening a new editor to display them.
 4891
 4892        if let Some((buffer, transaction)) = entries.first() {
 4893            if entries.len() == 1 {
 4894                let excerpt = this.update(&mut cx, |editor, cx| {
 4895                    editor
 4896                        .buffer()
 4897                        .read(cx)
 4898                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4899                })?;
 4900                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4901                    if excerpted_buffer == *buffer {
 4902                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4903                            let excerpt_range = excerpt_range.to_offset(buffer);
 4904                            buffer
 4905                                .edited_ranges_for_transaction::<usize>(transaction)
 4906                                .all(|range| {
 4907                                    excerpt_range.start <= range.start
 4908                                        && excerpt_range.end >= range.end
 4909                                })
 4910                        })?;
 4911
 4912                        if all_edits_within_excerpt {
 4913                            return Ok(());
 4914                        }
 4915                    }
 4916                }
 4917            }
 4918        } else {
 4919            return Ok(());
 4920        }
 4921
 4922        let mut ranges_to_highlight = Vec::new();
 4923        let excerpt_buffer = cx.new_model(|cx| {
 4924            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4925            for (buffer_handle, transaction) in &entries {
 4926                let buffer = buffer_handle.read(cx);
 4927                ranges_to_highlight.extend(
 4928                    multibuffer.push_excerpts_with_context_lines(
 4929                        buffer_handle.clone(),
 4930                        buffer
 4931                            .edited_ranges_for_transaction::<usize>(transaction)
 4932                            .collect(),
 4933                        DEFAULT_MULTIBUFFER_CONTEXT,
 4934                        cx,
 4935                    ),
 4936                );
 4937            }
 4938            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4939            multibuffer
 4940        })?;
 4941
 4942        workspace.update(&mut cx, |workspace, cx| {
 4943            let project = workspace.project().clone();
 4944            let editor =
 4945                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4946            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4947            editor.update(cx, |editor, cx| {
 4948                editor.highlight_background::<Self>(
 4949                    &ranges_to_highlight,
 4950                    |theme| theme.editor_highlighted_line_background,
 4951                    cx,
 4952                );
 4953            });
 4954        })?;
 4955
 4956        Ok(())
 4957    }
 4958
 4959    pub fn clear_code_action_providers(&mut self) {
 4960        self.code_action_providers.clear();
 4961        self.available_code_actions.take();
 4962    }
 4963
 4964    pub fn push_code_action_provider(
 4965        &mut self,
 4966        provider: Arc<dyn CodeActionProvider>,
 4967        cx: &mut ViewContext<Self>,
 4968    ) {
 4969        self.code_action_providers.push(provider);
 4970        self.refresh_code_actions(cx);
 4971    }
 4972
 4973    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4974        let buffer = self.buffer.read(cx);
 4975        let newest_selection = self.selections.newest_anchor().clone();
 4976        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4977        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4978        if start_buffer != end_buffer {
 4979            return None;
 4980        }
 4981
 4982        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4983            cx.background_executor()
 4984                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4985                .await;
 4986
 4987            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4988                let providers = this.code_action_providers.clone();
 4989                let tasks = this
 4990                    .code_action_providers
 4991                    .iter()
 4992                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4993                    .collect::<Vec<_>>();
 4994                (providers, tasks)
 4995            })?;
 4996
 4997            let mut actions = Vec::new();
 4998            for (provider, provider_actions) in
 4999                providers.into_iter().zip(future::join_all(tasks).await)
 5000            {
 5001                if let Some(provider_actions) = provider_actions.log_err() {
 5002                    actions.extend(provider_actions.into_iter().map(|action| {
 5003                        AvailableCodeAction {
 5004                            excerpt_id: newest_selection.start.excerpt_id,
 5005                            action,
 5006                            provider: provider.clone(),
 5007                        }
 5008                    }));
 5009                }
 5010            }
 5011
 5012            this.update(&mut cx, |this, cx| {
 5013                this.available_code_actions = if actions.is_empty() {
 5014                    None
 5015                } else {
 5016                    Some((
 5017                        Location {
 5018                            buffer: start_buffer,
 5019                            range: start..end,
 5020                        },
 5021                        actions.into(),
 5022                    ))
 5023                };
 5024                cx.notify();
 5025            })
 5026        }));
 5027        None
 5028    }
 5029
 5030    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5031        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5032            self.show_git_blame_inline = false;
 5033
 5034            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5035                cx.background_executor().timer(delay).await;
 5036
 5037                this.update(&mut cx, |this, cx| {
 5038                    this.show_git_blame_inline = true;
 5039                    cx.notify();
 5040                })
 5041                .log_err();
 5042            }));
 5043        }
 5044    }
 5045
 5046    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5047        if self.pending_rename.is_some() {
 5048            return None;
 5049        }
 5050
 5051        let provider = self.semantics_provider.clone()?;
 5052        let buffer = self.buffer.read(cx);
 5053        let newest_selection = self.selections.newest_anchor().clone();
 5054        let cursor_position = newest_selection.head();
 5055        let (cursor_buffer, cursor_buffer_position) =
 5056            buffer.text_anchor_for_position(cursor_position, cx)?;
 5057        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5058        if cursor_buffer != tail_buffer {
 5059            return None;
 5060        }
 5061
 5062        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5063            cx.background_executor()
 5064                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5065                .await;
 5066
 5067            let highlights = if let Some(highlights) = cx
 5068                .update(|cx| {
 5069                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5070                })
 5071                .ok()
 5072                .flatten()
 5073            {
 5074                highlights.await.log_err()
 5075            } else {
 5076                None
 5077            };
 5078
 5079            if let Some(highlights) = highlights {
 5080                this.update(&mut cx, |this, cx| {
 5081                    if this.pending_rename.is_some() {
 5082                        return;
 5083                    }
 5084
 5085                    let buffer_id = cursor_position.buffer_id;
 5086                    let buffer = this.buffer.read(cx);
 5087                    if !buffer
 5088                        .text_anchor_for_position(cursor_position, cx)
 5089                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5090                    {
 5091                        return;
 5092                    }
 5093
 5094                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5095                    let mut write_ranges = Vec::new();
 5096                    let mut read_ranges = Vec::new();
 5097                    for highlight in highlights {
 5098                        for (excerpt_id, excerpt_range) in
 5099                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5100                        {
 5101                            let start = highlight
 5102                                .range
 5103                                .start
 5104                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5105                            let end = highlight
 5106                                .range
 5107                                .end
 5108                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5109                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5110                                continue;
 5111                            }
 5112
 5113                            let range = Anchor {
 5114                                buffer_id,
 5115                                excerpt_id,
 5116                                text_anchor: start,
 5117                            }..Anchor {
 5118                                buffer_id,
 5119                                excerpt_id,
 5120                                text_anchor: end,
 5121                            };
 5122                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5123                                write_ranges.push(range);
 5124                            } else {
 5125                                read_ranges.push(range);
 5126                            }
 5127                        }
 5128                    }
 5129
 5130                    this.highlight_background::<DocumentHighlightRead>(
 5131                        &read_ranges,
 5132                        |theme| theme.editor_document_highlight_read_background,
 5133                        cx,
 5134                    );
 5135                    this.highlight_background::<DocumentHighlightWrite>(
 5136                        &write_ranges,
 5137                        |theme| theme.editor_document_highlight_write_background,
 5138                        cx,
 5139                    );
 5140                    cx.notify();
 5141                })
 5142                .log_err();
 5143            }
 5144        }));
 5145        None
 5146    }
 5147
 5148    pub fn refresh_inline_completion(
 5149        &mut self,
 5150        debounce: bool,
 5151        user_requested: bool,
 5152        cx: &mut ViewContext<Self>,
 5153    ) -> Option<()> {
 5154        let provider = self.inline_completion_provider()?;
 5155        let cursor = self.selections.newest_anchor().head();
 5156        let (buffer, cursor_buffer_position) =
 5157            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5158
 5159        if !user_requested
 5160            && (!self.enable_inline_completions
 5161                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5162        {
 5163            self.discard_inline_completion(false, cx);
 5164            return None;
 5165        }
 5166
 5167        self.update_visible_inline_completion(cx);
 5168        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5169        Some(())
 5170    }
 5171
 5172    fn cycle_inline_completion(
 5173        &mut self,
 5174        direction: Direction,
 5175        cx: &mut ViewContext<Self>,
 5176    ) -> Option<()> {
 5177        let provider = self.inline_completion_provider()?;
 5178        let cursor = self.selections.newest_anchor().head();
 5179        let (buffer, cursor_buffer_position) =
 5180            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5181        if !self.enable_inline_completions
 5182            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5183        {
 5184            return None;
 5185        }
 5186
 5187        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5188        self.update_visible_inline_completion(cx);
 5189
 5190        Some(())
 5191    }
 5192
 5193    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5194        if !self.has_active_inline_completion(cx) {
 5195            self.refresh_inline_completion(false, true, cx);
 5196            return;
 5197        }
 5198
 5199        self.update_visible_inline_completion(cx);
 5200    }
 5201
 5202    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5203        self.show_cursor_names(cx);
 5204    }
 5205
 5206    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5207        self.show_cursor_names = true;
 5208        cx.notify();
 5209        cx.spawn(|this, mut cx| async move {
 5210            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5211            this.update(&mut cx, |this, cx| {
 5212                this.show_cursor_names = false;
 5213                cx.notify()
 5214            })
 5215            .ok()
 5216        })
 5217        .detach();
 5218    }
 5219
 5220    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5221        if self.has_active_inline_completion(cx) {
 5222            self.cycle_inline_completion(Direction::Next, cx);
 5223        } else {
 5224            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5225            if is_copilot_disabled {
 5226                cx.propagate();
 5227            }
 5228        }
 5229    }
 5230
 5231    pub fn previous_inline_completion(
 5232        &mut self,
 5233        _: &PreviousInlineCompletion,
 5234        cx: &mut ViewContext<Self>,
 5235    ) {
 5236        if self.has_active_inline_completion(cx) {
 5237            self.cycle_inline_completion(Direction::Prev, cx);
 5238        } else {
 5239            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5240            if is_copilot_disabled {
 5241                cx.propagate();
 5242            }
 5243        }
 5244    }
 5245
 5246    pub fn accept_inline_completion(
 5247        &mut self,
 5248        _: &AcceptInlineCompletion,
 5249        cx: &mut ViewContext<Self>,
 5250    ) {
 5251        let Some(completion) = self.take_active_inline_completion(cx) else {
 5252            return;
 5253        };
 5254        if let Some(provider) = self.inline_completion_provider() {
 5255            provider.accept(cx);
 5256        }
 5257
 5258        cx.emit(EditorEvent::InputHandled {
 5259            utf16_range_to_replace: None,
 5260            text: completion.text.to_string().into(),
 5261        });
 5262
 5263        if let Some(range) = completion.delete_range {
 5264            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5265        }
 5266        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5267        self.refresh_inline_completion(true, true, cx);
 5268        cx.notify();
 5269    }
 5270
 5271    pub fn accept_partial_inline_completion(
 5272        &mut self,
 5273        _: &AcceptPartialInlineCompletion,
 5274        cx: &mut ViewContext<Self>,
 5275    ) {
 5276        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5277            if let Some(completion) = self.take_active_inline_completion(cx) {
 5278                let mut partial_completion = completion
 5279                    .text
 5280                    .chars()
 5281                    .by_ref()
 5282                    .take_while(|c| c.is_alphabetic())
 5283                    .collect::<String>();
 5284                if partial_completion.is_empty() {
 5285                    partial_completion = completion
 5286                        .text
 5287                        .chars()
 5288                        .by_ref()
 5289                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5290                        .collect::<String>();
 5291                }
 5292
 5293                cx.emit(EditorEvent::InputHandled {
 5294                    utf16_range_to_replace: None,
 5295                    text: partial_completion.clone().into(),
 5296                });
 5297
 5298                if let Some(range) = completion.delete_range {
 5299                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5300                }
 5301                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5302
 5303                self.refresh_inline_completion(true, true, cx);
 5304                cx.notify();
 5305            }
 5306        }
 5307    }
 5308
 5309    fn discard_inline_completion(
 5310        &mut self,
 5311        should_report_inline_completion_event: bool,
 5312        cx: &mut ViewContext<Self>,
 5313    ) -> bool {
 5314        if let Some(provider) = self.inline_completion_provider() {
 5315            provider.discard(should_report_inline_completion_event, cx);
 5316        }
 5317
 5318        self.take_active_inline_completion(cx).is_some()
 5319    }
 5320
 5321    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5322        if let Some(completion) = self.active_inline_completion.as_ref() {
 5323            let buffer = self.buffer.read(cx).read(cx);
 5324            completion.position.is_valid(&buffer)
 5325        } else {
 5326            false
 5327        }
 5328    }
 5329
 5330    fn take_active_inline_completion(
 5331        &mut self,
 5332        cx: &mut ViewContext<Self>,
 5333    ) -> Option<CompletionState> {
 5334        let completion = self.active_inline_completion.take()?;
 5335        let render_inlay_ids = completion.render_inlay_ids.clone();
 5336        self.display_map.update(cx, |map, cx| {
 5337            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5338        });
 5339        let buffer = self.buffer.read(cx).read(cx);
 5340
 5341        if completion.position.is_valid(&buffer) {
 5342            Some(completion)
 5343        } else {
 5344            None
 5345        }
 5346    }
 5347
 5348    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5349        let selection = self.selections.newest_anchor();
 5350        let cursor = selection.head();
 5351
 5352        let excerpt_id = cursor.excerpt_id;
 5353
 5354        if self.context_menu.read().is_none()
 5355            && self.completion_tasks.is_empty()
 5356            && selection.start == selection.end
 5357        {
 5358            if let Some(provider) = self.inline_completion_provider() {
 5359                if let Some((buffer, cursor_buffer_position)) =
 5360                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5361                {
 5362                    if let Some(proposal) =
 5363                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5364                    {
 5365                        let mut to_remove = Vec::new();
 5366                        if let Some(completion) = self.active_inline_completion.take() {
 5367                            to_remove.extend(completion.render_inlay_ids.iter());
 5368                        }
 5369
 5370                        let to_add = proposal
 5371                            .inlays
 5372                            .iter()
 5373                            .filter_map(|inlay| {
 5374                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5375                                let id = post_inc(&mut self.next_inlay_id);
 5376                                match inlay {
 5377                                    InlayProposal::Hint(position, hint) => {
 5378                                        let position =
 5379                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5380                                        Some(Inlay::hint(id, position, hint))
 5381                                    }
 5382                                    InlayProposal::Suggestion(position, text) => {
 5383                                        let position =
 5384                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5385                                        Some(Inlay::suggestion(id, position, text.clone()))
 5386                                    }
 5387                                }
 5388                            })
 5389                            .collect_vec();
 5390
 5391                        self.active_inline_completion = Some(CompletionState {
 5392                            position: cursor,
 5393                            text: proposal.text,
 5394                            delete_range: proposal.delete_range.and_then(|range| {
 5395                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5396                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5397                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5398                                Some(start?..end?)
 5399                            }),
 5400                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5401                        });
 5402
 5403                        self.display_map
 5404                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5405
 5406                        cx.notify();
 5407                        return;
 5408                    }
 5409                }
 5410            }
 5411        }
 5412
 5413        self.discard_inline_completion(false, cx);
 5414    }
 5415
 5416    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5417        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5418    }
 5419
 5420    fn render_code_actions_indicator(
 5421        &self,
 5422        _style: &EditorStyle,
 5423        row: DisplayRow,
 5424        is_active: bool,
 5425        cx: &mut ViewContext<Self>,
 5426    ) -> Option<IconButton> {
 5427        if self.available_code_actions.is_some() {
 5428            Some(
 5429                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5430                    .shape(ui::IconButtonShape::Square)
 5431                    .icon_size(IconSize::XSmall)
 5432                    .icon_color(Color::Muted)
 5433                    .selected(is_active)
 5434                    .tooltip({
 5435                        let focus_handle = self.focus_handle.clone();
 5436                        move |cx| {
 5437                            Tooltip::for_action_in(
 5438                                "Toggle Code Actions",
 5439                                &ToggleCodeActions {
 5440                                    deployed_from_indicator: None,
 5441                                },
 5442                                &focus_handle,
 5443                                cx,
 5444                            )
 5445                        }
 5446                    })
 5447                    .on_click(cx.listener(move |editor, _e, cx| {
 5448                        editor.focus(cx);
 5449                        editor.toggle_code_actions(
 5450                            &ToggleCodeActions {
 5451                                deployed_from_indicator: Some(row),
 5452                            },
 5453                            cx,
 5454                        );
 5455                    })),
 5456            )
 5457        } else {
 5458            None
 5459        }
 5460    }
 5461
 5462    fn clear_tasks(&mut self) {
 5463        self.tasks.clear()
 5464    }
 5465
 5466    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5467        if self.tasks.insert(key, value).is_some() {
 5468            // This case should hopefully be rare, but just in case...
 5469            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5470        }
 5471    }
 5472
 5473    fn render_run_indicator(
 5474        &self,
 5475        _style: &EditorStyle,
 5476        is_active: bool,
 5477        row: DisplayRow,
 5478        cx: &mut ViewContext<Self>,
 5479    ) -> IconButton {
 5480        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5481            .shape(ui::IconButtonShape::Square)
 5482            .icon_size(IconSize::XSmall)
 5483            .icon_color(Color::Muted)
 5484            .selected(is_active)
 5485            .on_click(cx.listener(move |editor, _e, cx| {
 5486                editor.focus(cx);
 5487                editor.toggle_code_actions(
 5488                    &ToggleCodeActions {
 5489                        deployed_from_indicator: Some(row),
 5490                    },
 5491                    cx,
 5492                );
 5493            }))
 5494    }
 5495
 5496    pub fn context_menu_visible(&self) -> bool {
 5497        self.context_menu
 5498            .read()
 5499            .as_ref()
 5500            .map_or(false, |menu| menu.visible())
 5501    }
 5502
 5503    fn render_context_menu(
 5504        &self,
 5505        cursor_position: DisplayPoint,
 5506        style: &EditorStyle,
 5507        max_height: Pixels,
 5508        cx: &mut ViewContext<Editor>,
 5509    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5510        self.context_menu.read().as_ref().map(|menu| {
 5511            menu.render(
 5512                cursor_position,
 5513                style,
 5514                max_height,
 5515                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5516                cx,
 5517            )
 5518        })
 5519    }
 5520
 5521    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5522        cx.notify();
 5523        self.completion_tasks.clear();
 5524        let context_menu = self.context_menu.write().take();
 5525        if context_menu.is_some() {
 5526            self.update_visible_inline_completion(cx);
 5527        }
 5528        context_menu
 5529    }
 5530
 5531    pub fn insert_snippet(
 5532        &mut self,
 5533        insertion_ranges: &[Range<usize>],
 5534        snippet: Snippet,
 5535        cx: &mut ViewContext<Self>,
 5536    ) -> Result<()> {
 5537        struct Tabstop<T> {
 5538            is_end_tabstop: bool,
 5539            ranges: Vec<Range<T>>,
 5540        }
 5541
 5542        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5543            let snippet_text: Arc<str> = snippet.text.clone().into();
 5544            buffer.edit(
 5545                insertion_ranges
 5546                    .iter()
 5547                    .cloned()
 5548                    .map(|range| (range, snippet_text.clone())),
 5549                Some(AutoindentMode::EachLine),
 5550                cx,
 5551            );
 5552
 5553            let snapshot = &*buffer.read(cx);
 5554            let snippet = &snippet;
 5555            snippet
 5556                .tabstops
 5557                .iter()
 5558                .map(|tabstop| {
 5559                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5560                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5561                    });
 5562                    let mut tabstop_ranges = tabstop
 5563                        .iter()
 5564                        .flat_map(|tabstop_range| {
 5565                            let mut delta = 0_isize;
 5566                            insertion_ranges.iter().map(move |insertion_range| {
 5567                                let insertion_start = insertion_range.start as isize + delta;
 5568                                delta +=
 5569                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5570
 5571                                let start = ((insertion_start + tabstop_range.start) as usize)
 5572                                    .min(snapshot.len());
 5573                                let end = ((insertion_start + tabstop_range.end) as usize)
 5574                                    .min(snapshot.len());
 5575                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5576                            })
 5577                        })
 5578                        .collect::<Vec<_>>();
 5579                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5580
 5581                    Tabstop {
 5582                        is_end_tabstop,
 5583                        ranges: tabstop_ranges,
 5584                    }
 5585                })
 5586                .collect::<Vec<_>>()
 5587        });
 5588        if let Some(tabstop) = tabstops.first() {
 5589            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5590                s.select_ranges(tabstop.ranges.iter().cloned());
 5591            });
 5592
 5593            // If we're already at the last tabstop and it's at the end of the snippet,
 5594            // we're done, we don't need to keep the state around.
 5595            if !tabstop.is_end_tabstop {
 5596                let ranges = tabstops
 5597                    .into_iter()
 5598                    .map(|tabstop| tabstop.ranges)
 5599                    .collect::<Vec<_>>();
 5600                self.snippet_stack.push(SnippetState {
 5601                    active_index: 0,
 5602                    ranges,
 5603                });
 5604            }
 5605
 5606            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5607            if self.autoclose_regions.is_empty() {
 5608                let snapshot = self.buffer.read(cx).snapshot(cx);
 5609                for selection in &mut self.selections.all::<Point>(cx) {
 5610                    let selection_head = selection.head();
 5611                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5612                        continue;
 5613                    };
 5614
 5615                    let mut bracket_pair = None;
 5616                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5617                    let prev_chars = snapshot
 5618                        .reversed_chars_at(selection_head)
 5619                        .collect::<String>();
 5620                    for (pair, enabled) in scope.brackets() {
 5621                        if enabled
 5622                            && pair.close
 5623                            && prev_chars.starts_with(pair.start.as_str())
 5624                            && next_chars.starts_with(pair.end.as_str())
 5625                        {
 5626                            bracket_pair = Some(pair.clone());
 5627                            break;
 5628                        }
 5629                    }
 5630                    if let Some(pair) = bracket_pair {
 5631                        let start = snapshot.anchor_after(selection_head);
 5632                        let end = snapshot.anchor_after(selection_head);
 5633                        self.autoclose_regions.push(AutocloseRegion {
 5634                            selection_id: selection.id,
 5635                            range: start..end,
 5636                            pair,
 5637                        });
 5638                    }
 5639                }
 5640            }
 5641        }
 5642        Ok(())
 5643    }
 5644
 5645    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5646        self.move_to_snippet_tabstop(Bias::Right, cx)
 5647    }
 5648
 5649    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5650        self.move_to_snippet_tabstop(Bias::Left, cx)
 5651    }
 5652
 5653    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5654        if let Some(mut snippet) = self.snippet_stack.pop() {
 5655            match bias {
 5656                Bias::Left => {
 5657                    if snippet.active_index > 0 {
 5658                        snippet.active_index -= 1;
 5659                    } else {
 5660                        self.snippet_stack.push(snippet);
 5661                        return false;
 5662                    }
 5663                }
 5664                Bias::Right => {
 5665                    if snippet.active_index + 1 < snippet.ranges.len() {
 5666                        snippet.active_index += 1;
 5667                    } else {
 5668                        self.snippet_stack.push(snippet);
 5669                        return false;
 5670                    }
 5671                }
 5672            }
 5673            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5674                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5675                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5676                });
 5677                // If snippet state is not at the last tabstop, push it back on the stack
 5678                if snippet.active_index + 1 < snippet.ranges.len() {
 5679                    self.snippet_stack.push(snippet);
 5680                }
 5681                return true;
 5682            }
 5683        }
 5684
 5685        false
 5686    }
 5687
 5688    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5689        self.transact(cx, |this, cx| {
 5690            this.select_all(&SelectAll, cx);
 5691            this.insert("", cx);
 5692        });
 5693    }
 5694
 5695    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5696        self.transact(cx, |this, cx| {
 5697            this.select_autoclose_pair(cx);
 5698            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5699            if !this.linked_edit_ranges.is_empty() {
 5700                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5701                let snapshot = this.buffer.read(cx).snapshot(cx);
 5702
 5703                for selection in selections.iter() {
 5704                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5705                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5706                    if selection_start.buffer_id != selection_end.buffer_id {
 5707                        continue;
 5708                    }
 5709                    if let Some(ranges) =
 5710                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5711                    {
 5712                        for (buffer, entries) in ranges {
 5713                            linked_ranges.entry(buffer).or_default().extend(entries);
 5714                        }
 5715                    }
 5716                }
 5717            }
 5718
 5719            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5720            if !this.selections.line_mode {
 5721                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5722                for selection in &mut selections {
 5723                    if selection.is_empty() {
 5724                        let old_head = selection.head();
 5725                        let mut new_head =
 5726                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5727                                .to_point(&display_map);
 5728                        if let Some((buffer, line_buffer_range)) = display_map
 5729                            .buffer_snapshot
 5730                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5731                        {
 5732                            let indent_size =
 5733                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5734                            let indent_len = match indent_size.kind {
 5735                                IndentKind::Space => {
 5736                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5737                                }
 5738                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5739                            };
 5740                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5741                                let indent_len = indent_len.get();
 5742                                new_head = cmp::min(
 5743                                    new_head,
 5744                                    MultiBufferPoint::new(
 5745                                        old_head.row,
 5746                                        ((old_head.column - 1) / indent_len) * indent_len,
 5747                                    ),
 5748                                );
 5749                            }
 5750                        }
 5751
 5752                        selection.set_head(new_head, SelectionGoal::None);
 5753                    }
 5754                }
 5755            }
 5756
 5757            this.signature_help_state.set_backspace_pressed(true);
 5758            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5759            this.insert("", cx);
 5760            let empty_str: Arc<str> = Arc::from("");
 5761            for (buffer, edits) in linked_ranges {
 5762                let snapshot = buffer.read(cx).snapshot();
 5763                use text::ToPoint as TP;
 5764
 5765                let edits = edits
 5766                    .into_iter()
 5767                    .map(|range| {
 5768                        let end_point = TP::to_point(&range.end, &snapshot);
 5769                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5770
 5771                        if end_point == start_point {
 5772                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5773                                .saturating_sub(1);
 5774                            start_point = TP::to_point(&offset, &snapshot);
 5775                        };
 5776
 5777                        (start_point..end_point, empty_str.clone())
 5778                    })
 5779                    .sorted_by_key(|(range, _)| range.start)
 5780                    .collect::<Vec<_>>();
 5781                buffer.update(cx, |this, cx| {
 5782                    this.edit(edits, None, cx);
 5783                })
 5784            }
 5785            this.refresh_inline_completion(true, false, cx);
 5786            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5787        });
 5788    }
 5789
 5790    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5791        self.transact(cx, |this, cx| {
 5792            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5793                let line_mode = s.line_mode;
 5794                s.move_with(|map, selection| {
 5795                    if selection.is_empty() && !line_mode {
 5796                        let cursor = movement::right(map, selection.head());
 5797                        selection.end = cursor;
 5798                        selection.reversed = true;
 5799                        selection.goal = SelectionGoal::None;
 5800                    }
 5801                })
 5802            });
 5803            this.insert("", cx);
 5804            this.refresh_inline_completion(true, false, cx);
 5805        });
 5806    }
 5807
 5808    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5809        if self.move_to_prev_snippet_tabstop(cx) {
 5810            return;
 5811        }
 5812
 5813        self.outdent(&Outdent, cx);
 5814    }
 5815
 5816    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5817        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5818            return;
 5819        }
 5820
 5821        let mut selections = self.selections.all_adjusted(cx);
 5822        let buffer = self.buffer.read(cx);
 5823        let snapshot = buffer.snapshot(cx);
 5824        let rows_iter = selections.iter().map(|s| s.head().row);
 5825        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5826
 5827        let mut edits = Vec::new();
 5828        let mut prev_edited_row = 0;
 5829        let mut row_delta = 0;
 5830        for selection in &mut selections {
 5831            if selection.start.row != prev_edited_row {
 5832                row_delta = 0;
 5833            }
 5834            prev_edited_row = selection.end.row;
 5835
 5836            // If the selection is non-empty, then increase the indentation of the selected lines.
 5837            if !selection.is_empty() {
 5838                row_delta =
 5839                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5840                continue;
 5841            }
 5842
 5843            // If the selection is empty and the cursor is in the leading whitespace before the
 5844            // suggested indentation, then auto-indent the line.
 5845            let cursor = selection.head();
 5846            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5847            if let Some(suggested_indent) =
 5848                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5849            {
 5850                if cursor.column < suggested_indent.len
 5851                    && cursor.column <= current_indent.len
 5852                    && current_indent.len <= suggested_indent.len
 5853                {
 5854                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5855                    selection.end = selection.start;
 5856                    if row_delta == 0 {
 5857                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5858                            cursor.row,
 5859                            current_indent,
 5860                            suggested_indent,
 5861                        ));
 5862                        row_delta = suggested_indent.len - current_indent.len;
 5863                    }
 5864                    continue;
 5865                }
 5866            }
 5867
 5868            // Otherwise, insert a hard or soft tab.
 5869            let settings = buffer.settings_at(cursor, cx);
 5870            let tab_size = if settings.hard_tabs {
 5871                IndentSize::tab()
 5872            } else {
 5873                let tab_size = settings.tab_size.get();
 5874                let char_column = snapshot
 5875                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5876                    .flat_map(str::chars)
 5877                    .count()
 5878                    + row_delta as usize;
 5879                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5880                IndentSize::spaces(chars_to_next_tab_stop)
 5881            };
 5882            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5883            selection.end = selection.start;
 5884            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5885            row_delta += tab_size.len;
 5886        }
 5887
 5888        self.transact(cx, |this, cx| {
 5889            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5890            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5891            this.refresh_inline_completion(true, false, cx);
 5892        });
 5893    }
 5894
 5895    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5896        if self.read_only(cx) {
 5897            return;
 5898        }
 5899        let mut selections = self.selections.all::<Point>(cx);
 5900        let mut prev_edited_row = 0;
 5901        let mut row_delta = 0;
 5902        let mut edits = Vec::new();
 5903        let buffer = self.buffer.read(cx);
 5904        let snapshot = buffer.snapshot(cx);
 5905        for selection in &mut selections {
 5906            if selection.start.row != prev_edited_row {
 5907                row_delta = 0;
 5908            }
 5909            prev_edited_row = selection.end.row;
 5910
 5911            row_delta =
 5912                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5913        }
 5914
 5915        self.transact(cx, |this, cx| {
 5916            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5917            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5918        });
 5919    }
 5920
 5921    fn indent_selection(
 5922        buffer: &MultiBuffer,
 5923        snapshot: &MultiBufferSnapshot,
 5924        selection: &mut Selection<Point>,
 5925        edits: &mut Vec<(Range<Point>, String)>,
 5926        delta_for_start_row: u32,
 5927        cx: &AppContext,
 5928    ) -> u32 {
 5929        let settings = buffer.settings_at(selection.start, cx);
 5930        let tab_size = settings.tab_size.get();
 5931        let indent_kind = if settings.hard_tabs {
 5932            IndentKind::Tab
 5933        } else {
 5934            IndentKind::Space
 5935        };
 5936        let mut start_row = selection.start.row;
 5937        let mut end_row = selection.end.row + 1;
 5938
 5939        // If a selection ends at the beginning of a line, don't indent
 5940        // that last line.
 5941        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5942            end_row -= 1;
 5943        }
 5944
 5945        // Avoid re-indenting a row that has already been indented by a
 5946        // previous selection, but still update this selection's column
 5947        // to reflect that indentation.
 5948        if delta_for_start_row > 0 {
 5949            start_row += 1;
 5950            selection.start.column += delta_for_start_row;
 5951            if selection.end.row == selection.start.row {
 5952                selection.end.column += delta_for_start_row;
 5953            }
 5954        }
 5955
 5956        let mut delta_for_end_row = 0;
 5957        let has_multiple_rows = start_row + 1 != end_row;
 5958        for row in start_row..end_row {
 5959            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5960            let indent_delta = match (current_indent.kind, indent_kind) {
 5961                (IndentKind::Space, IndentKind::Space) => {
 5962                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5963                    IndentSize::spaces(columns_to_next_tab_stop)
 5964                }
 5965                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5966                (_, IndentKind::Tab) => IndentSize::tab(),
 5967            };
 5968
 5969            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5970                0
 5971            } else {
 5972                selection.start.column
 5973            };
 5974            let row_start = Point::new(row, start);
 5975            edits.push((
 5976                row_start..row_start,
 5977                indent_delta.chars().collect::<String>(),
 5978            ));
 5979
 5980            // Update this selection's endpoints to reflect the indentation.
 5981            if row == selection.start.row {
 5982                selection.start.column += indent_delta.len;
 5983            }
 5984            if row == selection.end.row {
 5985                selection.end.column += indent_delta.len;
 5986                delta_for_end_row = indent_delta.len;
 5987            }
 5988        }
 5989
 5990        if selection.start.row == selection.end.row {
 5991            delta_for_start_row + delta_for_end_row
 5992        } else {
 5993            delta_for_end_row
 5994        }
 5995    }
 5996
 5997    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5998        if self.read_only(cx) {
 5999            return;
 6000        }
 6001        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6002        let selections = self.selections.all::<Point>(cx);
 6003        let mut deletion_ranges = Vec::new();
 6004        let mut last_outdent = None;
 6005        {
 6006            let buffer = self.buffer.read(cx);
 6007            let snapshot = buffer.snapshot(cx);
 6008            for selection in &selections {
 6009                let settings = buffer.settings_at(selection.start, cx);
 6010                let tab_size = settings.tab_size.get();
 6011                let mut rows = selection.spanned_rows(false, &display_map);
 6012
 6013                // Avoid re-outdenting a row that has already been outdented by a
 6014                // previous selection.
 6015                if let Some(last_row) = last_outdent {
 6016                    if last_row == rows.start {
 6017                        rows.start = rows.start.next_row();
 6018                    }
 6019                }
 6020                let has_multiple_rows = rows.len() > 1;
 6021                for row in rows.iter_rows() {
 6022                    let indent_size = snapshot.indent_size_for_line(row);
 6023                    if indent_size.len > 0 {
 6024                        let deletion_len = match indent_size.kind {
 6025                            IndentKind::Space => {
 6026                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6027                                if columns_to_prev_tab_stop == 0 {
 6028                                    tab_size
 6029                                } else {
 6030                                    columns_to_prev_tab_stop
 6031                                }
 6032                            }
 6033                            IndentKind::Tab => 1,
 6034                        };
 6035                        let start = if has_multiple_rows
 6036                            || deletion_len > selection.start.column
 6037                            || indent_size.len < selection.start.column
 6038                        {
 6039                            0
 6040                        } else {
 6041                            selection.start.column - deletion_len
 6042                        };
 6043                        deletion_ranges.push(
 6044                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6045                        );
 6046                        last_outdent = Some(row);
 6047                    }
 6048                }
 6049            }
 6050        }
 6051
 6052        self.transact(cx, |this, cx| {
 6053            this.buffer.update(cx, |buffer, cx| {
 6054                let empty_str: Arc<str> = Arc::default();
 6055                buffer.edit(
 6056                    deletion_ranges
 6057                        .into_iter()
 6058                        .map(|range| (range, empty_str.clone())),
 6059                    None,
 6060                    cx,
 6061                );
 6062            });
 6063            let selections = this.selections.all::<usize>(cx);
 6064            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6065        });
 6066    }
 6067
 6068    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6069        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6070        let selections = self.selections.all::<Point>(cx);
 6071
 6072        let mut new_cursors = Vec::new();
 6073        let mut edit_ranges = Vec::new();
 6074        let mut selections = selections.iter().peekable();
 6075        while let Some(selection) = selections.next() {
 6076            let mut rows = selection.spanned_rows(false, &display_map);
 6077            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6078
 6079            // Accumulate contiguous regions of rows that we want to delete.
 6080            while let Some(next_selection) = selections.peek() {
 6081                let next_rows = next_selection.spanned_rows(false, &display_map);
 6082                if next_rows.start <= rows.end {
 6083                    rows.end = next_rows.end;
 6084                    selections.next().unwrap();
 6085                } else {
 6086                    break;
 6087                }
 6088            }
 6089
 6090            let buffer = &display_map.buffer_snapshot;
 6091            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6092            let edit_end;
 6093            let cursor_buffer_row;
 6094            if buffer.max_point().row >= rows.end.0 {
 6095                // If there's a line after the range, delete the \n from the end of the row range
 6096                // and position the cursor on the next line.
 6097                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6098                cursor_buffer_row = rows.end;
 6099            } else {
 6100                // If there isn't a line after the range, delete the \n from the line before the
 6101                // start of the row range and position the cursor there.
 6102                edit_start = edit_start.saturating_sub(1);
 6103                edit_end = buffer.len();
 6104                cursor_buffer_row = rows.start.previous_row();
 6105            }
 6106
 6107            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6108            *cursor.column_mut() =
 6109                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6110
 6111            new_cursors.push((
 6112                selection.id,
 6113                buffer.anchor_after(cursor.to_point(&display_map)),
 6114            ));
 6115            edit_ranges.push(edit_start..edit_end);
 6116        }
 6117
 6118        self.transact(cx, |this, cx| {
 6119            let buffer = this.buffer.update(cx, |buffer, cx| {
 6120                let empty_str: Arc<str> = Arc::default();
 6121                buffer.edit(
 6122                    edit_ranges
 6123                        .into_iter()
 6124                        .map(|range| (range, empty_str.clone())),
 6125                    None,
 6126                    cx,
 6127                );
 6128                buffer.snapshot(cx)
 6129            });
 6130            let new_selections = new_cursors
 6131                .into_iter()
 6132                .map(|(id, cursor)| {
 6133                    let cursor = cursor.to_point(&buffer);
 6134                    Selection {
 6135                        id,
 6136                        start: cursor,
 6137                        end: cursor,
 6138                        reversed: false,
 6139                        goal: SelectionGoal::None,
 6140                    }
 6141                })
 6142                .collect();
 6143
 6144            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6145                s.select(new_selections);
 6146            });
 6147        });
 6148    }
 6149
 6150    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6151        if self.read_only(cx) {
 6152            return;
 6153        }
 6154        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6155        for selection in self.selections.all::<Point>(cx) {
 6156            let start = MultiBufferRow(selection.start.row);
 6157            let end = if selection.start.row == selection.end.row {
 6158                MultiBufferRow(selection.start.row + 1)
 6159            } else {
 6160                MultiBufferRow(selection.end.row)
 6161            };
 6162
 6163            if let Some(last_row_range) = row_ranges.last_mut() {
 6164                if start <= last_row_range.end {
 6165                    last_row_range.end = end;
 6166                    continue;
 6167                }
 6168            }
 6169            row_ranges.push(start..end);
 6170        }
 6171
 6172        let snapshot = self.buffer.read(cx).snapshot(cx);
 6173        let mut cursor_positions = Vec::new();
 6174        for row_range in &row_ranges {
 6175            let anchor = snapshot.anchor_before(Point::new(
 6176                row_range.end.previous_row().0,
 6177                snapshot.line_len(row_range.end.previous_row()),
 6178            ));
 6179            cursor_positions.push(anchor..anchor);
 6180        }
 6181
 6182        self.transact(cx, |this, cx| {
 6183            for row_range in row_ranges.into_iter().rev() {
 6184                for row in row_range.iter_rows().rev() {
 6185                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6186                    let next_line_row = row.next_row();
 6187                    let indent = snapshot.indent_size_for_line(next_line_row);
 6188                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6189
 6190                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6191                        " "
 6192                    } else {
 6193                        ""
 6194                    };
 6195
 6196                    this.buffer.update(cx, |buffer, cx| {
 6197                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6198                    });
 6199                }
 6200            }
 6201
 6202            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6203                s.select_anchor_ranges(cursor_positions)
 6204            });
 6205        });
 6206    }
 6207
 6208    pub fn sort_lines_case_sensitive(
 6209        &mut self,
 6210        _: &SortLinesCaseSensitive,
 6211        cx: &mut ViewContext<Self>,
 6212    ) {
 6213        self.manipulate_lines(cx, |lines| lines.sort())
 6214    }
 6215
 6216    pub fn sort_lines_case_insensitive(
 6217        &mut self,
 6218        _: &SortLinesCaseInsensitive,
 6219        cx: &mut ViewContext<Self>,
 6220    ) {
 6221        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6222    }
 6223
 6224    pub fn unique_lines_case_insensitive(
 6225        &mut self,
 6226        _: &UniqueLinesCaseInsensitive,
 6227        cx: &mut ViewContext<Self>,
 6228    ) {
 6229        self.manipulate_lines(cx, |lines| {
 6230            let mut seen = HashSet::default();
 6231            lines.retain(|line| seen.insert(line.to_lowercase()));
 6232        })
 6233    }
 6234
 6235    pub fn unique_lines_case_sensitive(
 6236        &mut self,
 6237        _: &UniqueLinesCaseSensitive,
 6238        cx: &mut ViewContext<Self>,
 6239    ) {
 6240        self.manipulate_lines(cx, |lines| {
 6241            let mut seen = HashSet::default();
 6242            lines.retain(|line| seen.insert(*line));
 6243        })
 6244    }
 6245
 6246    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6247        let mut revert_changes = HashMap::default();
 6248        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6249        for hunk in hunks_for_rows(
 6250            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6251            &multi_buffer_snapshot,
 6252        ) {
 6253            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6254        }
 6255        if !revert_changes.is_empty() {
 6256            self.transact(cx, |editor, cx| {
 6257                editor.revert(revert_changes, cx);
 6258            });
 6259        }
 6260    }
 6261
 6262    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6263        let Some(project) = self.project.clone() else {
 6264            return;
 6265        };
 6266        self.reload(project, cx).detach_and_notify_err(cx);
 6267    }
 6268
 6269    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6270        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6271        if !revert_changes.is_empty() {
 6272            self.transact(cx, |editor, cx| {
 6273                editor.revert(revert_changes, cx);
 6274            });
 6275        }
 6276    }
 6277
 6278    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6279        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6280            let project_path = buffer.read(cx).project_path(cx)?;
 6281            let project = self.project.as_ref()?.read(cx);
 6282            let entry = project.entry_for_path(&project_path, cx)?;
 6283            let parent = match &entry.canonical_path {
 6284                Some(canonical_path) => canonical_path.to_path_buf(),
 6285                None => project.absolute_path(&project_path, cx)?,
 6286            }
 6287            .parent()?
 6288            .to_path_buf();
 6289            Some(parent)
 6290        }) {
 6291            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6292        }
 6293    }
 6294
 6295    fn gather_revert_changes(
 6296        &mut self,
 6297        selections: &[Selection<Anchor>],
 6298        cx: &mut ViewContext<'_, Editor>,
 6299    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6300        let mut revert_changes = HashMap::default();
 6301        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6302        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6303            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6304        }
 6305        revert_changes
 6306    }
 6307
 6308    pub fn prepare_revert_change(
 6309        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6310        multi_buffer: &Model<MultiBuffer>,
 6311        hunk: &MultiBufferDiffHunk,
 6312        cx: &AppContext,
 6313    ) -> Option<()> {
 6314        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6315        let buffer = buffer.read(cx);
 6316        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6317        let buffer_snapshot = buffer.snapshot();
 6318        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6319        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6320            probe
 6321                .0
 6322                .start
 6323                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6324                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6325        }) {
 6326            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6327            Some(())
 6328        } else {
 6329            None
 6330        }
 6331    }
 6332
 6333    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6334        self.manipulate_lines(cx, |lines| lines.reverse())
 6335    }
 6336
 6337    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6338        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6339    }
 6340
 6341    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6342    where
 6343        Fn: FnMut(&mut Vec<&str>),
 6344    {
 6345        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6346        let buffer = self.buffer.read(cx).snapshot(cx);
 6347
 6348        let mut edits = Vec::new();
 6349
 6350        let selections = self.selections.all::<Point>(cx);
 6351        let mut selections = selections.iter().peekable();
 6352        let mut contiguous_row_selections = Vec::new();
 6353        let mut new_selections = Vec::new();
 6354        let mut added_lines = 0;
 6355        let mut removed_lines = 0;
 6356
 6357        while let Some(selection) = selections.next() {
 6358            let (start_row, end_row) = consume_contiguous_rows(
 6359                &mut contiguous_row_selections,
 6360                selection,
 6361                &display_map,
 6362                &mut selections,
 6363            );
 6364
 6365            let start_point = Point::new(start_row.0, 0);
 6366            let end_point = Point::new(
 6367                end_row.previous_row().0,
 6368                buffer.line_len(end_row.previous_row()),
 6369            );
 6370            let text = buffer
 6371                .text_for_range(start_point..end_point)
 6372                .collect::<String>();
 6373
 6374            let mut lines = text.split('\n').collect_vec();
 6375
 6376            let lines_before = lines.len();
 6377            callback(&mut lines);
 6378            let lines_after = lines.len();
 6379
 6380            edits.push((start_point..end_point, lines.join("\n")));
 6381
 6382            // Selections must change based on added and removed line count
 6383            let start_row =
 6384                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6385            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6386            new_selections.push(Selection {
 6387                id: selection.id,
 6388                start: start_row,
 6389                end: end_row,
 6390                goal: SelectionGoal::None,
 6391                reversed: selection.reversed,
 6392            });
 6393
 6394            if lines_after > lines_before {
 6395                added_lines += lines_after - lines_before;
 6396            } else if lines_before > lines_after {
 6397                removed_lines += lines_before - lines_after;
 6398            }
 6399        }
 6400
 6401        self.transact(cx, |this, cx| {
 6402            let buffer = this.buffer.update(cx, |buffer, cx| {
 6403                buffer.edit(edits, None, cx);
 6404                buffer.snapshot(cx)
 6405            });
 6406
 6407            // Recalculate offsets on newly edited buffer
 6408            let new_selections = new_selections
 6409                .iter()
 6410                .map(|s| {
 6411                    let start_point = Point::new(s.start.0, 0);
 6412                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6413                    Selection {
 6414                        id: s.id,
 6415                        start: buffer.point_to_offset(start_point),
 6416                        end: buffer.point_to_offset(end_point),
 6417                        goal: s.goal,
 6418                        reversed: s.reversed,
 6419                    }
 6420                })
 6421                .collect();
 6422
 6423            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6424                s.select(new_selections);
 6425            });
 6426
 6427            this.request_autoscroll(Autoscroll::fit(), cx);
 6428        });
 6429    }
 6430
 6431    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6432        self.manipulate_text(cx, |text| text.to_uppercase())
 6433    }
 6434
 6435    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6436        self.manipulate_text(cx, |text| text.to_lowercase())
 6437    }
 6438
 6439    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6440        self.manipulate_text(cx, |text| {
 6441            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6442            // https://github.com/rutrum/convert-case/issues/16
 6443            text.split('\n')
 6444                .map(|line| line.to_case(Case::Title))
 6445                .join("\n")
 6446        })
 6447    }
 6448
 6449    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6450        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6451    }
 6452
 6453    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6454        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6455    }
 6456
 6457    pub fn convert_to_upper_camel_case(
 6458        &mut self,
 6459        _: &ConvertToUpperCamelCase,
 6460        cx: &mut ViewContext<Self>,
 6461    ) {
 6462        self.manipulate_text(cx, |text| {
 6463            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6464            // https://github.com/rutrum/convert-case/issues/16
 6465            text.split('\n')
 6466                .map(|line| line.to_case(Case::UpperCamel))
 6467                .join("\n")
 6468        })
 6469    }
 6470
 6471    pub fn convert_to_lower_camel_case(
 6472        &mut self,
 6473        _: &ConvertToLowerCamelCase,
 6474        cx: &mut ViewContext<Self>,
 6475    ) {
 6476        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6477    }
 6478
 6479    pub fn convert_to_opposite_case(
 6480        &mut self,
 6481        _: &ConvertToOppositeCase,
 6482        cx: &mut ViewContext<Self>,
 6483    ) {
 6484        self.manipulate_text(cx, |text| {
 6485            text.chars()
 6486                .fold(String::with_capacity(text.len()), |mut t, c| {
 6487                    if c.is_uppercase() {
 6488                        t.extend(c.to_lowercase());
 6489                    } else {
 6490                        t.extend(c.to_uppercase());
 6491                    }
 6492                    t
 6493                })
 6494        })
 6495    }
 6496
 6497    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6498    where
 6499        Fn: FnMut(&str) -> String,
 6500    {
 6501        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6502        let buffer = self.buffer.read(cx).snapshot(cx);
 6503
 6504        let mut new_selections = Vec::new();
 6505        let mut edits = Vec::new();
 6506        let mut selection_adjustment = 0i32;
 6507
 6508        for selection in self.selections.all::<usize>(cx) {
 6509            let selection_is_empty = selection.is_empty();
 6510
 6511            let (start, end) = if selection_is_empty {
 6512                let word_range = movement::surrounding_word(
 6513                    &display_map,
 6514                    selection.start.to_display_point(&display_map),
 6515                );
 6516                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6517                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6518                (start, end)
 6519            } else {
 6520                (selection.start, selection.end)
 6521            };
 6522
 6523            let text = buffer.text_for_range(start..end).collect::<String>();
 6524            let old_length = text.len() as i32;
 6525            let text = callback(&text);
 6526
 6527            new_selections.push(Selection {
 6528                start: (start as i32 - selection_adjustment) as usize,
 6529                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6530                goal: SelectionGoal::None,
 6531                ..selection
 6532            });
 6533
 6534            selection_adjustment += old_length - text.len() as i32;
 6535
 6536            edits.push((start..end, text));
 6537        }
 6538
 6539        self.transact(cx, |this, cx| {
 6540            this.buffer.update(cx, |buffer, cx| {
 6541                buffer.edit(edits, None, cx);
 6542            });
 6543
 6544            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6545                s.select(new_selections);
 6546            });
 6547
 6548            this.request_autoscroll(Autoscroll::fit(), cx);
 6549        });
 6550    }
 6551
 6552    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6553        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6554        let buffer = &display_map.buffer_snapshot;
 6555        let selections = self.selections.all::<Point>(cx);
 6556
 6557        let mut edits = Vec::new();
 6558        let mut selections_iter = selections.iter().peekable();
 6559        while let Some(selection) = selections_iter.next() {
 6560            // Avoid duplicating the same lines twice.
 6561            let mut rows = selection.spanned_rows(false, &display_map);
 6562
 6563            while let Some(next_selection) = selections_iter.peek() {
 6564                let next_rows = next_selection.spanned_rows(false, &display_map);
 6565                if next_rows.start < rows.end {
 6566                    rows.end = next_rows.end;
 6567                    selections_iter.next().unwrap();
 6568                } else {
 6569                    break;
 6570                }
 6571            }
 6572
 6573            // Copy the text from the selected row region and splice it either at the start
 6574            // or end of the region.
 6575            let start = Point::new(rows.start.0, 0);
 6576            let end = Point::new(
 6577                rows.end.previous_row().0,
 6578                buffer.line_len(rows.end.previous_row()),
 6579            );
 6580            let text = buffer
 6581                .text_for_range(start..end)
 6582                .chain(Some("\n"))
 6583                .collect::<String>();
 6584            let insert_location = if upwards {
 6585                Point::new(rows.end.0, 0)
 6586            } else {
 6587                start
 6588            };
 6589            edits.push((insert_location..insert_location, text));
 6590        }
 6591
 6592        self.transact(cx, |this, cx| {
 6593            this.buffer.update(cx, |buffer, cx| {
 6594                buffer.edit(edits, None, cx);
 6595            });
 6596
 6597            this.request_autoscroll(Autoscroll::fit(), cx);
 6598        });
 6599    }
 6600
 6601    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6602        self.duplicate_line(true, cx);
 6603    }
 6604
 6605    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6606        self.duplicate_line(false, cx);
 6607    }
 6608
 6609    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6610        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6611        let buffer = self.buffer.read(cx).snapshot(cx);
 6612
 6613        let mut edits = Vec::new();
 6614        let mut unfold_ranges = Vec::new();
 6615        let mut refold_ranges = Vec::new();
 6616
 6617        let selections = self.selections.all::<Point>(cx);
 6618        let mut selections = selections.iter().peekable();
 6619        let mut contiguous_row_selections = Vec::new();
 6620        let mut new_selections = Vec::new();
 6621
 6622        while let Some(selection) = selections.next() {
 6623            // Find all the selections that span a contiguous row range
 6624            let (start_row, end_row) = consume_contiguous_rows(
 6625                &mut contiguous_row_selections,
 6626                selection,
 6627                &display_map,
 6628                &mut selections,
 6629            );
 6630
 6631            // Move the text spanned by the row range to be before the line preceding the row range
 6632            if start_row.0 > 0 {
 6633                let range_to_move = Point::new(
 6634                    start_row.previous_row().0,
 6635                    buffer.line_len(start_row.previous_row()),
 6636                )
 6637                    ..Point::new(
 6638                        end_row.previous_row().0,
 6639                        buffer.line_len(end_row.previous_row()),
 6640                    );
 6641                let insertion_point = display_map
 6642                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6643                    .0;
 6644
 6645                // Don't move lines across excerpts
 6646                if buffer
 6647                    .excerpt_boundaries_in_range((
 6648                        Bound::Excluded(insertion_point),
 6649                        Bound::Included(range_to_move.end),
 6650                    ))
 6651                    .next()
 6652                    .is_none()
 6653                {
 6654                    let text = buffer
 6655                        .text_for_range(range_to_move.clone())
 6656                        .flat_map(|s| s.chars())
 6657                        .skip(1)
 6658                        .chain(['\n'])
 6659                        .collect::<String>();
 6660
 6661                    edits.push((
 6662                        buffer.anchor_after(range_to_move.start)
 6663                            ..buffer.anchor_before(range_to_move.end),
 6664                        String::new(),
 6665                    ));
 6666                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6667                    edits.push((insertion_anchor..insertion_anchor, text));
 6668
 6669                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6670
 6671                    // Move selections up
 6672                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6673                        |mut selection| {
 6674                            selection.start.row -= row_delta;
 6675                            selection.end.row -= row_delta;
 6676                            selection
 6677                        },
 6678                    ));
 6679
 6680                    // Move folds up
 6681                    unfold_ranges.push(range_to_move.clone());
 6682                    for fold in display_map.folds_in_range(
 6683                        buffer.anchor_before(range_to_move.start)
 6684                            ..buffer.anchor_after(range_to_move.end),
 6685                    ) {
 6686                        let mut start = fold.range.start.to_point(&buffer);
 6687                        let mut end = fold.range.end.to_point(&buffer);
 6688                        start.row -= row_delta;
 6689                        end.row -= row_delta;
 6690                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6691                    }
 6692                }
 6693            }
 6694
 6695            // If we didn't move line(s), preserve the existing selections
 6696            new_selections.append(&mut contiguous_row_selections);
 6697        }
 6698
 6699        self.transact(cx, |this, cx| {
 6700            this.unfold_ranges(unfold_ranges, true, true, cx);
 6701            this.buffer.update(cx, |buffer, cx| {
 6702                for (range, text) in edits {
 6703                    buffer.edit([(range, text)], None, cx);
 6704                }
 6705            });
 6706            this.fold_ranges(refold_ranges, true, cx);
 6707            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6708                s.select(new_selections);
 6709            })
 6710        });
 6711    }
 6712
 6713    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6714        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6715        let buffer = self.buffer.read(cx).snapshot(cx);
 6716
 6717        let mut edits = Vec::new();
 6718        let mut unfold_ranges = Vec::new();
 6719        let mut refold_ranges = Vec::new();
 6720
 6721        let selections = self.selections.all::<Point>(cx);
 6722        let mut selections = selections.iter().peekable();
 6723        let mut contiguous_row_selections = Vec::new();
 6724        let mut new_selections = Vec::new();
 6725
 6726        while let Some(selection) = selections.next() {
 6727            // Find all the selections that span a contiguous row range
 6728            let (start_row, end_row) = consume_contiguous_rows(
 6729                &mut contiguous_row_selections,
 6730                selection,
 6731                &display_map,
 6732                &mut selections,
 6733            );
 6734
 6735            // Move the text spanned by the row range to be after the last line of the row range
 6736            if end_row.0 <= buffer.max_point().row {
 6737                let range_to_move =
 6738                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6739                let insertion_point = display_map
 6740                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6741                    .0;
 6742
 6743                // Don't move lines across excerpt boundaries
 6744                if buffer
 6745                    .excerpt_boundaries_in_range((
 6746                        Bound::Excluded(range_to_move.start),
 6747                        Bound::Included(insertion_point),
 6748                    ))
 6749                    .next()
 6750                    .is_none()
 6751                {
 6752                    let mut text = String::from("\n");
 6753                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6754                    text.pop(); // Drop trailing newline
 6755                    edits.push((
 6756                        buffer.anchor_after(range_to_move.start)
 6757                            ..buffer.anchor_before(range_to_move.end),
 6758                        String::new(),
 6759                    ));
 6760                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6761                    edits.push((insertion_anchor..insertion_anchor, text));
 6762
 6763                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6764
 6765                    // Move selections down
 6766                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6767                        |mut selection| {
 6768                            selection.start.row += row_delta;
 6769                            selection.end.row += row_delta;
 6770                            selection
 6771                        },
 6772                    ));
 6773
 6774                    // Move folds down
 6775                    unfold_ranges.push(range_to_move.clone());
 6776                    for fold in display_map.folds_in_range(
 6777                        buffer.anchor_before(range_to_move.start)
 6778                            ..buffer.anchor_after(range_to_move.end),
 6779                    ) {
 6780                        let mut start = fold.range.start.to_point(&buffer);
 6781                        let mut end = fold.range.end.to_point(&buffer);
 6782                        start.row += row_delta;
 6783                        end.row += row_delta;
 6784                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6785                    }
 6786                }
 6787            }
 6788
 6789            // If we didn't move line(s), preserve the existing selections
 6790            new_selections.append(&mut contiguous_row_selections);
 6791        }
 6792
 6793        self.transact(cx, |this, cx| {
 6794            this.unfold_ranges(unfold_ranges, true, true, cx);
 6795            this.buffer.update(cx, |buffer, cx| {
 6796                for (range, text) in edits {
 6797                    buffer.edit([(range, text)], None, cx);
 6798                }
 6799            });
 6800            this.fold_ranges(refold_ranges, true, cx);
 6801            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6802        });
 6803    }
 6804
 6805    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6806        let text_layout_details = &self.text_layout_details(cx);
 6807        self.transact(cx, |this, cx| {
 6808            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6809                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6810                let line_mode = s.line_mode;
 6811                s.move_with(|display_map, selection| {
 6812                    if !selection.is_empty() || line_mode {
 6813                        return;
 6814                    }
 6815
 6816                    let mut head = selection.head();
 6817                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6818                    if head.column() == display_map.line_len(head.row()) {
 6819                        transpose_offset = display_map
 6820                            .buffer_snapshot
 6821                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6822                    }
 6823
 6824                    if transpose_offset == 0 {
 6825                        return;
 6826                    }
 6827
 6828                    *head.column_mut() += 1;
 6829                    head = display_map.clip_point(head, Bias::Right);
 6830                    let goal = SelectionGoal::HorizontalPosition(
 6831                        display_map
 6832                            .x_for_display_point(head, text_layout_details)
 6833                            .into(),
 6834                    );
 6835                    selection.collapse_to(head, goal);
 6836
 6837                    let transpose_start = display_map
 6838                        .buffer_snapshot
 6839                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6840                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6841                        let transpose_end = display_map
 6842                            .buffer_snapshot
 6843                            .clip_offset(transpose_offset + 1, Bias::Right);
 6844                        if let Some(ch) =
 6845                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6846                        {
 6847                            edits.push((transpose_start..transpose_offset, String::new()));
 6848                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6849                        }
 6850                    }
 6851                });
 6852                edits
 6853            });
 6854            this.buffer
 6855                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6856            let selections = this.selections.all::<usize>(cx);
 6857            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6858                s.select(selections);
 6859            });
 6860        });
 6861    }
 6862
 6863    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6864        self.rewrap_impl(true, cx)
 6865    }
 6866
 6867    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6868        let buffer = self.buffer.read(cx).snapshot(cx);
 6869        let selections = self.selections.all::<Point>(cx);
 6870        let mut selections = selections.iter().peekable();
 6871
 6872        let mut edits = Vec::new();
 6873        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6874
 6875        while let Some(selection) = selections.next() {
 6876            let mut start_row = selection.start.row;
 6877            let mut end_row = selection.end.row;
 6878
 6879            // Skip selections that overlap with a range that has already been rewrapped.
 6880            let selection_range = start_row..end_row;
 6881            if rewrapped_row_ranges
 6882                .iter()
 6883                .any(|range| range.overlaps(&selection_range))
 6884            {
 6885                continue;
 6886            }
 6887
 6888            let mut should_rewrap = !only_text;
 6889
 6890            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6891                match language_scope.language_name().0.as_ref() {
 6892                    "Markdown" | "Plain Text" => {
 6893                        should_rewrap = true;
 6894                    }
 6895                    _ => {}
 6896                }
 6897            }
 6898
 6899            // Since not all lines in the selection may be at the same indent
 6900            // level, choose the indent size that is the most common between all
 6901            // of the lines.
 6902            //
 6903            // If there is a tie, we use the deepest indent.
 6904            let (indent_size, indent_end) = {
 6905                let mut indent_size_occurrences = HashMap::default();
 6906                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6907
 6908                for row in start_row..=end_row {
 6909                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6910                    rows_by_indent_size.entry(indent).or_default().push(row);
 6911                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6912                }
 6913
 6914                let indent_size = indent_size_occurrences
 6915                    .into_iter()
 6916                    .max_by_key(|(indent, count)| (*count, indent.len))
 6917                    .map(|(indent, _)| indent)
 6918                    .unwrap_or_default();
 6919                let row = rows_by_indent_size[&indent_size][0];
 6920                let indent_end = Point::new(row, indent_size.len);
 6921
 6922                (indent_size, indent_end)
 6923            };
 6924
 6925            let mut line_prefix = indent_size.chars().collect::<String>();
 6926
 6927            if let Some(comment_prefix) =
 6928                buffer
 6929                    .language_scope_at(selection.head())
 6930                    .and_then(|language| {
 6931                        language
 6932                            .line_comment_prefixes()
 6933                            .iter()
 6934                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6935                            .cloned()
 6936                    })
 6937            {
 6938                line_prefix.push_str(&comment_prefix);
 6939                should_rewrap = true;
 6940            }
 6941
 6942            if selection.is_empty() {
 6943                'expand_upwards: while start_row > 0 {
 6944                    let prev_row = start_row - 1;
 6945                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6946                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6947                    {
 6948                        start_row = prev_row;
 6949                    } else {
 6950                        break 'expand_upwards;
 6951                    }
 6952                }
 6953
 6954                'expand_downwards: while end_row < buffer.max_point().row {
 6955                    let next_row = end_row + 1;
 6956                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6957                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6958                    {
 6959                        end_row = next_row;
 6960                    } else {
 6961                        break 'expand_downwards;
 6962                    }
 6963                }
 6964            }
 6965
 6966            if !should_rewrap {
 6967                continue;
 6968            }
 6969
 6970            let start = Point::new(start_row, 0);
 6971            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6972            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6973            let Some(lines_without_prefixes) = selection_text
 6974                .lines()
 6975                .map(|line| {
 6976                    line.strip_prefix(&line_prefix)
 6977                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6978                        .ok_or_else(|| {
 6979                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6980                        })
 6981                })
 6982                .collect::<Result<Vec<_>, _>>()
 6983                .log_err()
 6984            else {
 6985                continue;
 6986            };
 6987
 6988            let unwrapped_text = lines_without_prefixes.join(" ");
 6989            let wrap_column = buffer
 6990                .settings_at(Point::new(start_row, 0), cx)
 6991                .preferred_line_length as usize;
 6992            let mut wrapped_text = String::new();
 6993            let mut current_line = line_prefix.clone();
 6994            for word in unwrapped_text.split_whitespace() {
 6995                if current_line.len() + word.len() >= wrap_column {
 6996                    wrapped_text.push_str(&current_line);
 6997                    wrapped_text.push('\n');
 6998                    current_line.truncate(line_prefix.len());
 6999                }
 7000
 7001                if current_line.len() > line_prefix.len() {
 7002                    current_line.push(' ');
 7003                }
 7004
 7005                current_line.push_str(word);
 7006            }
 7007
 7008            if !current_line.is_empty() {
 7009                wrapped_text.push_str(&current_line);
 7010            }
 7011
 7012            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7013            let mut offset = start.to_offset(&buffer);
 7014            let mut moved_since_edit = true;
 7015
 7016            for change in diff.iter_all_changes() {
 7017                let value = change.value();
 7018                match change.tag() {
 7019                    ChangeTag::Equal => {
 7020                        offset += value.len();
 7021                        moved_since_edit = true;
 7022                    }
 7023                    ChangeTag::Delete => {
 7024                        let start = buffer.anchor_after(offset);
 7025                        let end = buffer.anchor_before(offset + value.len());
 7026
 7027                        if moved_since_edit {
 7028                            edits.push((start..end, String::new()));
 7029                        } else {
 7030                            edits.last_mut().unwrap().0.end = end;
 7031                        }
 7032
 7033                        offset += value.len();
 7034                        moved_since_edit = false;
 7035                    }
 7036                    ChangeTag::Insert => {
 7037                        if moved_since_edit {
 7038                            let anchor = buffer.anchor_after(offset);
 7039                            edits.push((anchor..anchor, value.to_string()));
 7040                        } else {
 7041                            edits.last_mut().unwrap().1.push_str(value);
 7042                        }
 7043
 7044                        moved_since_edit = false;
 7045                    }
 7046                }
 7047            }
 7048
 7049            rewrapped_row_ranges.push(start_row..=end_row);
 7050        }
 7051
 7052        self.buffer
 7053            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7054    }
 7055
 7056    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7057        let mut text = String::new();
 7058        let buffer = self.buffer.read(cx).snapshot(cx);
 7059        let mut selections = self.selections.all::<Point>(cx);
 7060        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7061        {
 7062            let max_point = buffer.max_point();
 7063            let mut is_first = true;
 7064            for selection in &mut selections {
 7065                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7066                if is_entire_line {
 7067                    selection.start = Point::new(selection.start.row, 0);
 7068                    if !selection.is_empty() && selection.end.column == 0 {
 7069                        selection.end = cmp::min(max_point, selection.end);
 7070                    } else {
 7071                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7072                    }
 7073                    selection.goal = SelectionGoal::None;
 7074                }
 7075                if is_first {
 7076                    is_first = false;
 7077                } else {
 7078                    text += "\n";
 7079                }
 7080                let mut len = 0;
 7081                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7082                    text.push_str(chunk);
 7083                    len += chunk.len();
 7084                }
 7085                clipboard_selections.push(ClipboardSelection {
 7086                    len,
 7087                    is_entire_line,
 7088                    first_line_indent: buffer
 7089                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7090                        .len,
 7091                });
 7092            }
 7093        }
 7094
 7095        self.transact(cx, |this, cx| {
 7096            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7097                s.select(selections);
 7098            });
 7099            this.insert("", cx);
 7100            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7101                text,
 7102                clipboard_selections,
 7103            ));
 7104        });
 7105    }
 7106
 7107    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7108        let selections = self.selections.all::<Point>(cx);
 7109        let buffer = self.buffer.read(cx).read(cx);
 7110        let mut text = String::new();
 7111
 7112        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7113        {
 7114            let max_point = buffer.max_point();
 7115            let mut is_first = true;
 7116            for selection in selections.iter() {
 7117                let mut start = selection.start;
 7118                let mut end = selection.end;
 7119                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7120                if is_entire_line {
 7121                    start = Point::new(start.row, 0);
 7122                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7123                }
 7124                if is_first {
 7125                    is_first = false;
 7126                } else {
 7127                    text += "\n";
 7128                }
 7129                let mut len = 0;
 7130                for chunk in buffer.text_for_range(start..end) {
 7131                    text.push_str(chunk);
 7132                    len += chunk.len();
 7133                }
 7134                clipboard_selections.push(ClipboardSelection {
 7135                    len,
 7136                    is_entire_line,
 7137                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7138                });
 7139            }
 7140        }
 7141
 7142        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7143            text,
 7144            clipboard_selections,
 7145        ));
 7146    }
 7147
 7148    pub fn do_paste(
 7149        &mut self,
 7150        text: &String,
 7151        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7152        handle_entire_lines: bool,
 7153        cx: &mut ViewContext<Self>,
 7154    ) {
 7155        if self.read_only(cx) {
 7156            return;
 7157        }
 7158
 7159        let clipboard_text = Cow::Borrowed(text);
 7160
 7161        self.transact(cx, |this, cx| {
 7162            if let Some(mut clipboard_selections) = clipboard_selections {
 7163                let old_selections = this.selections.all::<usize>(cx);
 7164                let all_selections_were_entire_line =
 7165                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7166                let first_selection_indent_column =
 7167                    clipboard_selections.first().map(|s| s.first_line_indent);
 7168                if clipboard_selections.len() != old_selections.len() {
 7169                    clipboard_selections.drain(..);
 7170                }
 7171
 7172                this.buffer.update(cx, |buffer, cx| {
 7173                    let snapshot = buffer.read(cx);
 7174                    let mut start_offset = 0;
 7175                    let mut edits = Vec::new();
 7176                    let mut original_indent_columns = Vec::new();
 7177                    for (ix, selection) in old_selections.iter().enumerate() {
 7178                        let to_insert;
 7179                        let entire_line;
 7180                        let original_indent_column;
 7181                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7182                            let end_offset = start_offset + clipboard_selection.len;
 7183                            to_insert = &clipboard_text[start_offset..end_offset];
 7184                            entire_line = clipboard_selection.is_entire_line;
 7185                            start_offset = end_offset + 1;
 7186                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7187                        } else {
 7188                            to_insert = clipboard_text.as_str();
 7189                            entire_line = all_selections_were_entire_line;
 7190                            original_indent_column = first_selection_indent_column
 7191                        }
 7192
 7193                        // If the corresponding selection was empty when this slice of the
 7194                        // clipboard text was written, then the entire line containing the
 7195                        // selection was copied. If this selection is also currently empty,
 7196                        // then paste the line before the current line of the buffer.
 7197                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7198                            let column = selection.start.to_point(&snapshot).column as usize;
 7199                            let line_start = selection.start - column;
 7200                            line_start..line_start
 7201                        } else {
 7202                            selection.range()
 7203                        };
 7204
 7205                        edits.push((range, to_insert));
 7206                        original_indent_columns.extend(original_indent_column);
 7207                    }
 7208                    drop(snapshot);
 7209
 7210                    buffer.edit(
 7211                        edits,
 7212                        Some(AutoindentMode::Block {
 7213                            original_indent_columns,
 7214                        }),
 7215                        cx,
 7216                    );
 7217                });
 7218
 7219                let selections = this.selections.all::<usize>(cx);
 7220                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7221            } else {
 7222                this.insert(&clipboard_text, cx);
 7223            }
 7224        });
 7225    }
 7226
 7227    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7228        if let Some(item) = cx.read_from_clipboard() {
 7229            let entries = item.entries();
 7230
 7231            match entries.first() {
 7232                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7233                // of all the pasted entries.
 7234                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7235                    .do_paste(
 7236                        clipboard_string.text(),
 7237                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7238                        true,
 7239                        cx,
 7240                    ),
 7241                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7242            }
 7243        }
 7244    }
 7245
 7246    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7247        if self.read_only(cx) {
 7248            return;
 7249        }
 7250
 7251        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7252            if let Some((selections, _)) =
 7253                self.selection_history.transaction(transaction_id).cloned()
 7254            {
 7255                self.change_selections(None, cx, |s| {
 7256                    s.select_anchors(selections.to_vec());
 7257                });
 7258            }
 7259            self.request_autoscroll(Autoscroll::fit(), cx);
 7260            self.unmark_text(cx);
 7261            self.refresh_inline_completion(true, false, cx);
 7262            cx.emit(EditorEvent::Edited { transaction_id });
 7263            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7264        }
 7265    }
 7266
 7267    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7268        if self.read_only(cx) {
 7269            return;
 7270        }
 7271
 7272        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7273            if let Some((_, Some(selections))) =
 7274                self.selection_history.transaction(transaction_id).cloned()
 7275            {
 7276                self.change_selections(None, cx, |s| {
 7277                    s.select_anchors(selections.to_vec());
 7278                });
 7279            }
 7280            self.request_autoscroll(Autoscroll::fit(), cx);
 7281            self.unmark_text(cx);
 7282            self.refresh_inline_completion(true, false, cx);
 7283            cx.emit(EditorEvent::Edited { transaction_id });
 7284        }
 7285    }
 7286
 7287    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7288        self.buffer
 7289            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7290    }
 7291
 7292    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7293        self.buffer
 7294            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7295    }
 7296
 7297    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7298        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7299            let line_mode = s.line_mode;
 7300            s.move_with(|map, selection| {
 7301                let cursor = if selection.is_empty() && !line_mode {
 7302                    movement::left(map, selection.start)
 7303                } else {
 7304                    selection.start
 7305                };
 7306                selection.collapse_to(cursor, SelectionGoal::None);
 7307            });
 7308        })
 7309    }
 7310
 7311    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7312        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7313            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7314        })
 7315    }
 7316
 7317    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7318        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7319            let line_mode = s.line_mode;
 7320            s.move_with(|map, selection| {
 7321                let cursor = if selection.is_empty() && !line_mode {
 7322                    movement::right(map, selection.end)
 7323                } else {
 7324                    selection.end
 7325                };
 7326                selection.collapse_to(cursor, SelectionGoal::None)
 7327            });
 7328        })
 7329    }
 7330
 7331    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7332        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7333            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7334        })
 7335    }
 7336
 7337    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7338        if self.take_rename(true, cx).is_some() {
 7339            return;
 7340        }
 7341
 7342        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7343            cx.propagate();
 7344            return;
 7345        }
 7346
 7347        let text_layout_details = &self.text_layout_details(cx);
 7348        let selection_count = self.selections.count();
 7349        let first_selection = self.selections.first_anchor();
 7350
 7351        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7352            let line_mode = s.line_mode;
 7353            s.move_with(|map, selection| {
 7354                if !selection.is_empty() && !line_mode {
 7355                    selection.goal = SelectionGoal::None;
 7356                }
 7357                let (cursor, goal) = movement::up(
 7358                    map,
 7359                    selection.start,
 7360                    selection.goal,
 7361                    false,
 7362                    text_layout_details,
 7363                );
 7364                selection.collapse_to(cursor, goal);
 7365            });
 7366        });
 7367
 7368        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7369        {
 7370            cx.propagate();
 7371        }
 7372    }
 7373
 7374    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7375        if self.take_rename(true, cx).is_some() {
 7376            return;
 7377        }
 7378
 7379        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7380            cx.propagate();
 7381            return;
 7382        }
 7383
 7384        let text_layout_details = &self.text_layout_details(cx);
 7385
 7386        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7387            let line_mode = s.line_mode;
 7388            s.move_with(|map, selection| {
 7389                if !selection.is_empty() && !line_mode {
 7390                    selection.goal = SelectionGoal::None;
 7391                }
 7392                let (cursor, goal) = movement::up_by_rows(
 7393                    map,
 7394                    selection.start,
 7395                    action.lines,
 7396                    selection.goal,
 7397                    false,
 7398                    text_layout_details,
 7399                );
 7400                selection.collapse_to(cursor, goal);
 7401            });
 7402        })
 7403    }
 7404
 7405    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7406        if self.take_rename(true, cx).is_some() {
 7407            return;
 7408        }
 7409
 7410        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7411            cx.propagate();
 7412            return;
 7413        }
 7414
 7415        let text_layout_details = &self.text_layout_details(cx);
 7416
 7417        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7418            let line_mode = s.line_mode;
 7419            s.move_with(|map, selection| {
 7420                if !selection.is_empty() && !line_mode {
 7421                    selection.goal = SelectionGoal::None;
 7422                }
 7423                let (cursor, goal) = movement::down_by_rows(
 7424                    map,
 7425                    selection.start,
 7426                    action.lines,
 7427                    selection.goal,
 7428                    false,
 7429                    text_layout_details,
 7430                );
 7431                selection.collapse_to(cursor, goal);
 7432            });
 7433        })
 7434    }
 7435
 7436    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7437        let text_layout_details = &self.text_layout_details(cx);
 7438        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7439            s.move_heads_with(|map, head, goal| {
 7440                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7441            })
 7442        })
 7443    }
 7444
 7445    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7446        let text_layout_details = &self.text_layout_details(cx);
 7447        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7448            s.move_heads_with(|map, head, goal| {
 7449                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7450            })
 7451        })
 7452    }
 7453
 7454    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7455        let Some(row_count) = self.visible_row_count() else {
 7456            return;
 7457        };
 7458
 7459        let text_layout_details = &self.text_layout_details(cx);
 7460
 7461        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7462            s.move_heads_with(|map, head, goal| {
 7463                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7464            })
 7465        })
 7466    }
 7467
 7468    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7469        if self.take_rename(true, cx).is_some() {
 7470            return;
 7471        }
 7472
 7473        if self
 7474            .context_menu
 7475            .write()
 7476            .as_mut()
 7477            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7478            .unwrap_or(false)
 7479        {
 7480            return;
 7481        }
 7482
 7483        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7484            cx.propagate();
 7485            return;
 7486        }
 7487
 7488        let Some(row_count) = self.visible_row_count() else {
 7489            return;
 7490        };
 7491
 7492        let autoscroll = if action.center_cursor {
 7493            Autoscroll::center()
 7494        } else {
 7495            Autoscroll::fit()
 7496        };
 7497
 7498        let text_layout_details = &self.text_layout_details(cx);
 7499
 7500        self.change_selections(Some(autoscroll), cx, |s| {
 7501            let line_mode = s.line_mode;
 7502            s.move_with(|map, selection| {
 7503                if !selection.is_empty() && !line_mode {
 7504                    selection.goal = SelectionGoal::None;
 7505                }
 7506                let (cursor, goal) = movement::up_by_rows(
 7507                    map,
 7508                    selection.end,
 7509                    row_count,
 7510                    selection.goal,
 7511                    false,
 7512                    text_layout_details,
 7513                );
 7514                selection.collapse_to(cursor, goal);
 7515            });
 7516        });
 7517    }
 7518
 7519    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7520        let text_layout_details = &self.text_layout_details(cx);
 7521        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7522            s.move_heads_with(|map, head, goal| {
 7523                movement::up(map, head, goal, false, text_layout_details)
 7524            })
 7525        })
 7526    }
 7527
 7528    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7529        self.take_rename(true, cx);
 7530
 7531        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7532            cx.propagate();
 7533            return;
 7534        }
 7535
 7536        let text_layout_details = &self.text_layout_details(cx);
 7537        let selection_count = self.selections.count();
 7538        let first_selection = self.selections.first_anchor();
 7539
 7540        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7541            let line_mode = s.line_mode;
 7542            s.move_with(|map, selection| {
 7543                if !selection.is_empty() && !line_mode {
 7544                    selection.goal = SelectionGoal::None;
 7545                }
 7546                let (cursor, goal) = movement::down(
 7547                    map,
 7548                    selection.end,
 7549                    selection.goal,
 7550                    false,
 7551                    text_layout_details,
 7552                );
 7553                selection.collapse_to(cursor, goal);
 7554            });
 7555        });
 7556
 7557        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7558        {
 7559            cx.propagate();
 7560        }
 7561    }
 7562
 7563    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7564        let Some(row_count) = self.visible_row_count() else {
 7565            return;
 7566        };
 7567
 7568        let text_layout_details = &self.text_layout_details(cx);
 7569
 7570        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7571            s.move_heads_with(|map, head, goal| {
 7572                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7573            })
 7574        })
 7575    }
 7576
 7577    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7578        if self.take_rename(true, cx).is_some() {
 7579            return;
 7580        }
 7581
 7582        if self
 7583            .context_menu
 7584            .write()
 7585            .as_mut()
 7586            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7587            .unwrap_or(false)
 7588        {
 7589            return;
 7590        }
 7591
 7592        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7593            cx.propagate();
 7594            return;
 7595        }
 7596
 7597        let Some(row_count) = self.visible_row_count() else {
 7598            return;
 7599        };
 7600
 7601        let autoscroll = if action.center_cursor {
 7602            Autoscroll::center()
 7603        } else {
 7604            Autoscroll::fit()
 7605        };
 7606
 7607        let text_layout_details = &self.text_layout_details(cx);
 7608        self.change_selections(Some(autoscroll), cx, |s| {
 7609            let line_mode = s.line_mode;
 7610            s.move_with(|map, selection| {
 7611                if !selection.is_empty() && !line_mode {
 7612                    selection.goal = SelectionGoal::None;
 7613                }
 7614                let (cursor, goal) = movement::down_by_rows(
 7615                    map,
 7616                    selection.end,
 7617                    row_count,
 7618                    selection.goal,
 7619                    false,
 7620                    text_layout_details,
 7621                );
 7622                selection.collapse_to(cursor, goal);
 7623            });
 7624        });
 7625    }
 7626
 7627    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7628        let text_layout_details = &self.text_layout_details(cx);
 7629        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7630            s.move_heads_with(|map, head, goal| {
 7631                movement::down(map, head, goal, false, text_layout_details)
 7632            })
 7633        });
 7634    }
 7635
 7636    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7637        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7638            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7639        }
 7640    }
 7641
 7642    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7643        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7644            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7645        }
 7646    }
 7647
 7648    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7649        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7650            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7651        }
 7652    }
 7653
 7654    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7655        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7656            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7657        }
 7658    }
 7659
 7660    pub fn move_to_previous_word_start(
 7661        &mut self,
 7662        _: &MoveToPreviousWordStart,
 7663        cx: &mut ViewContext<Self>,
 7664    ) {
 7665        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7666            s.move_cursors_with(|map, head, _| {
 7667                (
 7668                    movement::previous_word_start(map, head),
 7669                    SelectionGoal::None,
 7670                )
 7671            });
 7672        })
 7673    }
 7674
 7675    pub fn move_to_previous_subword_start(
 7676        &mut self,
 7677        _: &MoveToPreviousSubwordStart,
 7678        cx: &mut ViewContext<Self>,
 7679    ) {
 7680        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7681            s.move_cursors_with(|map, head, _| {
 7682                (
 7683                    movement::previous_subword_start(map, head),
 7684                    SelectionGoal::None,
 7685                )
 7686            });
 7687        })
 7688    }
 7689
 7690    pub fn select_to_previous_word_start(
 7691        &mut self,
 7692        _: &SelectToPreviousWordStart,
 7693        cx: &mut ViewContext<Self>,
 7694    ) {
 7695        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7696            s.move_heads_with(|map, head, _| {
 7697                (
 7698                    movement::previous_word_start(map, head),
 7699                    SelectionGoal::None,
 7700                )
 7701            });
 7702        })
 7703    }
 7704
 7705    pub fn select_to_previous_subword_start(
 7706        &mut self,
 7707        _: &SelectToPreviousSubwordStart,
 7708        cx: &mut ViewContext<Self>,
 7709    ) {
 7710        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7711            s.move_heads_with(|map, head, _| {
 7712                (
 7713                    movement::previous_subword_start(map, head),
 7714                    SelectionGoal::None,
 7715                )
 7716            });
 7717        })
 7718    }
 7719
 7720    pub fn delete_to_previous_word_start(
 7721        &mut self,
 7722        action: &DeleteToPreviousWordStart,
 7723        cx: &mut ViewContext<Self>,
 7724    ) {
 7725        self.transact(cx, |this, cx| {
 7726            this.select_autoclose_pair(cx);
 7727            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7728                let line_mode = s.line_mode;
 7729                s.move_with(|map, selection| {
 7730                    if selection.is_empty() && !line_mode {
 7731                        let cursor = if action.ignore_newlines {
 7732                            movement::previous_word_start(map, selection.head())
 7733                        } else {
 7734                            movement::previous_word_start_or_newline(map, selection.head())
 7735                        };
 7736                        selection.set_head(cursor, SelectionGoal::None);
 7737                    }
 7738                });
 7739            });
 7740            this.insert("", cx);
 7741        });
 7742    }
 7743
 7744    pub fn delete_to_previous_subword_start(
 7745        &mut self,
 7746        _: &DeleteToPreviousSubwordStart,
 7747        cx: &mut ViewContext<Self>,
 7748    ) {
 7749        self.transact(cx, |this, cx| {
 7750            this.select_autoclose_pair(cx);
 7751            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7752                let line_mode = s.line_mode;
 7753                s.move_with(|map, selection| {
 7754                    if selection.is_empty() && !line_mode {
 7755                        let cursor = movement::previous_subword_start(map, selection.head());
 7756                        selection.set_head(cursor, SelectionGoal::None);
 7757                    }
 7758                });
 7759            });
 7760            this.insert("", cx);
 7761        });
 7762    }
 7763
 7764    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7765        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7766            s.move_cursors_with(|map, head, _| {
 7767                (movement::next_word_end(map, head), SelectionGoal::None)
 7768            });
 7769        })
 7770    }
 7771
 7772    pub fn move_to_next_subword_end(
 7773        &mut self,
 7774        _: &MoveToNextSubwordEnd,
 7775        cx: &mut ViewContext<Self>,
 7776    ) {
 7777        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7778            s.move_cursors_with(|map, head, _| {
 7779                (movement::next_subword_end(map, head), SelectionGoal::None)
 7780            });
 7781        })
 7782    }
 7783
 7784    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7785        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7786            s.move_heads_with(|map, head, _| {
 7787                (movement::next_word_end(map, head), SelectionGoal::None)
 7788            });
 7789        })
 7790    }
 7791
 7792    pub fn select_to_next_subword_end(
 7793        &mut self,
 7794        _: &SelectToNextSubwordEnd,
 7795        cx: &mut ViewContext<Self>,
 7796    ) {
 7797        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7798            s.move_heads_with(|map, head, _| {
 7799                (movement::next_subword_end(map, head), SelectionGoal::None)
 7800            });
 7801        })
 7802    }
 7803
 7804    pub fn delete_to_next_word_end(
 7805        &mut self,
 7806        action: &DeleteToNextWordEnd,
 7807        cx: &mut ViewContext<Self>,
 7808    ) {
 7809        self.transact(cx, |this, cx| {
 7810            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7811                let line_mode = s.line_mode;
 7812                s.move_with(|map, selection| {
 7813                    if selection.is_empty() && !line_mode {
 7814                        let cursor = if action.ignore_newlines {
 7815                            movement::next_word_end(map, selection.head())
 7816                        } else {
 7817                            movement::next_word_end_or_newline(map, selection.head())
 7818                        };
 7819                        selection.set_head(cursor, SelectionGoal::None);
 7820                    }
 7821                });
 7822            });
 7823            this.insert("", cx);
 7824        });
 7825    }
 7826
 7827    pub fn delete_to_next_subword_end(
 7828        &mut self,
 7829        _: &DeleteToNextSubwordEnd,
 7830        cx: &mut ViewContext<Self>,
 7831    ) {
 7832        self.transact(cx, |this, cx| {
 7833            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7834                s.move_with(|map, selection| {
 7835                    if selection.is_empty() {
 7836                        let cursor = movement::next_subword_end(map, selection.head());
 7837                        selection.set_head(cursor, SelectionGoal::None);
 7838                    }
 7839                });
 7840            });
 7841            this.insert("", cx);
 7842        });
 7843    }
 7844
 7845    pub fn move_to_beginning_of_line(
 7846        &mut self,
 7847        action: &MoveToBeginningOfLine,
 7848        cx: &mut ViewContext<Self>,
 7849    ) {
 7850        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7851            s.move_cursors_with(|map, head, _| {
 7852                (
 7853                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7854                    SelectionGoal::None,
 7855                )
 7856            });
 7857        })
 7858    }
 7859
 7860    pub fn select_to_beginning_of_line(
 7861        &mut self,
 7862        action: &SelectToBeginningOfLine,
 7863        cx: &mut ViewContext<Self>,
 7864    ) {
 7865        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7866            s.move_heads_with(|map, head, _| {
 7867                (
 7868                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7869                    SelectionGoal::None,
 7870                )
 7871            });
 7872        });
 7873    }
 7874
 7875    pub fn delete_to_beginning_of_line(
 7876        &mut self,
 7877        _: &DeleteToBeginningOfLine,
 7878        cx: &mut ViewContext<Self>,
 7879    ) {
 7880        self.transact(cx, |this, cx| {
 7881            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7882                s.move_with(|_, selection| {
 7883                    selection.reversed = true;
 7884                });
 7885            });
 7886
 7887            this.select_to_beginning_of_line(
 7888                &SelectToBeginningOfLine {
 7889                    stop_at_soft_wraps: false,
 7890                },
 7891                cx,
 7892            );
 7893            this.backspace(&Backspace, cx);
 7894        });
 7895    }
 7896
 7897    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7898        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7899            s.move_cursors_with(|map, head, _| {
 7900                (
 7901                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7902                    SelectionGoal::None,
 7903                )
 7904            });
 7905        })
 7906    }
 7907
 7908    pub fn select_to_end_of_line(
 7909        &mut self,
 7910        action: &SelectToEndOfLine,
 7911        cx: &mut ViewContext<Self>,
 7912    ) {
 7913        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7914            s.move_heads_with(|map, head, _| {
 7915                (
 7916                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7917                    SelectionGoal::None,
 7918                )
 7919            });
 7920        })
 7921    }
 7922
 7923    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7924        self.transact(cx, |this, cx| {
 7925            this.select_to_end_of_line(
 7926                &SelectToEndOfLine {
 7927                    stop_at_soft_wraps: false,
 7928                },
 7929                cx,
 7930            );
 7931            this.delete(&Delete, cx);
 7932        });
 7933    }
 7934
 7935    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7936        self.transact(cx, |this, cx| {
 7937            this.select_to_end_of_line(
 7938                &SelectToEndOfLine {
 7939                    stop_at_soft_wraps: false,
 7940                },
 7941                cx,
 7942            );
 7943            this.cut(&Cut, cx);
 7944        });
 7945    }
 7946
 7947    pub fn move_to_start_of_paragraph(
 7948        &mut self,
 7949        _: &MoveToStartOfParagraph,
 7950        cx: &mut ViewContext<Self>,
 7951    ) {
 7952        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7953            cx.propagate();
 7954            return;
 7955        }
 7956
 7957        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7958            s.move_with(|map, selection| {
 7959                selection.collapse_to(
 7960                    movement::start_of_paragraph(map, selection.head(), 1),
 7961                    SelectionGoal::None,
 7962                )
 7963            });
 7964        })
 7965    }
 7966
 7967    pub fn move_to_end_of_paragraph(
 7968        &mut self,
 7969        _: &MoveToEndOfParagraph,
 7970        cx: &mut ViewContext<Self>,
 7971    ) {
 7972        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7973            cx.propagate();
 7974            return;
 7975        }
 7976
 7977        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7978            s.move_with(|map, selection| {
 7979                selection.collapse_to(
 7980                    movement::end_of_paragraph(map, selection.head(), 1),
 7981                    SelectionGoal::None,
 7982                )
 7983            });
 7984        })
 7985    }
 7986
 7987    pub fn select_to_start_of_paragraph(
 7988        &mut self,
 7989        _: &SelectToStartOfParagraph,
 7990        cx: &mut ViewContext<Self>,
 7991    ) {
 7992        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7993            cx.propagate();
 7994            return;
 7995        }
 7996
 7997        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7998            s.move_heads_with(|map, head, _| {
 7999                (
 8000                    movement::start_of_paragraph(map, head, 1),
 8001                    SelectionGoal::None,
 8002                )
 8003            });
 8004        })
 8005    }
 8006
 8007    pub fn select_to_end_of_paragraph(
 8008        &mut self,
 8009        _: &SelectToEndOfParagraph,
 8010        cx: &mut ViewContext<Self>,
 8011    ) {
 8012        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8013            cx.propagate();
 8014            return;
 8015        }
 8016
 8017        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8018            s.move_heads_with(|map, head, _| {
 8019                (
 8020                    movement::end_of_paragraph(map, head, 1),
 8021                    SelectionGoal::None,
 8022                )
 8023            });
 8024        })
 8025    }
 8026
 8027    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8028        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8029            cx.propagate();
 8030            return;
 8031        }
 8032
 8033        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8034            s.select_ranges(vec![0..0]);
 8035        });
 8036    }
 8037
 8038    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8039        let mut selection = self.selections.last::<Point>(cx);
 8040        selection.set_head(Point::zero(), SelectionGoal::None);
 8041
 8042        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8043            s.select(vec![selection]);
 8044        });
 8045    }
 8046
 8047    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8048        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8049            cx.propagate();
 8050            return;
 8051        }
 8052
 8053        let cursor = self.buffer.read(cx).read(cx).len();
 8054        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8055            s.select_ranges(vec![cursor..cursor])
 8056        });
 8057    }
 8058
 8059    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8060        self.nav_history = nav_history;
 8061    }
 8062
 8063    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8064        self.nav_history.as_ref()
 8065    }
 8066
 8067    fn push_to_nav_history(
 8068        &mut self,
 8069        cursor_anchor: Anchor,
 8070        new_position: Option<Point>,
 8071        cx: &mut ViewContext<Self>,
 8072    ) {
 8073        if let Some(nav_history) = self.nav_history.as_mut() {
 8074            let buffer = self.buffer.read(cx).read(cx);
 8075            let cursor_position = cursor_anchor.to_point(&buffer);
 8076            let scroll_state = self.scroll_manager.anchor();
 8077            let scroll_top_row = scroll_state.top_row(&buffer);
 8078            drop(buffer);
 8079
 8080            if let Some(new_position) = new_position {
 8081                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8082                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8083                    return;
 8084                }
 8085            }
 8086
 8087            nav_history.push(
 8088                Some(NavigationData {
 8089                    cursor_anchor,
 8090                    cursor_position,
 8091                    scroll_anchor: scroll_state,
 8092                    scroll_top_row,
 8093                }),
 8094                cx,
 8095            );
 8096        }
 8097    }
 8098
 8099    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8100        let buffer = self.buffer.read(cx).snapshot(cx);
 8101        let mut selection = self.selections.first::<usize>(cx);
 8102        selection.set_head(buffer.len(), SelectionGoal::None);
 8103        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8104            s.select(vec![selection]);
 8105        });
 8106    }
 8107
 8108    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8109        let end = self.buffer.read(cx).read(cx).len();
 8110        self.change_selections(None, cx, |s| {
 8111            s.select_ranges(vec![0..end]);
 8112        });
 8113    }
 8114
 8115    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8116        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8117        let mut selections = self.selections.all::<Point>(cx);
 8118        let max_point = display_map.buffer_snapshot.max_point();
 8119        for selection in &mut selections {
 8120            let rows = selection.spanned_rows(true, &display_map);
 8121            selection.start = Point::new(rows.start.0, 0);
 8122            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8123            selection.reversed = false;
 8124        }
 8125        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8126            s.select(selections);
 8127        });
 8128    }
 8129
 8130    pub fn split_selection_into_lines(
 8131        &mut self,
 8132        _: &SplitSelectionIntoLines,
 8133        cx: &mut ViewContext<Self>,
 8134    ) {
 8135        let mut to_unfold = Vec::new();
 8136        let mut new_selection_ranges = Vec::new();
 8137        {
 8138            let selections = self.selections.all::<Point>(cx);
 8139            let buffer = self.buffer.read(cx).read(cx);
 8140            for selection in selections {
 8141                for row in selection.start.row..selection.end.row {
 8142                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8143                    new_selection_ranges.push(cursor..cursor);
 8144                }
 8145                new_selection_ranges.push(selection.end..selection.end);
 8146                to_unfold.push(selection.start..selection.end);
 8147            }
 8148        }
 8149        self.unfold_ranges(to_unfold, true, true, cx);
 8150        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8151            s.select_ranges(new_selection_ranges);
 8152        });
 8153    }
 8154
 8155    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8156        self.add_selection(true, cx);
 8157    }
 8158
 8159    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8160        self.add_selection(false, cx);
 8161    }
 8162
 8163    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8164        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8165        let mut selections = self.selections.all::<Point>(cx);
 8166        let text_layout_details = self.text_layout_details(cx);
 8167        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8168            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8169            let range = oldest_selection.display_range(&display_map).sorted();
 8170
 8171            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8172            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8173            let positions = start_x.min(end_x)..start_x.max(end_x);
 8174
 8175            selections.clear();
 8176            let mut stack = Vec::new();
 8177            for row in range.start.row().0..=range.end.row().0 {
 8178                if let Some(selection) = self.selections.build_columnar_selection(
 8179                    &display_map,
 8180                    DisplayRow(row),
 8181                    &positions,
 8182                    oldest_selection.reversed,
 8183                    &text_layout_details,
 8184                ) {
 8185                    stack.push(selection.id);
 8186                    selections.push(selection);
 8187                }
 8188            }
 8189
 8190            if above {
 8191                stack.reverse();
 8192            }
 8193
 8194            AddSelectionsState { above, stack }
 8195        });
 8196
 8197        let last_added_selection = *state.stack.last().unwrap();
 8198        let mut new_selections = Vec::new();
 8199        if above == state.above {
 8200            let end_row = if above {
 8201                DisplayRow(0)
 8202            } else {
 8203                display_map.max_point().row()
 8204            };
 8205
 8206            'outer: for selection in selections {
 8207                if selection.id == last_added_selection {
 8208                    let range = selection.display_range(&display_map).sorted();
 8209                    debug_assert_eq!(range.start.row(), range.end.row());
 8210                    let mut row = range.start.row();
 8211                    let positions =
 8212                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8213                            px(start)..px(end)
 8214                        } else {
 8215                            let start_x =
 8216                                display_map.x_for_display_point(range.start, &text_layout_details);
 8217                            let end_x =
 8218                                display_map.x_for_display_point(range.end, &text_layout_details);
 8219                            start_x.min(end_x)..start_x.max(end_x)
 8220                        };
 8221
 8222                    while row != end_row {
 8223                        if above {
 8224                            row.0 -= 1;
 8225                        } else {
 8226                            row.0 += 1;
 8227                        }
 8228
 8229                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8230                            &display_map,
 8231                            row,
 8232                            &positions,
 8233                            selection.reversed,
 8234                            &text_layout_details,
 8235                        ) {
 8236                            state.stack.push(new_selection.id);
 8237                            if above {
 8238                                new_selections.push(new_selection);
 8239                                new_selections.push(selection);
 8240                            } else {
 8241                                new_selections.push(selection);
 8242                                new_selections.push(new_selection);
 8243                            }
 8244
 8245                            continue 'outer;
 8246                        }
 8247                    }
 8248                }
 8249
 8250                new_selections.push(selection);
 8251            }
 8252        } else {
 8253            new_selections = selections;
 8254            new_selections.retain(|s| s.id != last_added_selection);
 8255            state.stack.pop();
 8256        }
 8257
 8258        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8259            s.select(new_selections);
 8260        });
 8261        if state.stack.len() > 1 {
 8262            self.add_selections_state = Some(state);
 8263        }
 8264    }
 8265
 8266    pub fn select_next_match_internal(
 8267        &mut self,
 8268        display_map: &DisplaySnapshot,
 8269        replace_newest: bool,
 8270        autoscroll: Option<Autoscroll>,
 8271        cx: &mut ViewContext<Self>,
 8272    ) -> Result<()> {
 8273        fn select_next_match_ranges(
 8274            this: &mut Editor,
 8275            range: Range<usize>,
 8276            replace_newest: bool,
 8277            auto_scroll: Option<Autoscroll>,
 8278            cx: &mut ViewContext<Editor>,
 8279        ) {
 8280            this.unfold_ranges([range.clone()], false, true, cx);
 8281            this.change_selections(auto_scroll, cx, |s| {
 8282                if replace_newest {
 8283                    s.delete(s.newest_anchor().id);
 8284                }
 8285                s.insert_range(range.clone());
 8286            });
 8287        }
 8288
 8289        let buffer = &display_map.buffer_snapshot;
 8290        let mut selections = self.selections.all::<usize>(cx);
 8291        if let Some(mut select_next_state) = self.select_next_state.take() {
 8292            let query = &select_next_state.query;
 8293            if !select_next_state.done {
 8294                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8295                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8296                let mut next_selected_range = None;
 8297
 8298                let bytes_after_last_selection =
 8299                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8300                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8301                let query_matches = query
 8302                    .stream_find_iter(bytes_after_last_selection)
 8303                    .map(|result| (last_selection.end, result))
 8304                    .chain(
 8305                        query
 8306                            .stream_find_iter(bytes_before_first_selection)
 8307                            .map(|result| (0, result)),
 8308                    );
 8309
 8310                for (start_offset, query_match) in query_matches {
 8311                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8312                    let offset_range =
 8313                        start_offset + query_match.start()..start_offset + query_match.end();
 8314                    let display_range = offset_range.start.to_display_point(display_map)
 8315                        ..offset_range.end.to_display_point(display_map);
 8316
 8317                    if !select_next_state.wordwise
 8318                        || (!movement::is_inside_word(display_map, display_range.start)
 8319                            && !movement::is_inside_word(display_map, display_range.end))
 8320                    {
 8321                        // TODO: This is n^2, because we might check all the selections
 8322                        if !selections
 8323                            .iter()
 8324                            .any(|selection| selection.range().overlaps(&offset_range))
 8325                        {
 8326                            next_selected_range = Some(offset_range);
 8327                            break;
 8328                        }
 8329                    }
 8330                }
 8331
 8332                if let Some(next_selected_range) = next_selected_range {
 8333                    select_next_match_ranges(
 8334                        self,
 8335                        next_selected_range,
 8336                        replace_newest,
 8337                        autoscroll,
 8338                        cx,
 8339                    );
 8340                } else {
 8341                    select_next_state.done = true;
 8342                }
 8343            }
 8344
 8345            self.select_next_state = Some(select_next_state);
 8346        } else {
 8347            let mut only_carets = true;
 8348            let mut same_text_selected = true;
 8349            let mut selected_text = None;
 8350
 8351            let mut selections_iter = selections.iter().peekable();
 8352            while let Some(selection) = selections_iter.next() {
 8353                if selection.start != selection.end {
 8354                    only_carets = false;
 8355                }
 8356
 8357                if same_text_selected {
 8358                    if selected_text.is_none() {
 8359                        selected_text =
 8360                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8361                    }
 8362
 8363                    if let Some(next_selection) = selections_iter.peek() {
 8364                        if next_selection.range().len() == selection.range().len() {
 8365                            let next_selected_text = buffer
 8366                                .text_for_range(next_selection.range())
 8367                                .collect::<String>();
 8368                            if Some(next_selected_text) != selected_text {
 8369                                same_text_selected = false;
 8370                                selected_text = None;
 8371                            }
 8372                        } else {
 8373                            same_text_selected = false;
 8374                            selected_text = None;
 8375                        }
 8376                    }
 8377                }
 8378            }
 8379
 8380            if only_carets {
 8381                for selection in &mut selections {
 8382                    let word_range = movement::surrounding_word(
 8383                        display_map,
 8384                        selection.start.to_display_point(display_map),
 8385                    );
 8386                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8387                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8388                    selection.goal = SelectionGoal::None;
 8389                    selection.reversed = false;
 8390                    select_next_match_ranges(
 8391                        self,
 8392                        selection.start..selection.end,
 8393                        replace_newest,
 8394                        autoscroll,
 8395                        cx,
 8396                    );
 8397                }
 8398
 8399                if selections.len() == 1 {
 8400                    let selection = selections
 8401                        .last()
 8402                        .expect("ensured that there's only one selection");
 8403                    let query = buffer
 8404                        .text_for_range(selection.start..selection.end)
 8405                        .collect::<String>();
 8406                    let is_empty = query.is_empty();
 8407                    let select_state = SelectNextState {
 8408                        query: AhoCorasick::new(&[query])?,
 8409                        wordwise: true,
 8410                        done: is_empty,
 8411                    };
 8412                    self.select_next_state = Some(select_state);
 8413                } else {
 8414                    self.select_next_state = None;
 8415                }
 8416            } else if let Some(selected_text) = selected_text {
 8417                self.select_next_state = Some(SelectNextState {
 8418                    query: AhoCorasick::new(&[selected_text])?,
 8419                    wordwise: false,
 8420                    done: false,
 8421                });
 8422                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8423            }
 8424        }
 8425        Ok(())
 8426    }
 8427
 8428    pub fn select_all_matches(
 8429        &mut self,
 8430        _action: &SelectAllMatches,
 8431        cx: &mut ViewContext<Self>,
 8432    ) -> Result<()> {
 8433        self.push_to_selection_history();
 8434        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8435
 8436        self.select_next_match_internal(&display_map, false, None, cx)?;
 8437        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8438            return Ok(());
 8439        };
 8440        if select_next_state.done {
 8441            return Ok(());
 8442        }
 8443
 8444        let mut new_selections = self.selections.all::<usize>(cx);
 8445
 8446        let buffer = &display_map.buffer_snapshot;
 8447        let query_matches = select_next_state
 8448            .query
 8449            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8450
 8451        for query_match in query_matches {
 8452            let query_match = query_match.unwrap(); // can only fail due to I/O
 8453            let offset_range = query_match.start()..query_match.end();
 8454            let display_range = offset_range.start.to_display_point(&display_map)
 8455                ..offset_range.end.to_display_point(&display_map);
 8456
 8457            if !select_next_state.wordwise
 8458                || (!movement::is_inside_word(&display_map, display_range.start)
 8459                    && !movement::is_inside_word(&display_map, display_range.end))
 8460            {
 8461                self.selections.change_with(cx, |selections| {
 8462                    new_selections.push(Selection {
 8463                        id: selections.new_selection_id(),
 8464                        start: offset_range.start,
 8465                        end: offset_range.end,
 8466                        reversed: false,
 8467                        goal: SelectionGoal::None,
 8468                    });
 8469                });
 8470            }
 8471        }
 8472
 8473        new_selections.sort_by_key(|selection| selection.start);
 8474        let mut ix = 0;
 8475        while ix + 1 < new_selections.len() {
 8476            let current_selection = &new_selections[ix];
 8477            let next_selection = &new_selections[ix + 1];
 8478            if current_selection.range().overlaps(&next_selection.range()) {
 8479                if current_selection.id < next_selection.id {
 8480                    new_selections.remove(ix + 1);
 8481                } else {
 8482                    new_selections.remove(ix);
 8483                }
 8484            } else {
 8485                ix += 1;
 8486            }
 8487        }
 8488
 8489        select_next_state.done = true;
 8490        self.unfold_ranges(
 8491            new_selections.iter().map(|selection| selection.range()),
 8492            false,
 8493            false,
 8494            cx,
 8495        );
 8496        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8497            selections.select(new_selections)
 8498        });
 8499
 8500        Ok(())
 8501    }
 8502
 8503    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8504        self.push_to_selection_history();
 8505        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8506        self.select_next_match_internal(
 8507            &display_map,
 8508            action.replace_newest,
 8509            Some(Autoscroll::newest()),
 8510            cx,
 8511        )?;
 8512        Ok(())
 8513    }
 8514
 8515    pub fn select_previous(
 8516        &mut self,
 8517        action: &SelectPrevious,
 8518        cx: &mut ViewContext<Self>,
 8519    ) -> Result<()> {
 8520        self.push_to_selection_history();
 8521        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8522        let buffer = &display_map.buffer_snapshot;
 8523        let mut selections = self.selections.all::<usize>(cx);
 8524        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8525            let query = &select_prev_state.query;
 8526            if !select_prev_state.done {
 8527                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8528                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8529                let mut next_selected_range = None;
 8530                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8531                let bytes_before_last_selection =
 8532                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8533                let bytes_after_first_selection =
 8534                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8535                let query_matches = query
 8536                    .stream_find_iter(bytes_before_last_selection)
 8537                    .map(|result| (last_selection.start, result))
 8538                    .chain(
 8539                        query
 8540                            .stream_find_iter(bytes_after_first_selection)
 8541                            .map(|result| (buffer.len(), result)),
 8542                    );
 8543                for (end_offset, query_match) in query_matches {
 8544                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8545                    let offset_range =
 8546                        end_offset - query_match.end()..end_offset - query_match.start();
 8547                    let display_range = offset_range.start.to_display_point(&display_map)
 8548                        ..offset_range.end.to_display_point(&display_map);
 8549
 8550                    if !select_prev_state.wordwise
 8551                        || (!movement::is_inside_word(&display_map, display_range.start)
 8552                            && !movement::is_inside_word(&display_map, display_range.end))
 8553                    {
 8554                        next_selected_range = Some(offset_range);
 8555                        break;
 8556                    }
 8557                }
 8558
 8559                if let Some(next_selected_range) = next_selected_range {
 8560                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8561                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8562                        if action.replace_newest {
 8563                            s.delete(s.newest_anchor().id);
 8564                        }
 8565                        s.insert_range(next_selected_range);
 8566                    });
 8567                } else {
 8568                    select_prev_state.done = true;
 8569                }
 8570            }
 8571
 8572            self.select_prev_state = Some(select_prev_state);
 8573        } else {
 8574            let mut only_carets = true;
 8575            let mut same_text_selected = true;
 8576            let mut selected_text = None;
 8577
 8578            let mut selections_iter = selections.iter().peekable();
 8579            while let Some(selection) = selections_iter.next() {
 8580                if selection.start != selection.end {
 8581                    only_carets = false;
 8582                }
 8583
 8584                if same_text_selected {
 8585                    if selected_text.is_none() {
 8586                        selected_text =
 8587                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8588                    }
 8589
 8590                    if let Some(next_selection) = selections_iter.peek() {
 8591                        if next_selection.range().len() == selection.range().len() {
 8592                            let next_selected_text = buffer
 8593                                .text_for_range(next_selection.range())
 8594                                .collect::<String>();
 8595                            if Some(next_selected_text) != selected_text {
 8596                                same_text_selected = false;
 8597                                selected_text = None;
 8598                            }
 8599                        } else {
 8600                            same_text_selected = false;
 8601                            selected_text = None;
 8602                        }
 8603                    }
 8604                }
 8605            }
 8606
 8607            if only_carets {
 8608                for selection in &mut selections {
 8609                    let word_range = movement::surrounding_word(
 8610                        &display_map,
 8611                        selection.start.to_display_point(&display_map),
 8612                    );
 8613                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8614                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8615                    selection.goal = SelectionGoal::None;
 8616                    selection.reversed = false;
 8617                }
 8618                if selections.len() == 1 {
 8619                    let selection = selections
 8620                        .last()
 8621                        .expect("ensured that there's only one selection");
 8622                    let query = buffer
 8623                        .text_for_range(selection.start..selection.end)
 8624                        .collect::<String>();
 8625                    let is_empty = query.is_empty();
 8626                    let select_state = SelectNextState {
 8627                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8628                        wordwise: true,
 8629                        done: is_empty,
 8630                    };
 8631                    self.select_prev_state = Some(select_state);
 8632                } else {
 8633                    self.select_prev_state = None;
 8634                }
 8635
 8636                self.unfold_ranges(
 8637                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8638                    false,
 8639                    true,
 8640                    cx,
 8641                );
 8642                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8643                    s.select(selections);
 8644                });
 8645            } else if let Some(selected_text) = selected_text {
 8646                self.select_prev_state = Some(SelectNextState {
 8647                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8648                    wordwise: false,
 8649                    done: false,
 8650                });
 8651                self.select_previous(action, cx)?;
 8652            }
 8653        }
 8654        Ok(())
 8655    }
 8656
 8657    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8658        let text_layout_details = &self.text_layout_details(cx);
 8659        self.transact(cx, |this, cx| {
 8660            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8661            let mut edits = Vec::new();
 8662            let mut selection_edit_ranges = Vec::new();
 8663            let mut last_toggled_row = None;
 8664            let snapshot = this.buffer.read(cx).read(cx);
 8665            let empty_str: Arc<str> = Arc::default();
 8666            let mut suffixes_inserted = Vec::new();
 8667
 8668            fn comment_prefix_range(
 8669                snapshot: &MultiBufferSnapshot,
 8670                row: MultiBufferRow,
 8671                comment_prefix: &str,
 8672                comment_prefix_whitespace: &str,
 8673            ) -> Range<Point> {
 8674                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8675
 8676                let mut line_bytes = snapshot
 8677                    .bytes_in_range(start..snapshot.max_point())
 8678                    .flatten()
 8679                    .copied();
 8680
 8681                // If this line currently begins with the line comment prefix, then record
 8682                // the range containing the prefix.
 8683                if line_bytes
 8684                    .by_ref()
 8685                    .take(comment_prefix.len())
 8686                    .eq(comment_prefix.bytes())
 8687                {
 8688                    // Include any whitespace that matches the comment prefix.
 8689                    let matching_whitespace_len = line_bytes
 8690                        .zip(comment_prefix_whitespace.bytes())
 8691                        .take_while(|(a, b)| a == b)
 8692                        .count() as u32;
 8693                    let end = Point::new(
 8694                        start.row,
 8695                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8696                    );
 8697                    start..end
 8698                } else {
 8699                    start..start
 8700                }
 8701            }
 8702
 8703            fn comment_suffix_range(
 8704                snapshot: &MultiBufferSnapshot,
 8705                row: MultiBufferRow,
 8706                comment_suffix: &str,
 8707                comment_suffix_has_leading_space: bool,
 8708            ) -> Range<Point> {
 8709                let end = Point::new(row.0, snapshot.line_len(row));
 8710                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8711
 8712                let mut line_end_bytes = snapshot
 8713                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8714                    .flatten()
 8715                    .copied();
 8716
 8717                let leading_space_len = if suffix_start_column > 0
 8718                    && line_end_bytes.next() == Some(b' ')
 8719                    && comment_suffix_has_leading_space
 8720                {
 8721                    1
 8722                } else {
 8723                    0
 8724                };
 8725
 8726                // If this line currently begins with the line comment prefix, then record
 8727                // the range containing the prefix.
 8728                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8729                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8730                    start..end
 8731                } else {
 8732                    end..end
 8733                }
 8734            }
 8735
 8736            // TODO: Handle selections that cross excerpts
 8737            for selection in &mut selections {
 8738                let start_column = snapshot
 8739                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8740                    .len;
 8741                let language = if let Some(language) =
 8742                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8743                {
 8744                    language
 8745                } else {
 8746                    continue;
 8747                };
 8748
 8749                selection_edit_ranges.clear();
 8750
 8751                // If multiple selections contain a given row, avoid processing that
 8752                // row more than once.
 8753                let mut start_row = MultiBufferRow(selection.start.row);
 8754                if last_toggled_row == Some(start_row) {
 8755                    start_row = start_row.next_row();
 8756                }
 8757                let end_row =
 8758                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8759                        MultiBufferRow(selection.end.row - 1)
 8760                    } else {
 8761                        MultiBufferRow(selection.end.row)
 8762                    };
 8763                last_toggled_row = Some(end_row);
 8764
 8765                if start_row > end_row {
 8766                    continue;
 8767                }
 8768
 8769                // If the language has line comments, toggle those.
 8770                let full_comment_prefixes = language.line_comment_prefixes();
 8771                if !full_comment_prefixes.is_empty() {
 8772                    let first_prefix = full_comment_prefixes
 8773                        .first()
 8774                        .expect("prefixes is non-empty");
 8775                    let prefix_trimmed_lengths = full_comment_prefixes
 8776                        .iter()
 8777                        .map(|p| p.trim_end_matches(' ').len())
 8778                        .collect::<SmallVec<[usize; 4]>>();
 8779
 8780                    let mut all_selection_lines_are_comments = true;
 8781
 8782                    for row in start_row.0..=end_row.0 {
 8783                        let row = MultiBufferRow(row);
 8784                        if start_row < end_row && snapshot.is_line_blank(row) {
 8785                            continue;
 8786                        }
 8787
 8788                        let prefix_range = full_comment_prefixes
 8789                            .iter()
 8790                            .zip(prefix_trimmed_lengths.iter().copied())
 8791                            .map(|(prefix, trimmed_prefix_len)| {
 8792                                comment_prefix_range(
 8793                                    snapshot.deref(),
 8794                                    row,
 8795                                    &prefix[..trimmed_prefix_len],
 8796                                    &prefix[trimmed_prefix_len..],
 8797                                )
 8798                            })
 8799                            .max_by_key(|range| range.end.column - range.start.column)
 8800                            .expect("prefixes is non-empty");
 8801
 8802                        if prefix_range.is_empty() {
 8803                            all_selection_lines_are_comments = false;
 8804                        }
 8805
 8806                        selection_edit_ranges.push(prefix_range);
 8807                    }
 8808
 8809                    if all_selection_lines_are_comments {
 8810                        edits.extend(
 8811                            selection_edit_ranges
 8812                                .iter()
 8813                                .cloned()
 8814                                .map(|range| (range, empty_str.clone())),
 8815                        );
 8816                    } else {
 8817                        let min_column = selection_edit_ranges
 8818                            .iter()
 8819                            .map(|range| range.start.column)
 8820                            .min()
 8821                            .unwrap_or(0);
 8822                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8823                            let position = Point::new(range.start.row, min_column);
 8824                            (position..position, first_prefix.clone())
 8825                        }));
 8826                    }
 8827                } else if let Some((full_comment_prefix, comment_suffix)) =
 8828                    language.block_comment_delimiters()
 8829                {
 8830                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8831                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8832                    let prefix_range = comment_prefix_range(
 8833                        snapshot.deref(),
 8834                        start_row,
 8835                        comment_prefix,
 8836                        comment_prefix_whitespace,
 8837                    );
 8838                    let suffix_range = comment_suffix_range(
 8839                        snapshot.deref(),
 8840                        end_row,
 8841                        comment_suffix.trim_start_matches(' '),
 8842                        comment_suffix.starts_with(' '),
 8843                    );
 8844
 8845                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8846                        edits.push((
 8847                            prefix_range.start..prefix_range.start,
 8848                            full_comment_prefix.clone(),
 8849                        ));
 8850                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8851                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8852                    } else {
 8853                        edits.push((prefix_range, empty_str.clone()));
 8854                        edits.push((suffix_range, empty_str.clone()));
 8855                    }
 8856                } else {
 8857                    continue;
 8858                }
 8859            }
 8860
 8861            drop(snapshot);
 8862            this.buffer.update(cx, |buffer, cx| {
 8863                buffer.edit(edits, None, cx);
 8864            });
 8865
 8866            // Adjust selections so that they end before any comment suffixes that
 8867            // were inserted.
 8868            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8869            let mut selections = this.selections.all::<Point>(cx);
 8870            let snapshot = this.buffer.read(cx).read(cx);
 8871            for selection in &mut selections {
 8872                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8873                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8874                        Ordering::Less => {
 8875                            suffixes_inserted.next();
 8876                            continue;
 8877                        }
 8878                        Ordering::Greater => break,
 8879                        Ordering::Equal => {
 8880                            if selection.end.column == snapshot.line_len(row) {
 8881                                if selection.is_empty() {
 8882                                    selection.start.column -= suffix_len as u32;
 8883                                }
 8884                                selection.end.column -= suffix_len as u32;
 8885                            }
 8886                            break;
 8887                        }
 8888                    }
 8889                }
 8890            }
 8891
 8892            drop(snapshot);
 8893            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8894
 8895            let selections = this.selections.all::<Point>(cx);
 8896            let selections_on_single_row = selections.windows(2).all(|selections| {
 8897                selections[0].start.row == selections[1].start.row
 8898                    && selections[0].end.row == selections[1].end.row
 8899                    && selections[0].start.row == selections[0].end.row
 8900            });
 8901            let selections_selecting = selections
 8902                .iter()
 8903                .any(|selection| selection.start != selection.end);
 8904            let advance_downwards = action.advance_downwards
 8905                && selections_on_single_row
 8906                && !selections_selecting
 8907                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8908
 8909            if advance_downwards {
 8910                let snapshot = this.buffer.read(cx).snapshot(cx);
 8911
 8912                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8913                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8914                        let mut point = display_point.to_point(display_snapshot);
 8915                        point.row += 1;
 8916                        point = snapshot.clip_point(point, Bias::Left);
 8917                        let display_point = point.to_display_point(display_snapshot);
 8918                        let goal = SelectionGoal::HorizontalPosition(
 8919                            display_snapshot
 8920                                .x_for_display_point(display_point, text_layout_details)
 8921                                .into(),
 8922                        );
 8923                        (display_point, goal)
 8924                    })
 8925                });
 8926            }
 8927        });
 8928    }
 8929
 8930    pub fn select_enclosing_symbol(
 8931        &mut self,
 8932        _: &SelectEnclosingSymbol,
 8933        cx: &mut ViewContext<Self>,
 8934    ) {
 8935        let buffer = self.buffer.read(cx).snapshot(cx);
 8936        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8937
 8938        fn update_selection(
 8939            selection: &Selection<usize>,
 8940            buffer_snap: &MultiBufferSnapshot,
 8941        ) -> Option<Selection<usize>> {
 8942            let cursor = selection.head();
 8943            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8944            for symbol in symbols.iter().rev() {
 8945                let start = symbol.range.start.to_offset(buffer_snap);
 8946                let end = symbol.range.end.to_offset(buffer_snap);
 8947                let new_range = start..end;
 8948                if start < selection.start || end > selection.end {
 8949                    return Some(Selection {
 8950                        id: selection.id,
 8951                        start: new_range.start,
 8952                        end: new_range.end,
 8953                        goal: SelectionGoal::None,
 8954                        reversed: selection.reversed,
 8955                    });
 8956                }
 8957            }
 8958            None
 8959        }
 8960
 8961        let mut selected_larger_symbol = false;
 8962        let new_selections = old_selections
 8963            .iter()
 8964            .map(|selection| match update_selection(selection, &buffer) {
 8965                Some(new_selection) => {
 8966                    if new_selection.range() != selection.range() {
 8967                        selected_larger_symbol = true;
 8968                    }
 8969                    new_selection
 8970                }
 8971                None => selection.clone(),
 8972            })
 8973            .collect::<Vec<_>>();
 8974
 8975        if selected_larger_symbol {
 8976            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8977                s.select(new_selections);
 8978            });
 8979        }
 8980    }
 8981
 8982    pub fn select_larger_syntax_node(
 8983        &mut self,
 8984        _: &SelectLargerSyntaxNode,
 8985        cx: &mut ViewContext<Self>,
 8986    ) {
 8987        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8988        let buffer = self.buffer.read(cx).snapshot(cx);
 8989        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8990
 8991        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8992        let mut selected_larger_node = false;
 8993        let new_selections = old_selections
 8994            .iter()
 8995            .map(|selection| {
 8996                let old_range = selection.start..selection.end;
 8997                let mut new_range = old_range.clone();
 8998                while let Some(containing_range) =
 8999                    buffer.range_for_syntax_ancestor(new_range.clone())
 9000                {
 9001                    new_range = containing_range;
 9002                    if !display_map.intersects_fold(new_range.start)
 9003                        && !display_map.intersects_fold(new_range.end)
 9004                    {
 9005                        break;
 9006                    }
 9007                }
 9008
 9009                selected_larger_node |= new_range != old_range;
 9010                Selection {
 9011                    id: selection.id,
 9012                    start: new_range.start,
 9013                    end: new_range.end,
 9014                    goal: SelectionGoal::None,
 9015                    reversed: selection.reversed,
 9016                }
 9017            })
 9018            .collect::<Vec<_>>();
 9019
 9020        if selected_larger_node {
 9021            stack.push(old_selections);
 9022            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9023                s.select(new_selections);
 9024            });
 9025        }
 9026        self.select_larger_syntax_node_stack = stack;
 9027    }
 9028
 9029    pub fn select_smaller_syntax_node(
 9030        &mut self,
 9031        _: &SelectSmallerSyntaxNode,
 9032        cx: &mut ViewContext<Self>,
 9033    ) {
 9034        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9035        if let Some(selections) = stack.pop() {
 9036            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9037                s.select(selections.to_vec());
 9038            });
 9039        }
 9040        self.select_larger_syntax_node_stack = stack;
 9041    }
 9042
 9043    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9044        if !EditorSettings::get_global(cx).gutter.runnables {
 9045            self.clear_tasks();
 9046            return Task::ready(());
 9047        }
 9048        let project = self.project.clone();
 9049        cx.spawn(|this, mut cx| async move {
 9050            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9051                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9052            }) else {
 9053                return;
 9054            };
 9055
 9056            let Some(project) = project else {
 9057                return;
 9058            };
 9059
 9060            let hide_runnables = project
 9061                .update(&mut cx, |project, cx| {
 9062                    // Do not display any test indicators in non-dev server remote projects.
 9063                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9064                })
 9065                .unwrap_or(true);
 9066            if hide_runnables {
 9067                return;
 9068            }
 9069            let new_rows =
 9070                cx.background_executor()
 9071                    .spawn({
 9072                        let snapshot = display_snapshot.clone();
 9073                        async move {
 9074                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9075                        }
 9076                    })
 9077                    .await;
 9078            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9079
 9080            this.update(&mut cx, |this, _| {
 9081                this.clear_tasks();
 9082                for (key, value) in rows {
 9083                    this.insert_tasks(key, value);
 9084                }
 9085            })
 9086            .ok();
 9087        })
 9088    }
 9089    fn fetch_runnable_ranges(
 9090        snapshot: &DisplaySnapshot,
 9091        range: Range<Anchor>,
 9092    ) -> Vec<language::RunnableRange> {
 9093        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9094    }
 9095
 9096    fn runnable_rows(
 9097        project: Model<Project>,
 9098        snapshot: DisplaySnapshot,
 9099        runnable_ranges: Vec<RunnableRange>,
 9100        mut cx: AsyncWindowContext,
 9101    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9102        runnable_ranges
 9103            .into_iter()
 9104            .filter_map(|mut runnable| {
 9105                let tasks = cx
 9106                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9107                    .ok()?;
 9108                if tasks.is_empty() {
 9109                    return None;
 9110                }
 9111
 9112                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9113
 9114                let row = snapshot
 9115                    .buffer_snapshot
 9116                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9117                    .1
 9118                    .start
 9119                    .row;
 9120
 9121                let context_range =
 9122                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9123                Some((
 9124                    (runnable.buffer_id, row),
 9125                    RunnableTasks {
 9126                        templates: tasks,
 9127                        offset: MultiBufferOffset(runnable.run_range.start),
 9128                        context_range,
 9129                        column: point.column,
 9130                        extra_variables: runnable.extra_captures,
 9131                    },
 9132                ))
 9133            })
 9134            .collect()
 9135    }
 9136
 9137    fn templates_with_tags(
 9138        project: &Model<Project>,
 9139        runnable: &mut Runnable,
 9140        cx: &WindowContext<'_>,
 9141    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9142        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9143            let (worktree_id, file) = project
 9144                .buffer_for_id(runnable.buffer, cx)
 9145                .and_then(|buffer| buffer.read(cx).file())
 9146                .map(|file| (file.worktree_id(cx), file.clone()))
 9147                .unzip();
 9148
 9149            (
 9150                project.task_store().read(cx).task_inventory().cloned(),
 9151                worktree_id,
 9152                file,
 9153            )
 9154        });
 9155
 9156        let tags = mem::take(&mut runnable.tags);
 9157        let mut tags: Vec<_> = tags
 9158            .into_iter()
 9159            .flat_map(|tag| {
 9160                let tag = tag.0.clone();
 9161                inventory
 9162                    .as_ref()
 9163                    .into_iter()
 9164                    .flat_map(|inventory| {
 9165                        inventory.read(cx).list_tasks(
 9166                            file.clone(),
 9167                            Some(runnable.language.clone()),
 9168                            worktree_id,
 9169                            cx,
 9170                        )
 9171                    })
 9172                    .filter(move |(_, template)| {
 9173                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9174                    })
 9175            })
 9176            .sorted_by_key(|(kind, _)| kind.to_owned())
 9177            .collect();
 9178        if let Some((leading_tag_source, _)) = tags.first() {
 9179            // Strongest source wins; if we have worktree tag binding, prefer that to
 9180            // global and language bindings;
 9181            // if we have a global binding, prefer that to language binding.
 9182            let first_mismatch = tags
 9183                .iter()
 9184                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9185            if let Some(index) = first_mismatch {
 9186                tags.truncate(index);
 9187            }
 9188        }
 9189
 9190        tags
 9191    }
 9192
 9193    pub fn move_to_enclosing_bracket(
 9194        &mut self,
 9195        _: &MoveToEnclosingBracket,
 9196        cx: &mut ViewContext<Self>,
 9197    ) {
 9198        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9199            s.move_offsets_with(|snapshot, selection| {
 9200                let Some(enclosing_bracket_ranges) =
 9201                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9202                else {
 9203                    return;
 9204                };
 9205
 9206                let mut best_length = usize::MAX;
 9207                let mut best_inside = false;
 9208                let mut best_in_bracket_range = false;
 9209                let mut best_destination = None;
 9210                for (open, close) in enclosing_bracket_ranges {
 9211                    let close = close.to_inclusive();
 9212                    let length = close.end() - open.start;
 9213                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9214                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9215                        || close.contains(&selection.head());
 9216
 9217                    // If best is next to a bracket and current isn't, skip
 9218                    if !in_bracket_range && best_in_bracket_range {
 9219                        continue;
 9220                    }
 9221
 9222                    // Prefer smaller lengths unless best is inside and current isn't
 9223                    if length > best_length && (best_inside || !inside) {
 9224                        continue;
 9225                    }
 9226
 9227                    best_length = length;
 9228                    best_inside = inside;
 9229                    best_in_bracket_range = in_bracket_range;
 9230                    best_destination = Some(
 9231                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9232                            if inside {
 9233                                open.end
 9234                            } else {
 9235                                open.start
 9236                            }
 9237                        } else if inside {
 9238                            *close.start()
 9239                        } else {
 9240                            *close.end()
 9241                        },
 9242                    );
 9243                }
 9244
 9245                if let Some(destination) = best_destination {
 9246                    selection.collapse_to(destination, SelectionGoal::None);
 9247                }
 9248            })
 9249        });
 9250    }
 9251
 9252    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9253        self.end_selection(cx);
 9254        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9255        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9256            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9257            self.select_next_state = entry.select_next_state;
 9258            self.select_prev_state = entry.select_prev_state;
 9259            self.add_selections_state = entry.add_selections_state;
 9260            self.request_autoscroll(Autoscroll::newest(), cx);
 9261        }
 9262        self.selection_history.mode = SelectionHistoryMode::Normal;
 9263    }
 9264
 9265    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9266        self.end_selection(cx);
 9267        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9268        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9269            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9270            self.select_next_state = entry.select_next_state;
 9271            self.select_prev_state = entry.select_prev_state;
 9272            self.add_selections_state = entry.add_selections_state;
 9273            self.request_autoscroll(Autoscroll::newest(), cx);
 9274        }
 9275        self.selection_history.mode = SelectionHistoryMode::Normal;
 9276    }
 9277
 9278    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9279        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9280    }
 9281
 9282    pub fn expand_excerpts_down(
 9283        &mut self,
 9284        action: &ExpandExcerptsDown,
 9285        cx: &mut ViewContext<Self>,
 9286    ) {
 9287        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9288    }
 9289
 9290    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9291        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9292    }
 9293
 9294    pub fn expand_excerpts_for_direction(
 9295        &mut self,
 9296        lines: u32,
 9297        direction: ExpandExcerptDirection,
 9298        cx: &mut ViewContext<Self>,
 9299    ) {
 9300        let selections = self.selections.disjoint_anchors();
 9301
 9302        let lines = if lines == 0 {
 9303            EditorSettings::get_global(cx).expand_excerpt_lines
 9304        } else {
 9305            lines
 9306        };
 9307
 9308        self.buffer.update(cx, |buffer, cx| {
 9309            buffer.expand_excerpts(
 9310                selections
 9311                    .iter()
 9312                    .map(|selection| selection.head().excerpt_id)
 9313                    .dedup(),
 9314                lines,
 9315                direction,
 9316                cx,
 9317            )
 9318        })
 9319    }
 9320
 9321    pub fn expand_excerpt(
 9322        &mut self,
 9323        excerpt: ExcerptId,
 9324        direction: ExpandExcerptDirection,
 9325        cx: &mut ViewContext<Self>,
 9326    ) {
 9327        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9328        self.buffer.update(cx, |buffer, cx| {
 9329            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9330        })
 9331    }
 9332
 9333    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9334        self.go_to_diagnostic_impl(Direction::Next, cx)
 9335    }
 9336
 9337    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9338        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9339    }
 9340
 9341    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9342        let buffer = self.buffer.read(cx).snapshot(cx);
 9343        let selection = self.selections.newest::<usize>(cx);
 9344
 9345        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9346        if direction == Direction::Next {
 9347            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9348                let (group_id, jump_to) = popover.activation_info();
 9349                if self.activate_diagnostics(group_id, cx) {
 9350                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9351                        let mut new_selection = s.newest_anchor().clone();
 9352                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9353                        s.select_anchors(vec![new_selection.clone()]);
 9354                    });
 9355                }
 9356                return;
 9357            }
 9358        }
 9359
 9360        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9361            active_diagnostics
 9362                .primary_range
 9363                .to_offset(&buffer)
 9364                .to_inclusive()
 9365        });
 9366        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9367            if active_primary_range.contains(&selection.head()) {
 9368                *active_primary_range.start()
 9369            } else {
 9370                selection.head()
 9371            }
 9372        } else {
 9373            selection.head()
 9374        };
 9375        let snapshot = self.snapshot(cx);
 9376        loop {
 9377            let diagnostics = if direction == Direction::Prev {
 9378                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9379            } else {
 9380                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9381            }
 9382            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9383            let group = diagnostics
 9384                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9385                // be sorted in a stable way
 9386                // skip until we are at current active diagnostic, if it exists
 9387                .skip_while(|entry| {
 9388                    (match direction {
 9389                        Direction::Prev => entry.range.start >= search_start,
 9390                        Direction::Next => entry.range.start <= search_start,
 9391                    }) && self
 9392                        .active_diagnostics
 9393                        .as_ref()
 9394                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9395                })
 9396                .find_map(|entry| {
 9397                    if entry.diagnostic.is_primary
 9398                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9399                        && !entry.range.is_empty()
 9400                        // if we match with the active diagnostic, skip it
 9401                        && Some(entry.diagnostic.group_id)
 9402                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9403                    {
 9404                        Some((entry.range, entry.diagnostic.group_id))
 9405                    } else {
 9406                        None
 9407                    }
 9408                });
 9409
 9410            if let Some((primary_range, group_id)) = group {
 9411                if self.activate_diagnostics(group_id, cx) {
 9412                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9413                        s.select(vec![Selection {
 9414                            id: selection.id,
 9415                            start: primary_range.start,
 9416                            end: primary_range.start,
 9417                            reversed: false,
 9418                            goal: SelectionGoal::None,
 9419                        }]);
 9420                    });
 9421                }
 9422                break;
 9423            } else {
 9424                // Cycle around to the start of the buffer, potentially moving back to the start of
 9425                // the currently active diagnostic.
 9426                active_primary_range.take();
 9427                if direction == Direction::Prev {
 9428                    if search_start == buffer.len() {
 9429                        break;
 9430                    } else {
 9431                        search_start = buffer.len();
 9432                    }
 9433                } else if search_start == 0 {
 9434                    break;
 9435                } else {
 9436                    search_start = 0;
 9437                }
 9438            }
 9439        }
 9440    }
 9441
 9442    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9443        let snapshot = self
 9444            .display_map
 9445            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9446        let selection = self.selections.newest::<Point>(cx);
 9447        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9448    }
 9449
 9450    fn go_to_hunk_after_position(
 9451        &mut self,
 9452        snapshot: &DisplaySnapshot,
 9453        position: Point,
 9454        cx: &mut ViewContext<'_, Editor>,
 9455    ) -> Option<MultiBufferDiffHunk> {
 9456        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9457            snapshot,
 9458            position,
 9459            false,
 9460            snapshot
 9461                .buffer_snapshot
 9462                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9463            cx,
 9464        ) {
 9465            return Some(hunk);
 9466        }
 9467
 9468        let wrapped_point = Point::zero();
 9469        self.go_to_next_hunk_in_direction(
 9470            snapshot,
 9471            wrapped_point,
 9472            true,
 9473            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9474                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9475            ),
 9476            cx,
 9477        )
 9478    }
 9479
 9480    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9481        let snapshot = self
 9482            .display_map
 9483            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9484        let selection = self.selections.newest::<Point>(cx);
 9485
 9486        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9487    }
 9488
 9489    fn go_to_hunk_before_position(
 9490        &mut self,
 9491        snapshot: &DisplaySnapshot,
 9492        position: Point,
 9493        cx: &mut ViewContext<'_, Editor>,
 9494    ) -> Option<MultiBufferDiffHunk> {
 9495        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9496            snapshot,
 9497            position,
 9498            false,
 9499            snapshot
 9500                .buffer_snapshot
 9501                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9502            cx,
 9503        ) {
 9504            return Some(hunk);
 9505        }
 9506
 9507        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9508        self.go_to_next_hunk_in_direction(
 9509            snapshot,
 9510            wrapped_point,
 9511            true,
 9512            snapshot
 9513                .buffer_snapshot
 9514                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9515            cx,
 9516        )
 9517    }
 9518
 9519    fn go_to_next_hunk_in_direction(
 9520        &mut self,
 9521        snapshot: &DisplaySnapshot,
 9522        initial_point: Point,
 9523        is_wrapped: bool,
 9524        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9525        cx: &mut ViewContext<Editor>,
 9526    ) -> Option<MultiBufferDiffHunk> {
 9527        let display_point = initial_point.to_display_point(snapshot);
 9528        let mut hunks = hunks
 9529            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9530            .filter(|(display_hunk, _)| {
 9531                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9532            })
 9533            .dedup();
 9534
 9535        if let Some((display_hunk, hunk)) = hunks.next() {
 9536            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9537                let row = display_hunk.start_display_row();
 9538                let point = DisplayPoint::new(row, 0);
 9539                s.select_display_ranges([point..point]);
 9540            });
 9541
 9542            Some(hunk)
 9543        } else {
 9544            None
 9545        }
 9546    }
 9547
 9548    pub fn go_to_definition(
 9549        &mut self,
 9550        _: &GoToDefinition,
 9551        cx: &mut ViewContext<Self>,
 9552    ) -> Task<Result<Navigated>> {
 9553        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9554        cx.spawn(|editor, mut cx| async move {
 9555            if definition.await? == Navigated::Yes {
 9556                return Ok(Navigated::Yes);
 9557            }
 9558            match editor.update(&mut cx, |editor, cx| {
 9559                editor.find_all_references(&FindAllReferences, cx)
 9560            })? {
 9561                Some(references) => references.await,
 9562                None => Ok(Navigated::No),
 9563            }
 9564        })
 9565    }
 9566
 9567    pub fn go_to_declaration(
 9568        &mut self,
 9569        _: &GoToDeclaration,
 9570        cx: &mut ViewContext<Self>,
 9571    ) -> Task<Result<Navigated>> {
 9572        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9573    }
 9574
 9575    pub fn go_to_declaration_split(
 9576        &mut self,
 9577        _: &GoToDeclaration,
 9578        cx: &mut ViewContext<Self>,
 9579    ) -> Task<Result<Navigated>> {
 9580        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9581    }
 9582
 9583    pub fn go_to_implementation(
 9584        &mut self,
 9585        _: &GoToImplementation,
 9586        cx: &mut ViewContext<Self>,
 9587    ) -> Task<Result<Navigated>> {
 9588        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9589    }
 9590
 9591    pub fn go_to_implementation_split(
 9592        &mut self,
 9593        _: &GoToImplementationSplit,
 9594        cx: &mut ViewContext<Self>,
 9595    ) -> Task<Result<Navigated>> {
 9596        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9597    }
 9598
 9599    pub fn go_to_type_definition(
 9600        &mut self,
 9601        _: &GoToTypeDefinition,
 9602        cx: &mut ViewContext<Self>,
 9603    ) -> Task<Result<Navigated>> {
 9604        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9605    }
 9606
 9607    pub fn go_to_definition_split(
 9608        &mut self,
 9609        _: &GoToDefinitionSplit,
 9610        cx: &mut ViewContext<Self>,
 9611    ) -> Task<Result<Navigated>> {
 9612        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9613    }
 9614
 9615    pub fn go_to_type_definition_split(
 9616        &mut self,
 9617        _: &GoToTypeDefinitionSplit,
 9618        cx: &mut ViewContext<Self>,
 9619    ) -> Task<Result<Navigated>> {
 9620        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9621    }
 9622
 9623    fn go_to_definition_of_kind(
 9624        &mut self,
 9625        kind: GotoDefinitionKind,
 9626        split: bool,
 9627        cx: &mut ViewContext<Self>,
 9628    ) -> Task<Result<Navigated>> {
 9629        let Some(provider) = self.semantics_provider.clone() else {
 9630            return Task::ready(Ok(Navigated::No));
 9631        };
 9632        let buffer = self.buffer.read(cx);
 9633        let head = self.selections.newest::<usize>(cx).head();
 9634        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9635            text_anchor
 9636        } else {
 9637            return Task::ready(Ok(Navigated::No));
 9638        };
 9639
 9640        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9641            return Task::ready(Ok(Navigated::No));
 9642        };
 9643
 9644        cx.spawn(|editor, mut cx| async move {
 9645            let definitions = definitions.await?;
 9646            let navigated = editor
 9647                .update(&mut cx, |editor, cx| {
 9648                    editor.navigate_to_hover_links(
 9649                        Some(kind),
 9650                        definitions
 9651                            .into_iter()
 9652                            .filter(|location| {
 9653                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9654                            })
 9655                            .map(HoverLink::Text)
 9656                            .collect::<Vec<_>>(),
 9657                        split,
 9658                        cx,
 9659                    )
 9660                })?
 9661                .await?;
 9662            anyhow::Ok(navigated)
 9663        })
 9664    }
 9665
 9666    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9667        let position = self.selections.newest_anchor().head();
 9668        let Some((buffer, buffer_position)) =
 9669            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9670        else {
 9671            return;
 9672        };
 9673
 9674        cx.spawn(|editor, mut cx| async move {
 9675            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9676                editor.update(&mut cx, |_, cx| {
 9677                    cx.open_url(&url);
 9678                })
 9679            } else {
 9680                Ok(())
 9681            }
 9682        })
 9683        .detach();
 9684    }
 9685
 9686    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9687        let Some(workspace) = self.workspace() else {
 9688            return;
 9689        };
 9690
 9691        let position = self.selections.newest_anchor().head();
 9692
 9693        let Some((buffer, buffer_position)) =
 9694            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9695        else {
 9696            return;
 9697        };
 9698
 9699        let project = self.project.clone();
 9700
 9701        cx.spawn(|_, mut cx| async move {
 9702            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9703
 9704            if let Some((_, path)) = result {
 9705                workspace
 9706                    .update(&mut cx, |workspace, cx| {
 9707                        workspace.open_resolved_path(path, cx)
 9708                    })?
 9709                    .await?;
 9710            }
 9711            anyhow::Ok(())
 9712        })
 9713        .detach();
 9714    }
 9715
 9716    pub(crate) fn navigate_to_hover_links(
 9717        &mut self,
 9718        kind: Option<GotoDefinitionKind>,
 9719        mut definitions: Vec<HoverLink>,
 9720        split: bool,
 9721        cx: &mut ViewContext<Editor>,
 9722    ) -> Task<Result<Navigated>> {
 9723        // If there is one definition, just open it directly
 9724        if definitions.len() == 1 {
 9725            let definition = definitions.pop().unwrap();
 9726
 9727            enum TargetTaskResult {
 9728                Location(Option<Location>),
 9729                AlreadyNavigated,
 9730            }
 9731
 9732            let target_task = match definition {
 9733                HoverLink::Text(link) => {
 9734                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9735                }
 9736                HoverLink::InlayHint(lsp_location, server_id) => {
 9737                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9738                    cx.background_executor().spawn(async move {
 9739                        let location = computation.await?;
 9740                        Ok(TargetTaskResult::Location(location))
 9741                    })
 9742                }
 9743                HoverLink::Url(url) => {
 9744                    cx.open_url(&url);
 9745                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9746                }
 9747                HoverLink::File(path) => {
 9748                    if let Some(workspace) = self.workspace() {
 9749                        cx.spawn(|_, mut cx| async move {
 9750                            workspace
 9751                                .update(&mut cx, |workspace, cx| {
 9752                                    workspace.open_resolved_path(path, cx)
 9753                                })?
 9754                                .await
 9755                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9756                        })
 9757                    } else {
 9758                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9759                    }
 9760                }
 9761            };
 9762            cx.spawn(|editor, mut cx| async move {
 9763                let target = match target_task.await.context("target resolution task")? {
 9764                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9765                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9766                    TargetTaskResult::Location(Some(target)) => target,
 9767                };
 9768
 9769                editor.update(&mut cx, |editor, cx| {
 9770                    let Some(workspace) = editor.workspace() else {
 9771                        return Navigated::No;
 9772                    };
 9773                    let pane = workspace.read(cx).active_pane().clone();
 9774
 9775                    let range = target.range.to_offset(target.buffer.read(cx));
 9776                    let range = editor.range_for_match(&range);
 9777
 9778                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9779                        let buffer = target.buffer.read(cx);
 9780                        let range = check_multiline_range(buffer, range);
 9781                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9782                            s.select_ranges([range]);
 9783                        });
 9784                    } else {
 9785                        cx.window_context().defer(move |cx| {
 9786                            let target_editor: View<Self> =
 9787                                workspace.update(cx, |workspace, cx| {
 9788                                    let pane = if split {
 9789                                        workspace.adjacent_pane(cx)
 9790                                    } else {
 9791                                        workspace.active_pane().clone()
 9792                                    };
 9793
 9794                                    workspace.open_project_item(
 9795                                        pane,
 9796                                        target.buffer.clone(),
 9797                                        true,
 9798                                        true,
 9799                                        cx,
 9800                                    )
 9801                                });
 9802                            target_editor.update(cx, |target_editor, cx| {
 9803                                // When selecting a definition in a different buffer, disable the nav history
 9804                                // to avoid creating a history entry at the previous cursor location.
 9805                                pane.update(cx, |pane, _| pane.disable_history());
 9806                                let buffer = target.buffer.read(cx);
 9807                                let range = check_multiline_range(buffer, range);
 9808                                target_editor.change_selections(
 9809                                    Some(Autoscroll::focused()),
 9810                                    cx,
 9811                                    |s| {
 9812                                        s.select_ranges([range]);
 9813                                    },
 9814                                );
 9815                                pane.update(cx, |pane, _| pane.enable_history());
 9816                            });
 9817                        });
 9818                    }
 9819                    Navigated::Yes
 9820                })
 9821            })
 9822        } else if !definitions.is_empty() {
 9823            cx.spawn(|editor, mut cx| async move {
 9824                let (title, location_tasks, workspace) = editor
 9825                    .update(&mut cx, |editor, cx| {
 9826                        let tab_kind = match kind {
 9827                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9828                            _ => "Definitions",
 9829                        };
 9830                        let title = definitions
 9831                            .iter()
 9832                            .find_map(|definition| match definition {
 9833                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9834                                    let buffer = origin.buffer.read(cx);
 9835                                    format!(
 9836                                        "{} for {}",
 9837                                        tab_kind,
 9838                                        buffer
 9839                                            .text_for_range(origin.range.clone())
 9840                                            .collect::<String>()
 9841                                    )
 9842                                }),
 9843                                HoverLink::InlayHint(_, _) => None,
 9844                                HoverLink::Url(_) => None,
 9845                                HoverLink::File(_) => None,
 9846                            })
 9847                            .unwrap_or(tab_kind.to_string());
 9848                        let location_tasks = definitions
 9849                            .into_iter()
 9850                            .map(|definition| match definition {
 9851                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9852                                HoverLink::InlayHint(lsp_location, server_id) => {
 9853                                    editor.compute_target_location(lsp_location, server_id, cx)
 9854                                }
 9855                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9856                                HoverLink::File(_) => Task::ready(Ok(None)),
 9857                            })
 9858                            .collect::<Vec<_>>();
 9859                        (title, location_tasks, editor.workspace().clone())
 9860                    })
 9861                    .context("location tasks preparation")?;
 9862
 9863                let locations = future::join_all(location_tasks)
 9864                    .await
 9865                    .into_iter()
 9866                    .filter_map(|location| location.transpose())
 9867                    .collect::<Result<_>>()
 9868                    .context("location tasks")?;
 9869
 9870                let Some(workspace) = workspace else {
 9871                    return Ok(Navigated::No);
 9872                };
 9873                let opened = workspace
 9874                    .update(&mut cx, |workspace, cx| {
 9875                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9876                    })
 9877                    .ok();
 9878
 9879                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9880            })
 9881        } else {
 9882            Task::ready(Ok(Navigated::No))
 9883        }
 9884    }
 9885
 9886    fn compute_target_location(
 9887        &self,
 9888        lsp_location: lsp::Location,
 9889        server_id: LanguageServerId,
 9890        cx: &mut ViewContext<Self>,
 9891    ) -> Task<anyhow::Result<Option<Location>>> {
 9892        let Some(project) = self.project.clone() else {
 9893            return Task::Ready(Some(Ok(None)));
 9894        };
 9895
 9896        cx.spawn(move |editor, mut cx| async move {
 9897            let location_task = editor.update(&mut cx, |_, cx| {
 9898                project.update(cx, |project, cx| {
 9899                    let language_server_name = project
 9900                        .language_server_statuses(cx)
 9901                        .find(|(id, _)| server_id == *id)
 9902                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9903                    language_server_name.map(|language_server_name| {
 9904                        project.open_local_buffer_via_lsp(
 9905                            lsp_location.uri.clone(),
 9906                            server_id,
 9907                            language_server_name,
 9908                            cx,
 9909                        )
 9910                    })
 9911                })
 9912            })?;
 9913            let location = match location_task {
 9914                Some(task) => Some({
 9915                    let target_buffer_handle = task.await.context("open local buffer")?;
 9916                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9917                        let target_start = target_buffer
 9918                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9919                        let target_end = target_buffer
 9920                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9921                        target_buffer.anchor_after(target_start)
 9922                            ..target_buffer.anchor_before(target_end)
 9923                    })?;
 9924                    Location {
 9925                        buffer: target_buffer_handle,
 9926                        range,
 9927                    }
 9928                }),
 9929                None => None,
 9930            };
 9931            Ok(location)
 9932        })
 9933    }
 9934
 9935    pub fn find_all_references(
 9936        &mut self,
 9937        _: &FindAllReferences,
 9938        cx: &mut ViewContext<Self>,
 9939    ) -> Option<Task<Result<Navigated>>> {
 9940        let multi_buffer = self.buffer.read(cx);
 9941        let selection = self.selections.newest::<usize>(cx);
 9942        let head = selection.head();
 9943
 9944        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9945        let head_anchor = multi_buffer_snapshot.anchor_at(
 9946            head,
 9947            if head < selection.tail() {
 9948                Bias::Right
 9949            } else {
 9950                Bias::Left
 9951            },
 9952        );
 9953
 9954        match self
 9955            .find_all_references_task_sources
 9956            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9957        {
 9958            Ok(_) => {
 9959                log::info!(
 9960                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9961                );
 9962                return None;
 9963            }
 9964            Err(i) => {
 9965                self.find_all_references_task_sources.insert(i, head_anchor);
 9966            }
 9967        }
 9968
 9969        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9970        let workspace = self.workspace()?;
 9971        let project = workspace.read(cx).project().clone();
 9972        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9973        Some(cx.spawn(|editor, mut cx| async move {
 9974            let _cleanup = defer({
 9975                let mut cx = cx.clone();
 9976                move || {
 9977                    let _ = editor.update(&mut cx, |editor, _| {
 9978                        if let Ok(i) =
 9979                            editor
 9980                                .find_all_references_task_sources
 9981                                .binary_search_by(|anchor| {
 9982                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9983                                })
 9984                        {
 9985                            editor.find_all_references_task_sources.remove(i);
 9986                        }
 9987                    });
 9988                }
 9989            });
 9990
 9991            let locations = references.await?;
 9992            if locations.is_empty() {
 9993                return anyhow::Ok(Navigated::No);
 9994            }
 9995
 9996            workspace.update(&mut cx, |workspace, cx| {
 9997                let title = locations
 9998                    .first()
 9999                    .as_ref()
10000                    .map(|location| {
10001                        let buffer = location.buffer.read(cx);
10002                        format!(
10003                            "References to `{}`",
10004                            buffer
10005                                .text_for_range(location.range.clone())
10006                                .collect::<String>()
10007                        )
10008                    })
10009                    .unwrap();
10010                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10011                Navigated::Yes
10012            })
10013        }))
10014    }
10015
10016    /// Opens a multibuffer with the given project locations in it
10017    pub fn open_locations_in_multibuffer(
10018        workspace: &mut Workspace,
10019        mut locations: Vec<Location>,
10020        title: String,
10021        split: bool,
10022        cx: &mut ViewContext<Workspace>,
10023    ) {
10024        // If there are multiple definitions, open them in a multibuffer
10025        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10026        let mut locations = locations.into_iter().peekable();
10027        let mut ranges_to_highlight = Vec::new();
10028        let capability = workspace.project().read(cx).capability();
10029
10030        let excerpt_buffer = cx.new_model(|cx| {
10031            let mut multibuffer = MultiBuffer::new(capability);
10032            while let Some(location) = locations.next() {
10033                let buffer = location.buffer.read(cx);
10034                let mut ranges_for_buffer = Vec::new();
10035                let range = location.range.to_offset(buffer);
10036                ranges_for_buffer.push(range.clone());
10037
10038                while let Some(next_location) = locations.peek() {
10039                    if next_location.buffer == location.buffer {
10040                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10041                        locations.next();
10042                    } else {
10043                        break;
10044                    }
10045                }
10046
10047                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10048                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10049                    location.buffer.clone(),
10050                    ranges_for_buffer,
10051                    DEFAULT_MULTIBUFFER_CONTEXT,
10052                    cx,
10053                ))
10054            }
10055
10056            multibuffer.with_title(title)
10057        });
10058
10059        let editor = cx.new_view(|cx| {
10060            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10061        });
10062        editor.update(cx, |editor, cx| {
10063            if let Some(first_range) = ranges_to_highlight.first() {
10064                editor.change_selections(None, cx, |selections| {
10065                    selections.clear_disjoint();
10066                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10067                });
10068            }
10069            editor.highlight_background::<Self>(
10070                &ranges_to_highlight,
10071                |theme| theme.editor_highlighted_line_background,
10072                cx,
10073            );
10074        });
10075
10076        let item = Box::new(editor);
10077        let item_id = item.item_id();
10078
10079        if split {
10080            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10081        } else {
10082            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10083                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10084                    pane.close_current_preview_item(cx)
10085                } else {
10086                    None
10087                }
10088            });
10089            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10090        }
10091        workspace.active_pane().update(cx, |pane, cx| {
10092            pane.set_preview_item_id(Some(item_id), cx);
10093        });
10094    }
10095
10096    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10097        use language::ToOffset as _;
10098
10099        let provider = self.semantics_provider.clone()?;
10100        let selection = self.selections.newest_anchor().clone();
10101        let (cursor_buffer, cursor_buffer_position) = self
10102            .buffer
10103            .read(cx)
10104            .text_anchor_for_position(selection.head(), cx)?;
10105        let (tail_buffer, cursor_buffer_position_end) = self
10106            .buffer
10107            .read(cx)
10108            .text_anchor_for_position(selection.tail(), cx)?;
10109        if tail_buffer != cursor_buffer {
10110            return None;
10111        }
10112
10113        let snapshot = cursor_buffer.read(cx).snapshot();
10114        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10115        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10116        let prepare_rename = provider
10117            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10118            .unwrap_or_else(|| Task::ready(Ok(None)));
10119        drop(snapshot);
10120
10121        Some(cx.spawn(|this, mut cx| async move {
10122            let rename_range = if let Some(range) = prepare_rename.await? {
10123                Some(range)
10124            } else {
10125                this.update(&mut cx, |this, cx| {
10126                    let buffer = this.buffer.read(cx).snapshot(cx);
10127                    let mut buffer_highlights = this
10128                        .document_highlights_for_position(selection.head(), &buffer)
10129                        .filter(|highlight| {
10130                            highlight.start.excerpt_id == selection.head().excerpt_id
10131                                && highlight.end.excerpt_id == selection.head().excerpt_id
10132                        });
10133                    buffer_highlights
10134                        .next()
10135                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10136                })?
10137            };
10138            if let Some(rename_range) = rename_range {
10139                this.update(&mut cx, |this, cx| {
10140                    let snapshot = cursor_buffer.read(cx).snapshot();
10141                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10142                    let cursor_offset_in_rename_range =
10143                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10144                    let cursor_offset_in_rename_range_end =
10145                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10146
10147                    this.take_rename(false, cx);
10148                    let buffer = this.buffer.read(cx).read(cx);
10149                    let cursor_offset = selection.head().to_offset(&buffer);
10150                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10151                    let rename_end = rename_start + rename_buffer_range.len();
10152                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10153                    let mut old_highlight_id = None;
10154                    let old_name: Arc<str> = buffer
10155                        .chunks(rename_start..rename_end, true)
10156                        .map(|chunk| {
10157                            if old_highlight_id.is_none() {
10158                                old_highlight_id = chunk.syntax_highlight_id;
10159                            }
10160                            chunk.text
10161                        })
10162                        .collect::<String>()
10163                        .into();
10164
10165                    drop(buffer);
10166
10167                    // Position the selection in the rename editor so that it matches the current selection.
10168                    this.show_local_selections = false;
10169                    let rename_editor = cx.new_view(|cx| {
10170                        let mut editor = Editor::single_line(cx);
10171                        editor.buffer.update(cx, |buffer, cx| {
10172                            buffer.edit([(0..0, old_name.clone())], None, cx)
10173                        });
10174                        let rename_selection_range = match cursor_offset_in_rename_range
10175                            .cmp(&cursor_offset_in_rename_range_end)
10176                        {
10177                            Ordering::Equal => {
10178                                editor.select_all(&SelectAll, cx);
10179                                return editor;
10180                            }
10181                            Ordering::Less => {
10182                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10183                            }
10184                            Ordering::Greater => {
10185                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10186                            }
10187                        };
10188                        if rename_selection_range.end > old_name.len() {
10189                            editor.select_all(&SelectAll, cx);
10190                        } else {
10191                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10192                                s.select_ranges([rename_selection_range]);
10193                            });
10194                        }
10195                        editor
10196                    });
10197                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10198                        if e == &EditorEvent::Focused {
10199                            cx.emit(EditorEvent::FocusedIn)
10200                        }
10201                    })
10202                    .detach();
10203
10204                    let write_highlights =
10205                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10206                    let read_highlights =
10207                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10208                    let ranges = write_highlights
10209                        .iter()
10210                        .flat_map(|(_, ranges)| ranges.iter())
10211                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10212                        .cloned()
10213                        .collect();
10214
10215                    this.highlight_text::<Rename>(
10216                        ranges,
10217                        HighlightStyle {
10218                            fade_out: Some(0.6),
10219                            ..Default::default()
10220                        },
10221                        cx,
10222                    );
10223                    let rename_focus_handle = rename_editor.focus_handle(cx);
10224                    cx.focus(&rename_focus_handle);
10225                    let block_id = this.insert_blocks(
10226                        [BlockProperties {
10227                            style: BlockStyle::Flex,
10228                            placement: BlockPlacement::Below(range.start),
10229                            height: 1,
10230                            render: Box::new({
10231                                let rename_editor = rename_editor.clone();
10232                                move |cx: &mut BlockContext| {
10233                                    let mut text_style = cx.editor_style.text.clone();
10234                                    if let Some(highlight_style) = old_highlight_id
10235                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10236                                    {
10237                                        text_style = text_style.highlight(highlight_style);
10238                                    }
10239                                    div()
10240                                        .pl(cx.anchor_x)
10241                                        .child(EditorElement::new(
10242                                            &rename_editor,
10243                                            EditorStyle {
10244                                                background: cx.theme().system().transparent,
10245                                                local_player: cx.editor_style.local_player,
10246                                                text: text_style,
10247                                                scrollbar_width: cx.editor_style.scrollbar_width,
10248                                                syntax: cx.editor_style.syntax.clone(),
10249                                                status: cx.editor_style.status.clone(),
10250                                                inlay_hints_style: HighlightStyle {
10251                                                    font_weight: Some(FontWeight::BOLD),
10252                                                    ..make_inlay_hints_style(cx)
10253                                                },
10254                                                suggestions_style: HighlightStyle {
10255                                                    color: Some(cx.theme().status().predictive),
10256                                                    ..HighlightStyle::default()
10257                                                },
10258                                                ..EditorStyle::default()
10259                                            },
10260                                        ))
10261                                        .into_any_element()
10262                                }
10263                            }),
10264                            priority: 0,
10265                        }],
10266                        Some(Autoscroll::fit()),
10267                        cx,
10268                    )[0];
10269                    this.pending_rename = Some(RenameState {
10270                        range,
10271                        old_name,
10272                        editor: rename_editor,
10273                        block_id,
10274                    });
10275                })?;
10276            }
10277
10278            Ok(())
10279        }))
10280    }
10281
10282    pub fn confirm_rename(
10283        &mut self,
10284        _: &ConfirmRename,
10285        cx: &mut ViewContext<Self>,
10286    ) -> Option<Task<Result<()>>> {
10287        let rename = self.take_rename(false, cx)?;
10288        let workspace = self.workspace()?.downgrade();
10289        let (buffer, start) = self
10290            .buffer
10291            .read(cx)
10292            .text_anchor_for_position(rename.range.start, cx)?;
10293        let (end_buffer, _) = self
10294            .buffer
10295            .read(cx)
10296            .text_anchor_for_position(rename.range.end, cx)?;
10297        if buffer != end_buffer {
10298            return None;
10299        }
10300
10301        let old_name = rename.old_name;
10302        let new_name = rename.editor.read(cx).text(cx);
10303
10304        let rename = self.semantics_provider.as_ref()?.perform_rename(
10305            &buffer,
10306            start,
10307            new_name.clone(),
10308            cx,
10309        )?;
10310
10311        Some(cx.spawn(|editor, mut cx| async move {
10312            let project_transaction = rename.await?;
10313            Self::open_project_transaction(
10314                &editor,
10315                workspace,
10316                project_transaction,
10317                format!("Rename: {}{}", old_name, new_name),
10318                cx.clone(),
10319            )
10320            .await?;
10321
10322            editor.update(&mut cx, |editor, cx| {
10323                editor.refresh_document_highlights(cx);
10324            })?;
10325            Ok(())
10326        }))
10327    }
10328
10329    fn take_rename(
10330        &mut self,
10331        moving_cursor: bool,
10332        cx: &mut ViewContext<Self>,
10333    ) -> Option<RenameState> {
10334        let rename = self.pending_rename.take()?;
10335        if rename.editor.focus_handle(cx).is_focused(cx) {
10336            cx.focus(&self.focus_handle);
10337        }
10338
10339        self.remove_blocks(
10340            [rename.block_id].into_iter().collect(),
10341            Some(Autoscroll::fit()),
10342            cx,
10343        );
10344        self.clear_highlights::<Rename>(cx);
10345        self.show_local_selections = true;
10346
10347        if moving_cursor {
10348            let rename_editor = rename.editor.read(cx);
10349            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10350
10351            // Update the selection to match the position of the selection inside
10352            // the rename editor.
10353            let snapshot = self.buffer.read(cx).read(cx);
10354            let rename_range = rename.range.to_offset(&snapshot);
10355            let cursor_in_editor = snapshot
10356                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10357                .min(rename_range.end);
10358            drop(snapshot);
10359
10360            self.change_selections(None, cx, |s| {
10361                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10362            });
10363        } else {
10364            self.refresh_document_highlights(cx);
10365        }
10366
10367        Some(rename)
10368    }
10369
10370    pub fn pending_rename(&self) -> Option<&RenameState> {
10371        self.pending_rename.as_ref()
10372    }
10373
10374    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10375        let project = match &self.project {
10376            Some(project) => project.clone(),
10377            None => return None,
10378        };
10379
10380        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10381    }
10382
10383    fn format_selections(
10384        &mut self,
10385        _: &FormatSelections,
10386        cx: &mut ViewContext<Self>,
10387    ) -> Option<Task<Result<()>>> {
10388        let project = match &self.project {
10389            Some(project) => project.clone(),
10390            None => return None,
10391        };
10392
10393        let selections = self
10394            .selections
10395            .all_adjusted(cx)
10396            .into_iter()
10397            .filter(|s| !s.is_empty())
10398            .collect_vec();
10399
10400        Some(self.perform_format(
10401            project,
10402            FormatTrigger::Manual,
10403            FormatTarget::Ranges(selections),
10404            cx,
10405        ))
10406    }
10407
10408    fn perform_format(
10409        &mut self,
10410        project: Model<Project>,
10411        trigger: FormatTrigger,
10412        target: FormatTarget,
10413        cx: &mut ViewContext<Self>,
10414    ) -> Task<Result<()>> {
10415        let buffer = self.buffer().clone();
10416        let mut buffers = buffer.read(cx).all_buffers();
10417        if trigger == FormatTrigger::Save {
10418            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10419        }
10420
10421        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10422        let format = project.update(cx, |project, cx| {
10423            project.format(buffers, true, trigger, target, cx)
10424        });
10425
10426        cx.spawn(|_, mut cx| async move {
10427            let transaction = futures::select_biased! {
10428                () = timeout => {
10429                    log::warn!("timed out waiting for formatting");
10430                    None
10431                }
10432                transaction = format.log_err().fuse() => transaction,
10433            };
10434
10435            buffer
10436                .update(&mut cx, |buffer, cx| {
10437                    if let Some(transaction) = transaction {
10438                        if !buffer.is_singleton() {
10439                            buffer.push_transaction(&transaction.0, cx);
10440                        }
10441                    }
10442
10443                    cx.notify();
10444                })
10445                .ok();
10446
10447            Ok(())
10448        })
10449    }
10450
10451    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10452        if let Some(project) = self.project.clone() {
10453            self.buffer.update(cx, |multi_buffer, cx| {
10454                project.update(cx, |project, cx| {
10455                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10456                });
10457            })
10458        }
10459    }
10460
10461    fn cancel_language_server_work(
10462        &mut self,
10463        _: &CancelLanguageServerWork,
10464        cx: &mut ViewContext<Self>,
10465    ) {
10466        if let Some(project) = self.project.clone() {
10467            self.buffer.update(cx, |multi_buffer, cx| {
10468                project.update(cx, |project, cx| {
10469                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10470                });
10471            })
10472        }
10473    }
10474
10475    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10476        cx.show_character_palette();
10477    }
10478
10479    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10480        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10481            let buffer = self.buffer.read(cx).snapshot(cx);
10482            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10483            let is_valid = buffer
10484                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10485                .any(|entry| {
10486                    entry.diagnostic.is_primary
10487                        && !entry.range.is_empty()
10488                        && entry.range.start == primary_range_start
10489                        && entry.diagnostic.message == active_diagnostics.primary_message
10490                });
10491
10492            if is_valid != active_diagnostics.is_valid {
10493                active_diagnostics.is_valid = is_valid;
10494                let mut new_styles = HashMap::default();
10495                for (block_id, diagnostic) in &active_diagnostics.blocks {
10496                    new_styles.insert(
10497                        *block_id,
10498                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10499                    );
10500                }
10501                self.display_map.update(cx, |display_map, _cx| {
10502                    display_map.replace_blocks(new_styles)
10503                });
10504            }
10505        }
10506    }
10507
10508    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10509        self.dismiss_diagnostics(cx);
10510        let snapshot = self.snapshot(cx);
10511        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10512            let buffer = self.buffer.read(cx).snapshot(cx);
10513
10514            let mut primary_range = None;
10515            let mut primary_message = None;
10516            let mut group_end = Point::zero();
10517            let diagnostic_group = buffer
10518                .diagnostic_group::<MultiBufferPoint>(group_id)
10519                .filter_map(|entry| {
10520                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10521                        && (entry.range.start.row == entry.range.end.row
10522                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10523                    {
10524                        return None;
10525                    }
10526                    if entry.range.end > group_end {
10527                        group_end = entry.range.end;
10528                    }
10529                    if entry.diagnostic.is_primary {
10530                        primary_range = Some(entry.range.clone());
10531                        primary_message = Some(entry.diagnostic.message.clone());
10532                    }
10533                    Some(entry)
10534                })
10535                .collect::<Vec<_>>();
10536            let primary_range = primary_range?;
10537            let primary_message = primary_message?;
10538            let primary_range =
10539                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10540
10541            let blocks = display_map
10542                .insert_blocks(
10543                    diagnostic_group.iter().map(|entry| {
10544                        let diagnostic = entry.diagnostic.clone();
10545                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10546                        BlockProperties {
10547                            style: BlockStyle::Fixed,
10548                            placement: BlockPlacement::Below(
10549                                buffer.anchor_after(entry.range.start),
10550                            ),
10551                            height: message_height,
10552                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10553                            priority: 0,
10554                        }
10555                    }),
10556                    cx,
10557                )
10558                .into_iter()
10559                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10560                .collect();
10561
10562            Some(ActiveDiagnosticGroup {
10563                primary_range,
10564                primary_message,
10565                group_id,
10566                blocks,
10567                is_valid: true,
10568            })
10569        });
10570        self.active_diagnostics.is_some()
10571    }
10572
10573    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10574        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10575            self.display_map.update(cx, |display_map, cx| {
10576                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10577            });
10578            cx.notify();
10579        }
10580    }
10581
10582    pub fn set_selections_from_remote(
10583        &mut self,
10584        selections: Vec<Selection<Anchor>>,
10585        pending_selection: Option<Selection<Anchor>>,
10586        cx: &mut ViewContext<Self>,
10587    ) {
10588        let old_cursor_position = self.selections.newest_anchor().head();
10589        self.selections.change_with(cx, |s| {
10590            s.select_anchors(selections);
10591            if let Some(pending_selection) = pending_selection {
10592                s.set_pending(pending_selection, SelectMode::Character);
10593            } else {
10594                s.clear_pending();
10595            }
10596        });
10597        self.selections_did_change(false, &old_cursor_position, true, cx);
10598    }
10599
10600    fn push_to_selection_history(&mut self) {
10601        self.selection_history.push(SelectionHistoryEntry {
10602            selections: self.selections.disjoint_anchors(),
10603            select_next_state: self.select_next_state.clone(),
10604            select_prev_state: self.select_prev_state.clone(),
10605            add_selections_state: self.add_selections_state.clone(),
10606        });
10607    }
10608
10609    pub fn transact(
10610        &mut self,
10611        cx: &mut ViewContext<Self>,
10612        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10613    ) -> Option<TransactionId> {
10614        self.start_transaction_at(Instant::now(), cx);
10615        update(self, cx);
10616        self.end_transaction_at(Instant::now(), cx)
10617    }
10618
10619    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10620        self.end_selection(cx);
10621        if let Some(tx_id) = self
10622            .buffer
10623            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10624        {
10625            self.selection_history
10626                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10627            cx.emit(EditorEvent::TransactionBegun {
10628                transaction_id: tx_id,
10629            })
10630        }
10631    }
10632
10633    fn end_transaction_at(
10634        &mut self,
10635        now: Instant,
10636        cx: &mut ViewContext<Self>,
10637    ) -> Option<TransactionId> {
10638        if let Some(transaction_id) = self
10639            .buffer
10640            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10641        {
10642            if let Some((_, end_selections)) =
10643                self.selection_history.transaction_mut(transaction_id)
10644            {
10645                *end_selections = Some(self.selections.disjoint_anchors());
10646            } else {
10647                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10648            }
10649
10650            cx.emit(EditorEvent::Edited { transaction_id });
10651            Some(transaction_id)
10652        } else {
10653            None
10654        }
10655    }
10656
10657    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10658        let selection = self.selections.newest::<Point>(cx);
10659
10660        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10661        let range = if selection.is_empty() {
10662            let point = selection.head().to_display_point(&display_map);
10663            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10664            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10665                .to_point(&display_map);
10666            start..end
10667        } else {
10668            selection.range()
10669        };
10670        if display_map.folds_in_range(range).next().is_some() {
10671            self.unfold_lines(&Default::default(), cx)
10672        } else {
10673            self.fold(&Default::default(), cx)
10674        }
10675    }
10676
10677    pub fn toggle_fold_recursive(
10678        &mut self,
10679        _: &actions::ToggleFoldRecursive,
10680        cx: &mut ViewContext<Self>,
10681    ) {
10682        let selection = self.selections.newest::<Point>(cx);
10683
10684        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10685        let range = if selection.is_empty() {
10686            let point = selection.head().to_display_point(&display_map);
10687            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10688            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10689                .to_point(&display_map);
10690            start..end
10691        } else {
10692            selection.range()
10693        };
10694        if display_map.folds_in_range(range).next().is_some() {
10695            self.unfold_recursive(&Default::default(), cx)
10696        } else {
10697            self.fold_recursive(&Default::default(), cx)
10698        }
10699    }
10700
10701    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10702        let mut fold_ranges = Vec::new();
10703        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10704        let selections = self.selections.all_adjusted(cx);
10705
10706        for selection in selections {
10707            let range = selection.range().sorted();
10708            let buffer_start_row = range.start.row;
10709
10710            if range.start.row != range.end.row {
10711                let mut found = false;
10712                let mut row = range.start.row;
10713                while row <= range.end.row {
10714                    if let Some((foldable_range, fold_text)) =
10715                        { display_map.foldable_range(MultiBufferRow(row)) }
10716                    {
10717                        found = true;
10718                        row = foldable_range.end.row + 1;
10719                        fold_ranges.push((foldable_range, fold_text));
10720                    } else {
10721                        row += 1
10722                    }
10723                }
10724                if found {
10725                    continue;
10726                }
10727            }
10728
10729            for row in (0..=range.start.row).rev() {
10730                if let Some((foldable_range, fold_text)) =
10731                    display_map.foldable_range(MultiBufferRow(row))
10732                {
10733                    if foldable_range.end.row >= buffer_start_row {
10734                        fold_ranges.push((foldable_range, fold_text));
10735                        if row <= range.start.row {
10736                            break;
10737                        }
10738                    }
10739                }
10740            }
10741        }
10742
10743        self.fold_ranges(fold_ranges, true, cx);
10744    }
10745
10746    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10747        let fold_at_level = fold_at.level;
10748        let snapshot = self.buffer.read(cx).snapshot(cx);
10749        let mut fold_ranges = Vec::new();
10750        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10751
10752        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10753            while start_row < end_row {
10754                match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10755                    Some(foldable_range) => {
10756                        let nested_start_row = foldable_range.0.start.row + 1;
10757                        let nested_end_row = foldable_range.0.end.row;
10758
10759                        if current_level == fold_at_level {
10760                            fold_ranges.push(foldable_range);
10761                        }
10762
10763                        if current_level <= fold_at_level {
10764                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10765                        }
10766
10767                        start_row = nested_end_row + 1;
10768                    }
10769                    None => start_row += 1,
10770                }
10771            }
10772        }
10773
10774        self.fold_ranges(fold_ranges, true, cx);
10775    }
10776
10777    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10778        let mut fold_ranges = Vec::new();
10779        let snapshot = self.buffer.read(cx).snapshot(cx);
10780
10781        for row in 0..snapshot.max_buffer_row().0 {
10782            if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10783                fold_ranges.push(foldable_range);
10784            }
10785        }
10786
10787        self.fold_ranges(fold_ranges, true, cx);
10788    }
10789
10790    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10791        let mut fold_ranges = Vec::new();
10792        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10793        let selections = self.selections.all_adjusted(cx);
10794
10795        for selection in selections {
10796            let range = selection.range().sorted();
10797            let buffer_start_row = range.start.row;
10798
10799            if range.start.row != range.end.row {
10800                let mut found = false;
10801                for row in range.start.row..=range.end.row {
10802                    if let Some((foldable_range, fold_text)) =
10803                        { display_map.foldable_range(MultiBufferRow(row)) }
10804                    {
10805                        found = true;
10806                        fold_ranges.push((foldable_range, fold_text));
10807                    }
10808                }
10809                if found {
10810                    continue;
10811                }
10812            }
10813
10814            for row in (0..=range.start.row).rev() {
10815                if let Some((foldable_range, fold_text)) =
10816                    display_map.foldable_range(MultiBufferRow(row))
10817                {
10818                    if foldable_range.end.row >= buffer_start_row {
10819                        fold_ranges.push((foldable_range, fold_text));
10820                    } else {
10821                        break;
10822                    }
10823                }
10824            }
10825        }
10826
10827        self.fold_ranges(fold_ranges, true, cx);
10828    }
10829
10830    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10831        let buffer_row = fold_at.buffer_row;
10832        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10833
10834        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10835            let autoscroll = self
10836                .selections
10837                .all::<Point>(cx)
10838                .iter()
10839                .any(|selection| fold_range.overlaps(&selection.range()));
10840
10841            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10842        }
10843    }
10844
10845    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10846        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10847        let buffer = &display_map.buffer_snapshot;
10848        let selections = self.selections.all::<Point>(cx);
10849        let ranges = selections
10850            .iter()
10851            .map(|s| {
10852                let range = s.display_range(&display_map).sorted();
10853                let mut start = range.start.to_point(&display_map);
10854                let mut end = range.end.to_point(&display_map);
10855                start.column = 0;
10856                end.column = buffer.line_len(MultiBufferRow(end.row));
10857                start..end
10858            })
10859            .collect::<Vec<_>>();
10860
10861        self.unfold_ranges(ranges, true, true, cx);
10862    }
10863
10864    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10865        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10866        let selections = self.selections.all::<Point>(cx);
10867        let ranges = selections
10868            .iter()
10869            .map(|s| {
10870                let mut range = s.display_range(&display_map).sorted();
10871                *range.start.column_mut() = 0;
10872                *range.end.column_mut() = display_map.line_len(range.end.row());
10873                let start = range.start.to_point(&display_map);
10874                let end = range.end.to_point(&display_map);
10875                start..end
10876            })
10877            .collect::<Vec<_>>();
10878
10879        self.unfold_ranges(ranges, true, true, cx);
10880    }
10881
10882    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10883        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10884
10885        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10886            ..Point::new(
10887                unfold_at.buffer_row.0,
10888                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10889            );
10890
10891        let autoscroll = self
10892            .selections
10893            .all::<Point>(cx)
10894            .iter()
10895            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10896
10897        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10898    }
10899
10900    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10901        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10902        self.unfold_ranges(
10903            [Point::zero()..display_map.max_point().to_point(&display_map)],
10904            true,
10905            true,
10906            cx,
10907        );
10908    }
10909
10910    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10911        let selections = self.selections.all::<Point>(cx);
10912        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10913        let line_mode = self.selections.line_mode;
10914        let ranges = selections.into_iter().map(|s| {
10915            if line_mode {
10916                let start = Point::new(s.start.row, 0);
10917                let end = Point::new(
10918                    s.end.row,
10919                    display_map
10920                        .buffer_snapshot
10921                        .line_len(MultiBufferRow(s.end.row)),
10922                );
10923                (start..end, display_map.fold_placeholder.clone())
10924            } else {
10925                (s.start..s.end, display_map.fold_placeholder.clone())
10926            }
10927        });
10928        self.fold_ranges(ranges, true, cx);
10929    }
10930
10931    pub fn fold_ranges<T: ToOffset + Clone>(
10932        &mut self,
10933        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10934        auto_scroll: bool,
10935        cx: &mut ViewContext<Self>,
10936    ) {
10937        let mut fold_ranges = Vec::new();
10938        let mut buffers_affected = HashMap::default();
10939        let multi_buffer = self.buffer().read(cx);
10940        for (fold_range, fold_text) in ranges {
10941            if let Some((_, buffer, _)) =
10942                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10943            {
10944                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10945            };
10946            fold_ranges.push((fold_range, fold_text));
10947        }
10948
10949        let mut ranges = fold_ranges.into_iter().peekable();
10950        if ranges.peek().is_some() {
10951            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10952
10953            if auto_scroll {
10954                self.request_autoscroll(Autoscroll::fit(), cx);
10955            }
10956
10957            for buffer in buffers_affected.into_values() {
10958                self.sync_expanded_diff_hunks(buffer, cx);
10959            }
10960
10961            cx.notify();
10962
10963            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10964                // Clear diagnostics block when folding a range that contains it.
10965                let snapshot = self.snapshot(cx);
10966                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10967                    drop(snapshot);
10968                    self.active_diagnostics = Some(active_diagnostics);
10969                    self.dismiss_diagnostics(cx);
10970                } else {
10971                    self.active_diagnostics = Some(active_diagnostics);
10972                }
10973            }
10974
10975            self.scrollbar_marker_state.dirty = true;
10976        }
10977    }
10978
10979    pub fn unfold_ranges<T: ToOffset + Clone>(
10980        &mut self,
10981        ranges: impl IntoIterator<Item = Range<T>>,
10982        inclusive: bool,
10983        auto_scroll: bool,
10984        cx: &mut ViewContext<Self>,
10985    ) {
10986        let mut unfold_ranges = Vec::new();
10987        let mut buffers_affected = HashMap::default();
10988        let multi_buffer = self.buffer().read(cx);
10989        for range in ranges {
10990            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10991                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10992            };
10993            unfold_ranges.push(range);
10994        }
10995
10996        let mut ranges = unfold_ranges.into_iter().peekable();
10997        if ranges.peek().is_some() {
10998            self.display_map
10999                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
11000            if auto_scroll {
11001                self.request_autoscroll(Autoscroll::fit(), cx);
11002            }
11003
11004            for buffer in buffers_affected.into_values() {
11005                self.sync_expanded_diff_hunks(buffer, cx);
11006            }
11007
11008            cx.notify();
11009            self.scrollbar_marker_state.dirty = true;
11010            self.active_indent_guides_state.dirty = true;
11011        }
11012    }
11013
11014    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11015        self.display_map.read(cx).fold_placeholder.clone()
11016    }
11017
11018    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11019        if hovered != self.gutter_hovered {
11020            self.gutter_hovered = hovered;
11021            cx.notify();
11022        }
11023    }
11024
11025    pub fn insert_blocks(
11026        &mut self,
11027        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11028        autoscroll: Option<Autoscroll>,
11029        cx: &mut ViewContext<Self>,
11030    ) -> Vec<CustomBlockId> {
11031        let blocks = self
11032            .display_map
11033            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11034        if let Some(autoscroll) = autoscroll {
11035            self.request_autoscroll(autoscroll, cx);
11036        }
11037        cx.notify();
11038        blocks
11039    }
11040
11041    pub fn resize_blocks(
11042        &mut self,
11043        heights: HashMap<CustomBlockId, u32>,
11044        autoscroll: Option<Autoscroll>,
11045        cx: &mut ViewContext<Self>,
11046    ) {
11047        self.display_map
11048            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11049        if let Some(autoscroll) = autoscroll {
11050            self.request_autoscroll(autoscroll, cx);
11051        }
11052        cx.notify();
11053    }
11054
11055    pub fn replace_blocks(
11056        &mut self,
11057        renderers: HashMap<CustomBlockId, RenderBlock>,
11058        autoscroll: Option<Autoscroll>,
11059        cx: &mut ViewContext<Self>,
11060    ) {
11061        self.display_map
11062            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11063        if let Some(autoscroll) = autoscroll {
11064            self.request_autoscroll(autoscroll, cx);
11065        }
11066        cx.notify();
11067    }
11068
11069    pub fn remove_blocks(
11070        &mut self,
11071        block_ids: HashSet<CustomBlockId>,
11072        autoscroll: Option<Autoscroll>,
11073        cx: &mut ViewContext<Self>,
11074    ) {
11075        self.display_map.update(cx, |display_map, cx| {
11076            display_map.remove_blocks(block_ids, cx)
11077        });
11078        if let Some(autoscroll) = autoscroll {
11079            self.request_autoscroll(autoscroll, cx);
11080        }
11081        cx.notify();
11082    }
11083
11084    pub fn row_for_block(
11085        &self,
11086        block_id: CustomBlockId,
11087        cx: &mut ViewContext<Self>,
11088    ) -> Option<DisplayRow> {
11089        self.display_map
11090            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11091    }
11092
11093    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11094        self.focused_block = Some(focused_block);
11095    }
11096
11097    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11098        self.focused_block.take()
11099    }
11100
11101    pub fn insert_creases(
11102        &mut self,
11103        creases: impl IntoIterator<Item = Crease>,
11104        cx: &mut ViewContext<Self>,
11105    ) -> Vec<CreaseId> {
11106        self.display_map
11107            .update(cx, |map, cx| map.insert_creases(creases, cx))
11108    }
11109
11110    pub fn remove_creases(
11111        &mut self,
11112        ids: impl IntoIterator<Item = CreaseId>,
11113        cx: &mut ViewContext<Self>,
11114    ) {
11115        self.display_map
11116            .update(cx, |map, cx| map.remove_creases(ids, cx));
11117    }
11118
11119    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11120        self.display_map
11121            .update(cx, |map, cx| map.snapshot(cx))
11122            .longest_row()
11123    }
11124
11125    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11126        self.display_map
11127            .update(cx, |map, cx| map.snapshot(cx))
11128            .max_point()
11129    }
11130
11131    pub fn text(&self, cx: &AppContext) -> String {
11132        self.buffer.read(cx).read(cx).text()
11133    }
11134
11135    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11136        let text = self.text(cx);
11137        let text = text.trim();
11138
11139        if text.is_empty() {
11140            return None;
11141        }
11142
11143        Some(text.to_string())
11144    }
11145
11146    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11147        self.transact(cx, |this, cx| {
11148            this.buffer
11149                .read(cx)
11150                .as_singleton()
11151                .expect("you can only call set_text on editors for singleton buffers")
11152                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11153        });
11154    }
11155
11156    pub fn display_text(&self, cx: &mut AppContext) -> String {
11157        self.display_map
11158            .update(cx, |map, cx| map.snapshot(cx))
11159            .text()
11160    }
11161
11162    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11163        let mut wrap_guides = smallvec::smallvec![];
11164
11165        if self.show_wrap_guides == Some(false) {
11166            return wrap_guides;
11167        }
11168
11169        let settings = self.buffer.read(cx).settings_at(0, cx);
11170        if settings.show_wrap_guides {
11171            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11172                wrap_guides.push((soft_wrap as usize, true));
11173            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11174                wrap_guides.push((soft_wrap as usize, true));
11175            }
11176            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11177        }
11178
11179        wrap_guides
11180    }
11181
11182    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11183        let settings = self.buffer.read(cx).settings_at(0, cx);
11184        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11185        match mode {
11186            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11187                SoftWrap::None
11188            }
11189            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11190            language_settings::SoftWrap::PreferredLineLength => {
11191                SoftWrap::Column(settings.preferred_line_length)
11192            }
11193            language_settings::SoftWrap::Bounded => {
11194                SoftWrap::Bounded(settings.preferred_line_length)
11195            }
11196        }
11197    }
11198
11199    pub fn set_soft_wrap_mode(
11200        &mut self,
11201        mode: language_settings::SoftWrap,
11202        cx: &mut ViewContext<Self>,
11203    ) {
11204        self.soft_wrap_mode_override = Some(mode);
11205        cx.notify();
11206    }
11207
11208    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11209        self.text_style_refinement = Some(style);
11210    }
11211
11212    /// called by the Element so we know what style we were most recently rendered with.
11213    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11214        let rem_size = cx.rem_size();
11215        self.display_map.update(cx, |map, cx| {
11216            map.set_font(
11217                style.text.font(),
11218                style.text.font_size.to_pixels(rem_size),
11219                cx,
11220            )
11221        });
11222        self.style = Some(style);
11223    }
11224
11225    pub fn style(&self) -> Option<&EditorStyle> {
11226        self.style.as_ref()
11227    }
11228
11229    // Called by the element. This method is not designed to be called outside of the editor
11230    // element's layout code because it does not notify when rewrapping is computed synchronously.
11231    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11232        self.display_map
11233            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11234    }
11235
11236    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11237        if self.soft_wrap_mode_override.is_some() {
11238            self.soft_wrap_mode_override.take();
11239        } else {
11240            let soft_wrap = match self.soft_wrap_mode(cx) {
11241                SoftWrap::GitDiff => return,
11242                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11243                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11244                    language_settings::SoftWrap::None
11245                }
11246            };
11247            self.soft_wrap_mode_override = Some(soft_wrap);
11248        }
11249        cx.notify();
11250    }
11251
11252    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11253        let Some(workspace) = self.workspace() else {
11254            return;
11255        };
11256        let fs = workspace.read(cx).app_state().fs.clone();
11257        let current_show = TabBarSettings::get_global(cx).show;
11258        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11259            setting.show = Some(!current_show);
11260        });
11261    }
11262
11263    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11264        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11265            self.buffer
11266                .read(cx)
11267                .settings_at(0, cx)
11268                .indent_guides
11269                .enabled
11270        });
11271        self.show_indent_guides = Some(!currently_enabled);
11272        cx.notify();
11273    }
11274
11275    fn should_show_indent_guides(&self) -> Option<bool> {
11276        self.show_indent_guides
11277    }
11278
11279    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11280        let mut editor_settings = EditorSettings::get_global(cx).clone();
11281        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11282        EditorSettings::override_global(editor_settings, cx);
11283    }
11284
11285    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11286        self.use_relative_line_numbers
11287            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11288    }
11289
11290    pub fn toggle_relative_line_numbers(
11291        &mut self,
11292        _: &ToggleRelativeLineNumbers,
11293        cx: &mut ViewContext<Self>,
11294    ) {
11295        let is_relative = self.should_use_relative_line_numbers(cx);
11296        self.set_relative_line_number(Some(!is_relative), cx)
11297    }
11298
11299    pub fn set_relative_line_number(
11300        &mut self,
11301        is_relative: Option<bool>,
11302        cx: &mut ViewContext<Self>,
11303    ) {
11304        self.use_relative_line_numbers = is_relative;
11305        cx.notify();
11306    }
11307
11308    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11309        self.show_gutter = show_gutter;
11310        cx.notify();
11311    }
11312
11313    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11314        self.show_line_numbers = Some(show_line_numbers);
11315        cx.notify();
11316    }
11317
11318    pub fn set_show_git_diff_gutter(
11319        &mut self,
11320        show_git_diff_gutter: bool,
11321        cx: &mut ViewContext<Self>,
11322    ) {
11323        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11324        cx.notify();
11325    }
11326
11327    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11328        self.show_code_actions = Some(show_code_actions);
11329        cx.notify();
11330    }
11331
11332    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11333        self.show_runnables = Some(show_runnables);
11334        cx.notify();
11335    }
11336
11337    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11338        if self.display_map.read(cx).masked != masked {
11339            self.display_map.update(cx, |map, _| map.masked = masked);
11340        }
11341        cx.notify()
11342    }
11343
11344    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11345        self.show_wrap_guides = Some(show_wrap_guides);
11346        cx.notify();
11347    }
11348
11349    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11350        self.show_indent_guides = Some(show_indent_guides);
11351        cx.notify();
11352    }
11353
11354    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11355        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11356            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11357                if let Some(dir) = file.abs_path(cx).parent() {
11358                    return Some(dir.to_owned());
11359                }
11360            }
11361
11362            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11363                return Some(project_path.path.to_path_buf());
11364            }
11365        }
11366
11367        None
11368    }
11369
11370    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11371        self.active_excerpt(cx)?
11372            .1
11373            .read(cx)
11374            .file()
11375            .and_then(|f| f.as_local())
11376    }
11377
11378    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11379        if let Some(target) = self.target_file(cx) {
11380            cx.reveal_path(&target.abs_path(cx));
11381        }
11382    }
11383
11384    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11385        if let Some(file) = self.target_file(cx) {
11386            if let Some(path) = file.abs_path(cx).to_str() {
11387                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11388            }
11389        }
11390    }
11391
11392    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11393        if let Some(file) = self.target_file(cx) {
11394            if let Some(path) = file.path().to_str() {
11395                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11396            }
11397        }
11398    }
11399
11400    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11401        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11402
11403        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11404            self.start_git_blame(true, cx);
11405        }
11406
11407        cx.notify();
11408    }
11409
11410    pub fn toggle_git_blame_inline(
11411        &mut self,
11412        _: &ToggleGitBlameInline,
11413        cx: &mut ViewContext<Self>,
11414    ) {
11415        self.toggle_git_blame_inline_internal(true, cx);
11416        cx.notify();
11417    }
11418
11419    pub fn git_blame_inline_enabled(&self) -> bool {
11420        self.git_blame_inline_enabled
11421    }
11422
11423    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11424        self.show_selection_menu = self
11425            .show_selection_menu
11426            .map(|show_selections_menu| !show_selections_menu)
11427            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11428
11429        cx.notify();
11430    }
11431
11432    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11433        self.show_selection_menu
11434            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11435    }
11436
11437    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11438        if let Some(project) = self.project.as_ref() {
11439            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11440                return;
11441            };
11442
11443            if buffer.read(cx).file().is_none() {
11444                return;
11445            }
11446
11447            let focused = self.focus_handle(cx).contains_focused(cx);
11448
11449            let project = project.clone();
11450            let blame =
11451                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11452            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11453            self.blame = Some(blame);
11454        }
11455    }
11456
11457    fn toggle_git_blame_inline_internal(
11458        &mut self,
11459        user_triggered: bool,
11460        cx: &mut ViewContext<Self>,
11461    ) {
11462        if self.git_blame_inline_enabled {
11463            self.git_blame_inline_enabled = false;
11464            self.show_git_blame_inline = false;
11465            self.show_git_blame_inline_delay_task.take();
11466        } else {
11467            self.git_blame_inline_enabled = true;
11468            self.start_git_blame_inline(user_triggered, cx);
11469        }
11470
11471        cx.notify();
11472    }
11473
11474    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11475        self.start_git_blame(user_triggered, cx);
11476
11477        if ProjectSettings::get_global(cx)
11478            .git
11479            .inline_blame_delay()
11480            .is_some()
11481        {
11482            self.start_inline_blame_timer(cx);
11483        } else {
11484            self.show_git_blame_inline = true
11485        }
11486    }
11487
11488    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11489        self.blame.as_ref()
11490    }
11491
11492    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11493        self.show_git_blame_gutter && self.has_blame_entries(cx)
11494    }
11495
11496    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11497        self.show_git_blame_inline
11498            && self.focus_handle.is_focused(cx)
11499            && !self.newest_selection_head_on_empty_line(cx)
11500            && self.has_blame_entries(cx)
11501    }
11502
11503    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11504        self.blame()
11505            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11506    }
11507
11508    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11509        let cursor_anchor = self.selections.newest_anchor().head();
11510
11511        let snapshot = self.buffer.read(cx).snapshot(cx);
11512        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11513
11514        snapshot.line_len(buffer_row) == 0
11515    }
11516
11517    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11518        let buffer_and_selection = maybe!({
11519            let selection = self.selections.newest::<Point>(cx);
11520            let selection_range = selection.range();
11521
11522            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11523                (buffer, selection_range.start.row..selection_range.end.row)
11524            } else {
11525                let buffer_ranges = self
11526                    .buffer()
11527                    .read(cx)
11528                    .range_to_buffer_ranges(selection_range, cx);
11529
11530                let (buffer, range, _) = if selection.reversed {
11531                    buffer_ranges.first()
11532                } else {
11533                    buffer_ranges.last()
11534                }?;
11535
11536                let snapshot = buffer.read(cx).snapshot();
11537                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11538                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11539                (buffer.clone(), selection)
11540            };
11541
11542            Some((buffer, selection))
11543        });
11544
11545        let Some((buffer, selection)) = buffer_and_selection else {
11546            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11547        };
11548
11549        let Some(project) = self.project.as_ref() else {
11550            return Task::ready(Err(anyhow!("editor does not have project")));
11551        };
11552
11553        project.update(cx, |project, cx| {
11554            project.get_permalink_to_line(&buffer, selection, cx)
11555        })
11556    }
11557
11558    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11559        let permalink_task = self.get_permalink_to_line(cx);
11560        let workspace = self.workspace();
11561
11562        cx.spawn(|_, mut cx| async move {
11563            match permalink_task.await {
11564                Ok(permalink) => {
11565                    cx.update(|cx| {
11566                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11567                    })
11568                    .ok();
11569                }
11570                Err(err) => {
11571                    let message = format!("Failed to copy permalink: {err}");
11572
11573                    Err::<(), anyhow::Error>(err).log_err();
11574
11575                    if let Some(workspace) = workspace {
11576                        workspace
11577                            .update(&mut cx, |workspace, cx| {
11578                                struct CopyPermalinkToLine;
11579
11580                                workspace.show_toast(
11581                                    Toast::new(
11582                                        NotificationId::unique::<CopyPermalinkToLine>(),
11583                                        message,
11584                                    ),
11585                                    cx,
11586                                )
11587                            })
11588                            .ok();
11589                    }
11590                }
11591            }
11592        })
11593        .detach();
11594    }
11595
11596    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11597        if let Some(file) = self.target_file(cx) {
11598            if let Some(path) = file.path().to_str() {
11599                let selection = self.selections.newest::<Point>(cx).start.row + 1;
11600                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11601            }
11602        }
11603    }
11604
11605    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11606        let permalink_task = self.get_permalink_to_line(cx);
11607        let workspace = self.workspace();
11608
11609        cx.spawn(|_, mut cx| async move {
11610            match permalink_task.await {
11611                Ok(permalink) => {
11612                    cx.update(|cx| {
11613                        cx.open_url(permalink.as_ref());
11614                    })
11615                    .ok();
11616                }
11617                Err(err) => {
11618                    let message = format!("Failed to open permalink: {err}");
11619
11620                    Err::<(), anyhow::Error>(err).log_err();
11621
11622                    if let Some(workspace) = workspace {
11623                        workspace
11624                            .update(&mut cx, |workspace, cx| {
11625                                struct OpenPermalinkToLine;
11626
11627                                workspace.show_toast(
11628                                    Toast::new(
11629                                        NotificationId::unique::<OpenPermalinkToLine>(),
11630                                        message,
11631                                    ),
11632                                    cx,
11633                                )
11634                            })
11635                            .ok();
11636                    }
11637                }
11638            }
11639        })
11640        .detach();
11641    }
11642
11643    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11644    /// last highlight added will be used.
11645    ///
11646    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11647    pub fn highlight_rows<T: 'static>(
11648        &mut self,
11649        range: Range<Anchor>,
11650        color: Hsla,
11651        should_autoscroll: bool,
11652        cx: &mut ViewContext<Self>,
11653    ) {
11654        let snapshot = self.buffer().read(cx).snapshot(cx);
11655        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11656        let ix = row_highlights.binary_search_by(|highlight| {
11657            Ordering::Equal
11658                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11659                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11660        });
11661
11662        if let Err(mut ix) = ix {
11663            let index = post_inc(&mut self.highlight_order);
11664
11665            // If this range intersects with the preceding highlight, then merge it with
11666            // the preceding highlight. Otherwise insert a new highlight.
11667            let mut merged = false;
11668            if ix > 0 {
11669                let prev_highlight = &mut row_highlights[ix - 1];
11670                if prev_highlight
11671                    .range
11672                    .end
11673                    .cmp(&range.start, &snapshot)
11674                    .is_ge()
11675                {
11676                    ix -= 1;
11677                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11678                        prev_highlight.range.end = range.end;
11679                    }
11680                    merged = true;
11681                    prev_highlight.index = index;
11682                    prev_highlight.color = color;
11683                    prev_highlight.should_autoscroll = should_autoscroll;
11684                }
11685            }
11686
11687            if !merged {
11688                row_highlights.insert(
11689                    ix,
11690                    RowHighlight {
11691                        range: range.clone(),
11692                        index,
11693                        color,
11694                        should_autoscroll,
11695                    },
11696                );
11697            }
11698
11699            // If any of the following highlights intersect with this one, merge them.
11700            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11701                let highlight = &row_highlights[ix];
11702                if next_highlight
11703                    .range
11704                    .start
11705                    .cmp(&highlight.range.end, &snapshot)
11706                    .is_le()
11707                {
11708                    if next_highlight
11709                        .range
11710                        .end
11711                        .cmp(&highlight.range.end, &snapshot)
11712                        .is_gt()
11713                    {
11714                        row_highlights[ix].range.end = next_highlight.range.end;
11715                    }
11716                    row_highlights.remove(ix + 1);
11717                } else {
11718                    break;
11719                }
11720            }
11721        }
11722    }
11723
11724    /// Remove any highlighted row ranges of the given type that intersect the
11725    /// given ranges.
11726    pub fn remove_highlighted_rows<T: 'static>(
11727        &mut self,
11728        ranges_to_remove: Vec<Range<Anchor>>,
11729        cx: &mut ViewContext<Self>,
11730    ) {
11731        let snapshot = self.buffer().read(cx).snapshot(cx);
11732        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11733        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11734        row_highlights.retain(|highlight| {
11735            while let Some(range_to_remove) = ranges_to_remove.peek() {
11736                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11737                    Ordering::Less | Ordering::Equal => {
11738                        ranges_to_remove.next();
11739                    }
11740                    Ordering::Greater => {
11741                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11742                            Ordering::Less | Ordering::Equal => {
11743                                return false;
11744                            }
11745                            Ordering::Greater => break,
11746                        }
11747                    }
11748                }
11749            }
11750
11751            true
11752        })
11753    }
11754
11755    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11756    pub fn clear_row_highlights<T: 'static>(&mut self) {
11757        self.highlighted_rows.remove(&TypeId::of::<T>());
11758    }
11759
11760    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11761    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11762        self.highlighted_rows
11763            .get(&TypeId::of::<T>())
11764            .map_or(&[] as &[_], |vec| vec.as_slice())
11765            .iter()
11766            .map(|highlight| (highlight.range.clone(), highlight.color))
11767    }
11768
11769    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11770    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11771    /// Allows to ignore certain kinds of highlights.
11772    pub fn highlighted_display_rows(
11773        &mut self,
11774        cx: &mut WindowContext,
11775    ) -> BTreeMap<DisplayRow, Hsla> {
11776        let snapshot = self.snapshot(cx);
11777        let mut used_highlight_orders = HashMap::default();
11778        self.highlighted_rows
11779            .iter()
11780            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11781            .fold(
11782                BTreeMap::<DisplayRow, Hsla>::new(),
11783                |mut unique_rows, highlight| {
11784                    let start = highlight.range.start.to_display_point(&snapshot);
11785                    let end = highlight.range.end.to_display_point(&snapshot);
11786                    let start_row = start.row().0;
11787                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11788                        && end.column() == 0
11789                    {
11790                        end.row().0.saturating_sub(1)
11791                    } else {
11792                        end.row().0
11793                    };
11794                    for row in start_row..=end_row {
11795                        let used_index =
11796                            used_highlight_orders.entry(row).or_insert(highlight.index);
11797                        if highlight.index >= *used_index {
11798                            *used_index = highlight.index;
11799                            unique_rows.insert(DisplayRow(row), highlight.color);
11800                        }
11801                    }
11802                    unique_rows
11803                },
11804            )
11805    }
11806
11807    pub fn highlighted_display_row_for_autoscroll(
11808        &self,
11809        snapshot: &DisplaySnapshot,
11810    ) -> Option<DisplayRow> {
11811        self.highlighted_rows
11812            .values()
11813            .flat_map(|highlighted_rows| highlighted_rows.iter())
11814            .filter_map(|highlight| {
11815                if highlight.should_autoscroll {
11816                    Some(highlight.range.start.to_display_point(snapshot).row())
11817                } else {
11818                    None
11819                }
11820            })
11821            .min()
11822    }
11823
11824    pub fn set_search_within_ranges(
11825        &mut self,
11826        ranges: &[Range<Anchor>],
11827        cx: &mut ViewContext<Self>,
11828    ) {
11829        self.highlight_background::<SearchWithinRange>(
11830            ranges,
11831            |colors| colors.editor_document_highlight_read_background,
11832            cx,
11833        )
11834    }
11835
11836    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11837        self.breadcrumb_header = Some(new_header);
11838    }
11839
11840    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11841        self.clear_background_highlights::<SearchWithinRange>(cx);
11842    }
11843
11844    pub fn highlight_background<T: 'static>(
11845        &mut self,
11846        ranges: &[Range<Anchor>],
11847        color_fetcher: fn(&ThemeColors) -> Hsla,
11848        cx: &mut ViewContext<Self>,
11849    ) {
11850        self.background_highlights
11851            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11852        self.scrollbar_marker_state.dirty = true;
11853        cx.notify();
11854    }
11855
11856    pub fn clear_background_highlights<T: 'static>(
11857        &mut self,
11858        cx: &mut ViewContext<Self>,
11859    ) -> Option<BackgroundHighlight> {
11860        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11861        if !text_highlights.1.is_empty() {
11862            self.scrollbar_marker_state.dirty = true;
11863            cx.notify();
11864        }
11865        Some(text_highlights)
11866    }
11867
11868    pub fn highlight_gutter<T: 'static>(
11869        &mut self,
11870        ranges: &[Range<Anchor>],
11871        color_fetcher: fn(&AppContext) -> Hsla,
11872        cx: &mut ViewContext<Self>,
11873    ) {
11874        self.gutter_highlights
11875            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11876        cx.notify();
11877    }
11878
11879    pub fn clear_gutter_highlights<T: 'static>(
11880        &mut self,
11881        cx: &mut ViewContext<Self>,
11882    ) -> Option<GutterHighlight> {
11883        cx.notify();
11884        self.gutter_highlights.remove(&TypeId::of::<T>())
11885    }
11886
11887    #[cfg(feature = "test-support")]
11888    pub fn all_text_background_highlights(
11889        &mut self,
11890        cx: &mut ViewContext<Self>,
11891    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11892        let snapshot = self.snapshot(cx);
11893        let buffer = &snapshot.buffer_snapshot;
11894        let start = buffer.anchor_before(0);
11895        let end = buffer.anchor_after(buffer.len());
11896        let theme = cx.theme().colors();
11897        self.background_highlights_in_range(start..end, &snapshot, theme)
11898    }
11899
11900    #[cfg(feature = "test-support")]
11901    pub fn search_background_highlights(
11902        &mut self,
11903        cx: &mut ViewContext<Self>,
11904    ) -> Vec<Range<Point>> {
11905        let snapshot = self.buffer().read(cx).snapshot(cx);
11906
11907        let highlights = self
11908            .background_highlights
11909            .get(&TypeId::of::<items::BufferSearchHighlights>());
11910
11911        if let Some((_color, ranges)) = highlights {
11912            ranges
11913                .iter()
11914                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11915                .collect_vec()
11916        } else {
11917            vec![]
11918        }
11919    }
11920
11921    fn document_highlights_for_position<'a>(
11922        &'a self,
11923        position: Anchor,
11924        buffer: &'a MultiBufferSnapshot,
11925    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11926        let read_highlights = self
11927            .background_highlights
11928            .get(&TypeId::of::<DocumentHighlightRead>())
11929            .map(|h| &h.1);
11930        let write_highlights = self
11931            .background_highlights
11932            .get(&TypeId::of::<DocumentHighlightWrite>())
11933            .map(|h| &h.1);
11934        let left_position = position.bias_left(buffer);
11935        let right_position = position.bias_right(buffer);
11936        read_highlights
11937            .into_iter()
11938            .chain(write_highlights)
11939            .flat_map(move |ranges| {
11940                let start_ix = match ranges.binary_search_by(|probe| {
11941                    let cmp = probe.end.cmp(&left_position, buffer);
11942                    if cmp.is_ge() {
11943                        Ordering::Greater
11944                    } else {
11945                        Ordering::Less
11946                    }
11947                }) {
11948                    Ok(i) | Err(i) => i,
11949                };
11950
11951                ranges[start_ix..]
11952                    .iter()
11953                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11954            })
11955    }
11956
11957    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11958        self.background_highlights
11959            .get(&TypeId::of::<T>())
11960            .map_or(false, |(_, highlights)| !highlights.is_empty())
11961    }
11962
11963    pub fn background_highlights_in_range(
11964        &self,
11965        search_range: Range<Anchor>,
11966        display_snapshot: &DisplaySnapshot,
11967        theme: &ThemeColors,
11968    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11969        let mut results = Vec::new();
11970        for (color_fetcher, ranges) in self.background_highlights.values() {
11971            let color = color_fetcher(theme);
11972            let start_ix = match ranges.binary_search_by(|probe| {
11973                let cmp = probe
11974                    .end
11975                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11976                if cmp.is_gt() {
11977                    Ordering::Greater
11978                } else {
11979                    Ordering::Less
11980                }
11981            }) {
11982                Ok(i) | Err(i) => i,
11983            };
11984            for range in &ranges[start_ix..] {
11985                if range
11986                    .start
11987                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11988                    .is_ge()
11989                {
11990                    break;
11991                }
11992
11993                let start = range.start.to_display_point(display_snapshot);
11994                let end = range.end.to_display_point(display_snapshot);
11995                results.push((start..end, color))
11996            }
11997        }
11998        results
11999    }
12000
12001    pub fn background_highlight_row_ranges<T: 'static>(
12002        &self,
12003        search_range: Range<Anchor>,
12004        display_snapshot: &DisplaySnapshot,
12005        count: usize,
12006    ) -> Vec<RangeInclusive<DisplayPoint>> {
12007        let mut results = Vec::new();
12008        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12009            return vec![];
12010        };
12011
12012        let start_ix = match ranges.binary_search_by(|probe| {
12013            let cmp = probe
12014                .end
12015                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12016            if cmp.is_gt() {
12017                Ordering::Greater
12018            } else {
12019                Ordering::Less
12020            }
12021        }) {
12022            Ok(i) | Err(i) => i,
12023        };
12024        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12025            if let (Some(start_display), Some(end_display)) = (start, end) {
12026                results.push(
12027                    start_display.to_display_point(display_snapshot)
12028                        ..=end_display.to_display_point(display_snapshot),
12029                );
12030            }
12031        };
12032        let mut start_row: Option<Point> = None;
12033        let mut end_row: Option<Point> = None;
12034        if ranges.len() > count {
12035            return Vec::new();
12036        }
12037        for range in &ranges[start_ix..] {
12038            if range
12039                .start
12040                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12041                .is_ge()
12042            {
12043                break;
12044            }
12045            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12046            if let Some(current_row) = &end_row {
12047                if end.row == current_row.row {
12048                    continue;
12049                }
12050            }
12051            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12052            if start_row.is_none() {
12053                assert_eq!(end_row, None);
12054                start_row = Some(start);
12055                end_row = Some(end);
12056                continue;
12057            }
12058            if let Some(current_end) = end_row.as_mut() {
12059                if start.row > current_end.row + 1 {
12060                    push_region(start_row, end_row);
12061                    start_row = Some(start);
12062                    end_row = Some(end);
12063                } else {
12064                    // Merge two hunks.
12065                    *current_end = end;
12066                }
12067            } else {
12068                unreachable!();
12069            }
12070        }
12071        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12072        push_region(start_row, end_row);
12073        results
12074    }
12075
12076    pub fn gutter_highlights_in_range(
12077        &self,
12078        search_range: Range<Anchor>,
12079        display_snapshot: &DisplaySnapshot,
12080        cx: &AppContext,
12081    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12082        let mut results = Vec::new();
12083        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12084            let color = color_fetcher(cx);
12085            let start_ix = match ranges.binary_search_by(|probe| {
12086                let cmp = probe
12087                    .end
12088                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12089                if cmp.is_gt() {
12090                    Ordering::Greater
12091                } else {
12092                    Ordering::Less
12093                }
12094            }) {
12095                Ok(i) | Err(i) => i,
12096            };
12097            for range in &ranges[start_ix..] {
12098                if range
12099                    .start
12100                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12101                    .is_ge()
12102                {
12103                    break;
12104                }
12105
12106                let start = range.start.to_display_point(display_snapshot);
12107                let end = range.end.to_display_point(display_snapshot);
12108                results.push((start..end, color))
12109            }
12110        }
12111        results
12112    }
12113
12114    /// Get the text ranges corresponding to the redaction query
12115    pub fn redacted_ranges(
12116        &self,
12117        search_range: Range<Anchor>,
12118        display_snapshot: &DisplaySnapshot,
12119        cx: &WindowContext,
12120    ) -> Vec<Range<DisplayPoint>> {
12121        display_snapshot
12122            .buffer_snapshot
12123            .redacted_ranges(search_range, |file| {
12124                if let Some(file) = file {
12125                    file.is_private()
12126                        && EditorSettings::get(
12127                            Some(SettingsLocation {
12128                                worktree_id: file.worktree_id(cx),
12129                                path: file.path().as_ref(),
12130                            }),
12131                            cx,
12132                        )
12133                        .redact_private_values
12134                } else {
12135                    false
12136                }
12137            })
12138            .map(|range| {
12139                range.start.to_display_point(display_snapshot)
12140                    ..range.end.to_display_point(display_snapshot)
12141            })
12142            .collect()
12143    }
12144
12145    pub fn highlight_text<T: 'static>(
12146        &mut self,
12147        ranges: Vec<Range<Anchor>>,
12148        style: HighlightStyle,
12149        cx: &mut ViewContext<Self>,
12150    ) {
12151        self.display_map.update(cx, |map, _| {
12152            map.highlight_text(TypeId::of::<T>(), ranges, style)
12153        });
12154        cx.notify();
12155    }
12156
12157    pub(crate) fn highlight_inlays<T: 'static>(
12158        &mut self,
12159        highlights: Vec<InlayHighlight>,
12160        style: HighlightStyle,
12161        cx: &mut ViewContext<Self>,
12162    ) {
12163        self.display_map.update(cx, |map, _| {
12164            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12165        });
12166        cx.notify();
12167    }
12168
12169    pub fn text_highlights<'a, T: 'static>(
12170        &'a self,
12171        cx: &'a AppContext,
12172    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12173        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12174    }
12175
12176    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12177        let cleared = self
12178            .display_map
12179            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12180        if cleared {
12181            cx.notify();
12182        }
12183    }
12184
12185    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12186        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12187            && self.focus_handle.is_focused(cx)
12188    }
12189
12190    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12191        self.show_cursor_when_unfocused = is_enabled;
12192        cx.notify();
12193    }
12194
12195    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12196        cx.notify();
12197    }
12198
12199    fn on_buffer_event(
12200        &mut self,
12201        multibuffer: Model<MultiBuffer>,
12202        event: &multi_buffer::Event,
12203        cx: &mut ViewContext<Self>,
12204    ) {
12205        match event {
12206            multi_buffer::Event::Edited {
12207                singleton_buffer_edited,
12208            } => {
12209                self.scrollbar_marker_state.dirty = true;
12210                self.active_indent_guides_state.dirty = true;
12211                self.refresh_active_diagnostics(cx);
12212                self.refresh_code_actions(cx);
12213                if self.has_active_inline_completion(cx) {
12214                    self.update_visible_inline_completion(cx);
12215                }
12216                cx.emit(EditorEvent::BufferEdited);
12217                cx.emit(SearchEvent::MatchesInvalidated);
12218                if *singleton_buffer_edited {
12219                    if let Some(project) = &self.project {
12220                        let project = project.read(cx);
12221                        #[allow(clippy::mutable_key_type)]
12222                        let languages_affected = multibuffer
12223                            .read(cx)
12224                            .all_buffers()
12225                            .into_iter()
12226                            .filter_map(|buffer| {
12227                                let buffer = buffer.read(cx);
12228                                let language = buffer.language()?;
12229                                if project.is_local()
12230                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12231                                {
12232                                    None
12233                                } else {
12234                                    Some(language)
12235                                }
12236                            })
12237                            .cloned()
12238                            .collect::<HashSet<_>>();
12239                        if !languages_affected.is_empty() {
12240                            self.refresh_inlay_hints(
12241                                InlayHintRefreshReason::BufferEdited(languages_affected),
12242                                cx,
12243                            );
12244                        }
12245                    }
12246                }
12247
12248                let Some(project) = &self.project else { return };
12249                let (telemetry, is_via_ssh) = {
12250                    let project = project.read(cx);
12251                    let telemetry = project.client().telemetry().clone();
12252                    let is_via_ssh = project.is_via_ssh();
12253                    (telemetry, is_via_ssh)
12254                };
12255                refresh_linked_ranges(self, cx);
12256                telemetry.log_edit_event("editor", is_via_ssh);
12257            }
12258            multi_buffer::Event::ExcerptsAdded {
12259                buffer,
12260                predecessor,
12261                excerpts,
12262            } => {
12263                self.tasks_update_task = Some(self.refresh_runnables(cx));
12264                cx.emit(EditorEvent::ExcerptsAdded {
12265                    buffer: buffer.clone(),
12266                    predecessor: *predecessor,
12267                    excerpts: excerpts.clone(),
12268                });
12269                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12270            }
12271            multi_buffer::Event::ExcerptsRemoved { ids } => {
12272                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12273                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12274            }
12275            multi_buffer::Event::ExcerptsEdited { ids } => {
12276                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12277            }
12278            multi_buffer::Event::ExcerptsExpanded { ids } => {
12279                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12280            }
12281            multi_buffer::Event::Reparsed(buffer_id) => {
12282                self.tasks_update_task = Some(self.refresh_runnables(cx));
12283
12284                cx.emit(EditorEvent::Reparsed(*buffer_id));
12285            }
12286            multi_buffer::Event::LanguageChanged(buffer_id) => {
12287                linked_editing_ranges::refresh_linked_ranges(self, cx);
12288                cx.emit(EditorEvent::Reparsed(*buffer_id));
12289                cx.notify();
12290            }
12291            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12292            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12293            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12294                cx.emit(EditorEvent::TitleChanged)
12295            }
12296            multi_buffer::Event::DiffBaseChanged => {
12297                self.scrollbar_marker_state.dirty = true;
12298                cx.emit(EditorEvent::DiffBaseChanged);
12299                cx.notify();
12300            }
12301            multi_buffer::Event::DiffUpdated { buffer } => {
12302                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12303                cx.notify();
12304            }
12305            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12306            multi_buffer::Event::DiagnosticsUpdated => {
12307                self.refresh_active_diagnostics(cx);
12308                self.scrollbar_marker_state.dirty = true;
12309                cx.notify();
12310            }
12311            _ => {}
12312        };
12313    }
12314
12315    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12316        cx.notify();
12317    }
12318
12319    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12320        self.tasks_update_task = Some(self.refresh_runnables(cx));
12321        self.refresh_inline_completion(true, false, cx);
12322        self.refresh_inlay_hints(
12323            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12324                self.selections.newest_anchor().head(),
12325                &self.buffer.read(cx).snapshot(cx),
12326                cx,
12327            )),
12328            cx,
12329        );
12330
12331        let old_cursor_shape = self.cursor_shape;
12332
12333        {
12334            let editor_settings = EditorSettings::get_global(cx);
12335            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12336            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12337            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12338        }
12339
12340        if old_cursor_shape != self.cursor_shape {
12341            cx.emit(EditorEvent::CursorShapeChanged);
12342        }
12343
12344        let project_settings = ProjectSettings::get_global(cx);
12345        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12346
12347        if self.mode == EditorMode::Full {
12348            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12349            if self.git_blame_inline_enabled != inline_blame_enabled {
12350                self.toggle_git_blame_inline_internal(false, cx);
12351            }
12352        }
12353
12354        cx.notify();
12355    }
12356
12357    pub fn set_searchable(&mut self, searchable: bool) {
12358        self.searchable = searchable;
12359    }
12360
12361    pub fn searchable(&self) -> bool {
12362        self.searchable
12363    }
12364
12365    fn open_proposed_changes_editor(
12366        &mut self,
12367        _: &OpenProposedChangesEditor,
12368        cx: &mut ViewContext<Self>,
12369    ) {
12370        let Some(workspace) = self.workspace() else {
12371            cx.propagate();
12372            return;
12373        };
12374
12375        let buffer = self.buffer.read(cx);
12376        let mut new_selections_by_buffer = HashMap::default();
12377        for selection in self.selections.all::<usize>(cx) {
12378            for (buffer, range, _) in
12379                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12380            {
12381                let mut range = range.to_point(buffer.read(cx));
12382                range.start.column = 0;
12383                range.end.column = buffer.read(cx).line_len(range.end.row);
12384                new_selections_by_buffer
12385                    .entry(buffer)
12386                    .or_insert(Vec::new())
12387                    .push(range)
12388            }
12389        }
12390
12391        let proposed_changes_buffers = new_selections_by_buffer
12392            .into_iter()
12393            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12394            .collect::<Vec<_>>();
12395        let proposed_changes_editor = cx.new_view(|cx| {
12396            ProposedChangesEditor::new(
12397                "Proposed changes",
12398                proposed_changes_buffers,
12399                self.project.clone(),
12400                cx,
12401            )
12402        });
12403
12404        cx.window_context().defer(move |cx| {
12405            workspace.update(cx, |workspace, cx| {
12406                workspace.active_pane().update(cx, |pane, cx| {
12407                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12408                });
12409            });
12410        });
12411    }
12412
12413    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12414        self.open_excerpts_common(true, cx)
12415    }
12416
12417    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12418        self.open_excerpts_common(false, cx)
12419    }
12420
12421    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12422        let buffer = self.buffer.read(cx);
12423        if buffer.is_singleton() {
12424            cx.propagate();
12425            return;
12426        }
12427
12428        let Some(workspace) = self.workspace() else {
12429            cx.propagate();
12430            return;
12431        };
12432
12433        let mut new_selections_by_buffer = HashMap::default();
12434        for selection in self.selections.all::<usize>(cx) {
12435            for (mut buffer_handle, mut range, _) in
12436                buffer.range_to_buffer_ranges(selection.range(), cx)
12437            {
12438                // When editing branch buffers, jump to the corresponding location
12439                // in their base buffer.
12440                let buffer = buffer_handle.read(cx);
12441                if let Some(base_buffer) = buffer.diff_base_buffer() {
12442                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12443                    buffer_handle = base_buffer;
12444                }
12445
12446                if selection.reversed {
12447                    mem::swap(&mut range.start, &mut range.end);
12448                }
12449                new_selections_by_buffer
12450                    .entry(buffer_handle)
12451                    .or_insert(Vec::new())
12452                    .push(range)
12453            }
12454        }
12455
12456        // We defer the pane interaction because we ourselves are a workspace item
12457        // and activating a new item causes the pane to call a method on us reentrantly,
12458        // which panics if we're on the stack.
12459        cx.window_context().defer(move |cx| {
12460            workspace.update(cx, |workspace, cx| {
12461                let pane = if split {
12462                    workspace.adjacent_pane(cx)
12463                } else {
12464                    workspace.active_pane().clone()
12465                };
12466
12467                for (buffer, ranges) in new_selections_by_buffer {
12468                    let editor =
12469                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12470                    editor.update(cx, |editor, cx| {
12471                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12472                            s.select_ranges(ranges);
12473                        });
12474                    });
12475                }
12476            })
12477        });
12478    }
12479
12480    fn jump(
12481        &mut self,
12482        path: ProjectPath,
12483        position: Point,
12484        anchor: language::Anchor,
12485        offset_from_top: u32,
12486        cx: &mut ViewContext<Self>,
12487    ) {
12488        let workspace = self.workspace();
12489        cx.spawn(|_, mut cx| async move {
12490            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12491            let editor = workspace.update(&mut cx, |workspace, cx| {
12492                // Reset the preview item id before opening the new item
12493                workspace.active_pane().update(cx, |pane, cx| {
12494                    pane.set_preview_item_id(None, cx);
12495                });
12496                workspace.open_path_preview(path, None, true, true, cx)
12497            })?;
12498            let editor = editor
12499                .await?
12500                .downcast::<Editor>()
12501                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12502                .downgrade();
12503            editor.update(&mut cx, |editor, cx| {
12504                let buffer = editor
12505                    .buffer()
12506                    .read(cx)
12507                    .as_singleton()
12508                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12509                let buffer = buffer.read(cx);
12510                let cursor = if buffer.can_resolve(&anchor) {
12511                    language::ToPoint::to_point(&anchor, buffer)
12512                } else {
12513                    buffer.clip_point(position, Bias::Left)
12514                };
12515
12516                let nav_history = editor.nav_history.take();
12517                editor.change_selections(
12518                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12519                    cx,
12520                    |s| {
12521                        s.select_ranges([cursor..cursor]);
12522                    },
12523                );
12524                editor.nav_history = nav_history;
12525
12526                anyhow::Ok(())
12527            })??;
12528
12529            anyhow::Ok(())
12530        })
12531        .detach_and_log_err(cx);
12532    }
12533
12534    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12535        let snapshot = self.buffer.read(cx).read(cx);
12536        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12537        Some(
12538            ranges
12539                .iter()
12540                .map(move |range| {
12541                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12542                })
12543                .collect(),
12544        )
12545    }
12546
12547    fn selection_replacement_ranges(
12548        &self,
12549        range: Range<OffsetUtf16>,
12550        cx: &AppContext,
12551    ) -> Vec<Range<OffsetUtf16>> {
12552        let selections = self.selections.all::<OffsetUtf16>(cx);
12553        let newest_selection = selections
12554            .iter()
12555            .max_by_key(|selection| selection.id)
12556            .unwrap();
12557        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12558        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12559        let snapshot = self.buffer.read(cx).read(cx);
12560        selections
12561            .into_iter()
12562            .map(|mut selection| {
12563                selection.start.0 =
12564                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12565                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12566                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12567                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12568            })
12569            .collect()
12570    }
12571
12572    fn report_editor_event(
12573        &self,
12574        operation: &'static str,
12575        file_extension: Option<String>,
12576        cx: &AppContext,
12577    ) {
12578        if cfg!(any(test, feature = "test-support")) {
12579            return;
12580        }
12581
12582        let Some(project) = &self.project else { return };
12583
12584        // If None, we are in a file without an extension
12585        let file = self
12586            .buffer
12587            .read(cx)
12588            .as_singleton()
12589            .and_then(|b| b.read(cx).file());
12590        let file_extension = file_extension.or(file
12591            .as_ref()
12592            .and_then(|file| Path::new(file.file_name(cx)).extension())
12593            .and_then(|e| e.to_str())
12594            .map(|a| a.to_string()));
12595
12596        let vim_mode = cx
12597            .global::<SettingsStore>()
12598            .raw_user_settings()
12599            .get("vim_mode")
12600            == Some(&serde_json::Value::Bool(true));
12601
12602        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12603            == language::language_settings::InlineCompletionProvider::Copilot;
12604        let copilot_enabled_for_language = self
12605            .buffer
12606            .read(cx)
12607            .settings_at(0, cx)
12608            .show_inline_completions;
12609
12610        let project = project.read(cx);
12611        let telemetry = project.client().telemetry().clone();
12612        telemetry.report_editor_event(
12613            file_extension,
12614            vim_mode,
12615            operation,
12616            copilot_enabled,
12617            copilot_enabled_for_language,
12618            project.is_via_ssh(),
12619        )
12620    }
12621
12622    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12623    /// with each line being an array of {text, highlight} objects.
12624    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12625        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12626            return;
12627        };
12628
12629        #[derive(Serialize)]
12630        struct Chunk<'a> {
12631            text: String,
12632            highlight: Option<&'a str>,
12633        }
12634
12635        let snapshot = buffer.read(cx).snapshot();
12636        let range = self
12637            .selected_text_range(false, cx)
12638            .and_then(|selection| {
12639                if selection.range.is_empty() {
12640                    None
12641                } else {
12642                    Some(selection.range)
12643                }
12644            })
12645            .unwrap_or_else(|| 0..snapshot.len());
12646
12647        let chunks = snapshot.chunks(range, true);
12648        let mut lines = Vec::new();
12649        let mut line: VecDeque<Chunk> = VecDeque::new();
12650
12651        let Some(style) = self.style.as_ref() else {
12652            return;
12653        };
12654
12655        for chunk in chunks {
12656            let highlight = chunk
12657                .syntax_highlight_id
12658                .and_then(|id| id.name(&style.syntax));
12659            let mut chunk_lines = chunk.text.split('\n').peekable();
12660            while let Some(text) = chunk_lines.next() {
12661                let mut merged_with_last_token = false;
12662                if let Some(last_token) = line.back_mut() {
12663                    if last_token.highlight == highlight {
12664                        last_token.text.push_str(text);
12665                        merged_with_last_token = true;
12666                    }
12667                }
12668
12669                if !merged_with_last_token {
12670                    line.push_back(Chunk {
12671                        text: text.into(),
12672                        highlight,
12673                    });
12674                }
12675
12676                if chunk_lines.peek().is_some() {
12677                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12678                        line.pop_front();
12679                    }
12680                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12681                        line.pop_back();
12682                    }
12683
12684                    lines.push(mem::take(&mut line));
12685                }
12686            }
12687        }
12688
12689        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12690            return;
12691        };
12692        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12693    }
12694
12695    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12696        &self.inlay_hint_cache
12697    }
12698
12699    pub fn replay_insert_event(
12700        &mut self,
12701        text: &str,
12702        relative_utf16_range: Option<Range<isize>>,
12703        cx: &mut ViewContext<Self>,
12704    ) {
12705        if !self.input_enabled {
12706            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12707            return;
12708        }
12709        if let Some(relative_utf16_range) = relative_utf16_range {
12710            let selections = self.selections.all::<OffsetUtf16>(cx);
12711            self.change_selections(None, cx, |s| {
12712                let new_ranges = selections.into_iter().map(|range| {
12713                    let start = OffsetUtf16(
12714                        range
12715                            .head()
12716                            .0
12717                            .saturating_add_signed(relative_utf16_range.start),
12718                    );
12719                    let end = OffsetUtf16(
12720                        range
12721                            .head()
12722                            .0
12723                            .saturating_add_signed(relative_utf16_range.end),
12724                    );
12725                    start..end
12726                });
12727                s.select_ranges(new_ranges);
12728            });
12729        }
12730
12731        self.handle_input(text, cx);
12732    }
12733
12734    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12735        let Some(provider) = self.semantics_provider.as_ref() else {
12736            return false;
12737        };
12738
12739        let mut supports = false;
12740        self.buffer().read(cx).for_each_buffer(|buffer| {
12741            supports |= provider.supports_inlay_hints(buffer, cx);
12742        });
12743        supports
12744    }
12745
12746    pub fn focus(&self, cx: &mut WindowContext) {
12747        cx.focus(&self.focus_handle)
12748    }
12749
12750    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12751        self.focus_handle.is_focused(cx)
12752    }
12753
12754    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12755        cx.emit(EditorEvent::Focused);
12756
12757        if let Some(descendant) = self
12758            .last_focused_descendant
12759            .take()
12760            .and_then(|descendant| descendant.upgrade())
12761        {
12762            cx.focus(&descendant);
12763        } else {
12764            if let Some(blame) = self.blame.as_ref() {
12765                blame.update(cx, GitBlame::focus)
12766            }
12767
12768            self.blink_manager.update(cx, BlinkManager::enable);
12769            self.show_cursor_names(cx);
12770            self.buffer.update(cx, |buffer, cx| {
12771                buffer.finalize_last_transaction(cx);
12772                if self.leader_peer_id.is_none() {
12773                    buffer.set_active_selections(
12774                        &self.selections.disjoint_anchors(),
12775                        self.selections.line_mode,
12776                        self.cursor_shape,
12777                        cx,
12778                    );
12779                }
12780            });
12781        }
12782    }
12783
12784    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12785        cx.emit(EditorEvent::FocusedIn)
12786    }
12787
12788    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12789        if event.blurred != self.focus_handle {
12790            self.last_focused_descendant = Some(event.blurred);
12791        }
12792    }
12793
12794    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12795        self.blink_manager.update(cx, BlinkManager::disable);
12796        self.buffer
12797            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12798
12799        if let Some(blame) = self.blame.as_ref() {
12800            blame.update(cx, GitBlame::blur)
12801        }
12802        if !self.hover_state.focused(cx) {
12803            hide_hover(self, cx);
12804        }
12805
12806        self.hide_context_menu(cx);
12807        cx.emit(EditorEvent::Blurred);
12808        cx.notify();
12809    }
12810
12811    pub fn register_action<A: Action>(
12812        &mut self,
12813        listener: impl Fn(&A, &mut WindowContext) + 'static,
12814    ) -> Subscription {
12815        let id = self.next_editor_action_id.post_inc();
12816        let listener = Arc::new(listener);
12817        self.editor_actions.borrow_mut().insert(
12818            id,
12819            Box::new(move |cx| {
12820                let cx = cx.window_context();
12821                let listener = listener.clone();
12822                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12823                    let action = action.downcast_ref().unwrap();
12824                    if phase == DispatchPhase::Bubble {
12825                        listener(action, cx)
12826                    }
12827                })
12828            }),
12829        );
12830
12831        let editor_actions = self.editor_actions.clone();
12832        Subscription::new(move || {
12833            editor_actions.borrow_mut().remove(&id);
12834        })
12835    }
12836
12837    pub fn file_header_size(&self) -> u32 {
12838        FILE_HEADER_HEIGHT
12839    }
12840
12841    pub fn revert(
12842        &mut self,
12843        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12844        cx: &mut ViewContext<Self>,
12845    ) {
12846        self.buffer().update(cx, |multi_buffer, cx| {
12847            for (buffer_id, changes) in revert_changes {
12848                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12849                    buffer.update(cx, |buffer, cx| {
12850                        buffer.edit(
12851                            changes.into_iter().map(|(range, text)| {
12852                                (range, text.to_string().map(Arc::<str>::from))
12853                            }),
12854                            None,
12855                            cx,
12856                        );
12857                    });
12858                }
12859            }
12860        });
12861        self.change_selections(None, cx, |selections| selections.refresh());
12862    }
12863
12864    pub fn to_pixel_point(
12865        &mut self,
12866        source: multi_buffer::Anchor,
12867        editor_snapshot: &EditorSnapshot,
12868        cx: &mut ViewContext<Self>,
12869    ) -> Option<gpui::Point<Pixels>> {
12870        let source_point = source.to_display_point(editor_snapshot);
12871        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12872    }
12873
12874    pub fn display_to_pixel_point(
12875        &mut self,
12876        source: DisplayPoint,
12877        editor_snapshot: &EditorSnapshot,
12878        cx: &mut ViewContext<Self>,
12879    ) -> Option<gpui::Point<Pixels>> {
12880        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12881        let text_layout_details = self.text_layout_details(cx);
12882        let scroll_top = text_layout_details
12883            .scroll_anchor
12884            .scroll_position(editor_snapshot)
12885            .y;
12886
12887        if source.row().as_f32() < scroll_top.floor() {
12888            return None;
12889        }
12890        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12891        let source_y = line_height * (source.row().as_f32() - scroll_top);
12892        Some(gpui::Point::new(source_x, source_y))
12893    }
12894
12895    pub fn has_active_completions_menu(&self) -> bool {
12896        self.context_menu.read().as_ref().map_or(false, |menu| {
12897            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12898        })
12899    }
12900
12901    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12902        self.addons
12903            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12904    }
12905
12906    pub fn unregister_addon<T: Addon>(&mut self) {
12907        self.addons.remove(&std::any::TypeId::of::<T>());
12908    }
12909
12910    pub fn addon<T: Addon>(&self) -> Option<&T> {
12911        let type_id = std::any::TypeId::of::<T>();
12912        self.addons
12913            .get(&type_id)
12914            .and_then(|item| item.to_any().downcast_ref::<T>())
12915    }
12916}
12917
12918fn hunks_for_selections(
12919    multi_buffer_snapshot: &MultiBufferSnapshot,
12920    selections: &[Selection<Anchor>],
12921) -> Vec<MultiBufferDiffHunk> {
12922    let buffer_rows_for_selections = selections.iter().map(|selection| {
12923        let head = selection.head();
12924        let tail = selection.tail();
12925        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12926        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12927        if start > end {
12928            end..start
12929        } else {
12930            start..end
12931        }
12932    });
12933
12934    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12935}
12936
12937pub fn hunks_for_rows(
12938    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12939    multi_buffer_snapshot: &MultiBufferSnapshot,
12940) -> Vec<MultiBufferDiffHunk> {
12941    let mut hunks = Vec::new();
12942    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12943        HashMap::default();
12944    for selected_multi_buffer_rows in rows {
12945        let query_rows =
12946            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12947        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12948            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12949            // when the caret is just above or just below the deleted hunk.
12950            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12951            let related_to_selection = if allow_adjacent {
12952                hunk.row_range.overlaps(&query_rows)
12953                    || hunk.row_range.start == query_rows.end
12954                    || hunk.row_range.end == query_rows.start
12955            } else {
12956                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12957                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12958                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12959                    || selected_multi_buffer_rows.end == hunk.row_range.start
12960            };
12961            if related_to_selection {
12962                if !processed_buffer_rows
12963                    .entry(hunk.buffer_id)
12964                    .or_default()
12965                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12966                {
12967                    continue;
12968                }
12969                hunks.push(hunk);
12970            }
12971        }
12972    }
12973
12974    hunks
12975}
12976
12977pub trait CollaborationHub {
12978    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12979    fn user_participant_indices<'a>(
12980        &self,
12981        cx: &'a AppContext,
12982    ) -> &'a HashMap<u64, ParticipantIndex>;
12983    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12984}
12985
12986impl CollaborationHub for Model<Project> {
12987    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12988        self.read(cx).collaborators()
12989    }
12990
12991    fn user_participant_indices<'a>(
12992        &self,
12993        cx: &'a AppContext,
12994    ) -> &'a HashMap<u64, ParticipantIndex> {
12995        self.read(cx).user_store().read(cx).participant_indices()
12996    }
12997
12998    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12999        let this = self.read(cx);
13000        let user_ids = this.collaborators().values().map(|c| c.user_id);
13001        this.user_store().read_with(cx, |user_store, cx| {
13002            user_store.participant_names(user_ids, cx)
13003        })
13004    }
13005}
13006
13007pub trait SemanticsProvider {
13008    fn hover(
13009        &self,
13010        buffer: &Model<Buffer>,
13011        position: text::Anchor,
13012        cx: &mut AppContext,
13013    ) -> Option<Task<Vec<project::Hover>>>;
13014
13015    fn inlay_hints(
13016        &self,
13017        buffer_handle: Model<Buffer>,
13018        range: Range<text::Anchor>,
13019        cx: &mut AppContext,
13020    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13021
13022    fn resolve_inlay_hint(
13023        &self,
13024        hint: InlayHint,
13025        buffer_handle: Model<Buffer>,
13026        server_id: LanguageServerId,
13027        cx: &mut AppContext,
13028    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13029
13030    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13031
13032    fn document_highlights(
13033        &self,
13034        buffer: &Model<Buffer>,
13035        position: text::Anchor,
13036        cx: &mut AppContext,
13037    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13038
13039    fn definitions(
13040        &self,
13041        buffer: &Model<Buffer>,
13042        position: text::Anchor,
13043        kind: GotoDefinitionKind,
13044        cx: &mut AppContext,
13045    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13046
13047    fn range_for_rename(
13048        &self,
13049        buffer: &Model<Buffer>,
13050        position: text::Anchor,
13051        cx: &mut AppContext,
13052    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13053
13054    fn perform_rename(
13055        &self,
13056        buffer: &Model<Buffer>,
13057        position: text::Anchor,
13058        new_name: String,
13059        cx: &mut AppContext,
13060    ) -> Option<Task<Result<ProjectTransaction>>>;
13061}
13062
13063pub trait CompletionProvider {
13064    fn completions(
13065        &self,
13066        buffer: &Model<Buffer>,
13067        buffer_position: text::Anchor,
13068        trigger: CompletionContext,
13069        cx: &mut ViewContext<Editor>,
13070    ) -> Task<Result<Vec<Completion>>>;
13071
13072    fn resolve_completions(
13073        &self,
13074        buffer: Model<Buffer>,
13075        completion_indices: Vec<usize>,
13076        completions: Arc<RwLock<Box<[Completion]>>>,
13077        cx: &mut ViewContext<Editor>,
13078    ) -> Task<Result<bool>>;
13079
13080    fn apply_additional_edits_for_completion(
13081        &self,
13082        buffer: Model<Buffer>,
13083        completion: Completion,
13084        push_to_history: bool,
13085        cx: &mut ViewContext<Editor>,
13086    ) -> Task<Result<Option<language::Transaction>>>;
13087
13088    fn is_completion_trigger(
13089        &self,
13090        buffer: &Model<Buffer>,
13091        position: language::Anchor,
13092        text: &str,
13093        trigger_in_words: bool,
13094        cx: &mut ViewContext<Editor>,
13095    ) -> bool;
13096
13097    fn sort_completions(&self) -> bool {
13098        true
13099    }
13100}
13101
13102pub trait CodeActionProvider {
13103    fn code_actions(
13104        &self,
13105        buffer: &Model<Buffer>,
13106        range: Range<text::Anchor>,
13107        cx: &mut WindowContext,
13108    ) -> Task<Result<Vec<CodeAction>>>;
13109
13110    fn apply_code_action(
13111        &self,
13112        buffer_handle: Model<Buffer>,
13113        action: CodeAction,
13114        excerpt_id: ExcerptId,
13115        push_to_history: bool,
13116        cx: &mut WindowContext,
13117    ) -> Task<Result<ProjectTransaction>>;
13118}
13119
13120impl CodeActionProvider for Model<Project> {
13121    fn code_actions(
13122        &self,
13123        buffer: &Model<Buffer>,
13124        range: Range<text::Anchor>,
13125        cx: &mut WindowContext,
13126    ) -> Task<Result<Vec<CodeAction>>> {
13127        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13128    }
13129
13130    fn apply_code_action(
13131        &self,
13132        buffer_handle: Model<Buffer>,
13133        action: CodeAction,
13134        _excerpt_id: ExcerptId,
13135        push_to_history: bool,
13136        cx: &mut WindowContext,
13137    ) -> Task<Result<ProjectTransaction>> {
13138        self.update(cx, |project, cx| {
13139            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13140        })
13141    }
13142}
13143
13144fn snippet_completions(
13145    project: &Project,
13146    buffer: &Model<Buffer>,
13147    buffer_position: text::Anchor,
13148    cx: &mut AppContext,
13149) -> Vec<Completion> {
13150    let language = buffer.read(cx).language_at(buffer_position);
13151    let language_name = language.as_ref().map(|language| language.lsp_id());
13152    let snippet_store = project.snippets().read(cx);
13153    let snippets = snippet_store.snippets_for(language_name, cx);
13154
13155    if snippets.is_empty() {
13156        return vec![];
13157    }
13158    let snapshot = buffer.read(cx).text_snapshot();
13159    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13160
13161    let scope = language.map(|language| language.default_scope());
13162    let classifier = CharClassifier::new(scope).for_completion(true);
13163    let mut last_word = chars
13164        .take_while(|c| classifier.is_word(*c))
13165        .collect::<String>();
13166    last_word = last_word.chars().rev().collect();
13167    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13168    let to_lsp = |point: &text::Anchor| {
13169        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13170        point_to_lsp(end)
13171    };
13172    let lsp_end = to_lsp(&buffer_position);
13173    snippets
13174        .into_iter()
13175        .filter_map(|snippet| {
13176            let matching_prefix = snippet
13177                .prefix
13178                .iter()
13179                .find(|prefix| prefix.starts_with(&last_word))?;
13180            let start = as_offset - last_word.len();
13181            let start = snapshot.anchor_before(start);
13182            let range = start..buffer_position;
13183            let lsp_start = to_lsp(&start);
13184            let lsp_range = lsp::Range {
13185                start: lsp_start,
13186                end: lsp_end,
13187            };
13188            Some(Completion {
13189                old_range: range,
13190                new_text: snippet.body.clone(),
13191                label: CodeLabel {
13192                    text: matching_prefix.clone(),
13193                    runs: vec![],
13194                    filter_range: 0..matching_prefix.len(),
13195                },
13196                server_id: LanguageServerId(usize::MAX),
13197                documentation: snippet.description.clone().map(Documentation::SingleLine),
13198                lsp_completion: lsp::CompletionItem {
13199                    label: snippet.prefix.first().unwrap().clone(),
13200                    kind: Some(CompletionItemKind::SNIPPET),
13201                    label_details: snippet.description.as_ref().map(|description| {
13202                        lsp::CompletionItemLabelDetails {
13203                            detail: Some(description.clone()),
13204                            description: None,
13205                        }
13206                    }),
13207                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13208                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13209                        lsp::InsertReplaceEdit {
13210                            new_text: snippet.body.clone(),
13211                            insert: lsp_range,
13212                            replace: lsp_range,
13213                        },
13214                    )),
13215                    filter_text: Some(snippet.body.clone()),
13216                    sort_text: Some(char::MAX.to_string()),
13217                    ..Default::default()
13218                },
13219                confirm: None,
13220            })
13221        })
13222        .collect()
13223}
13224
13225impl CompletionProvider for Model<Project> {
13226    fn completions(
13227        &self,
13228        buffer: &Model<Buffer>,
13229        buffer_position: text::Anchor,
13230        options: CompletionContext,
13231        cx: &mut ViewContext<Editor>,
13232    ) -> Task<Result<Vec<Completion>>> {
13233        self.update(cx, |project, cx| {
13234            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13235            let project_completions = project.completions(buffer, buffer_position, options, cx);
13236            cx.background_executor().spawn(async move {
13237                let mut completions = project_completions.await?;
13238                //let snippets = snippets.into_iter().;
13239                completions.extend(snippets);
13240                Ok(completions)
13241            })
13242        })
13243    }
13244
13245    fn resolve_completions(
13246        &self,
13247        buffer: Model<Buffer>,
13248        completion_indices: Vec<usize>,
13249        completions: Arc<RwLock<Box<[Completion]>>>,
13250        cx: &mut ViewContext<Editor>,
13251    ) -> Task<Result<bool>> {
13252        self.update(cx, |project, cx| {
13253            project.resolve_completions(buffer, completion_indices, completions, cx)
13254        })
13255    }
13256
13257    fn apply_additional_edits_for_completion(
13258        &self,
13259        buffer: Model<Buffer>,
13260        completion: Completion,
13261        push_to_history: bool,
13262        cx: &mut ViewContext<Editor>,
13263    ) -> Task<Result<Option<language::Transaction>>> {
13264        self.update(cx, |project, cx| {
13265            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13266        })
13267    }
13268
13269    fn is_completion_trigger(
13270        &self,
13271        buffer: &Model<Buffer>,
13272        position: language::Anchor,
13273        text: &str,
13274        trigger_in_words: bool,
13275        cx: &mut ViewContext<Editor>,
13276    ) -> bool {
13277        if !EditorSettings::get_global(cx).show_completions_on_input {
13278            return false;
13279        }
13280
13281        let mut chars = text.chars();
13282        let char = if let Some(char) = chars.next() {
13283            char
13284        } else {
13285            return false;
13286        };
13287        if chars.next().is_some() {
13288            return false;
13289        }
13290
13291        let buffer = buffer.read(cx);
13292        let classifier = buffer
13293            .snapshot()
13294            .char_classifier_at(position)
13295            .for_completion(true);
13296        if trigger_in_words && classifier.is_word(char) {
13297            return true;
13298        }
13299
13300        buffer
13301            .completion_triggers()
13302            .iter()
13303            .any(|string| string == text)
13304    }
13305}
13306
13307impl SemanticsProvider for Model<Project> {
13308    fn hover(
13309        &self,
13310        buffer: &Model<Buffer>,
13311        position: text::Anchor,
13312        cx: &mut AppContext,
13313    ) -> Option<Task<Vec<project::Hover>>> {
13314        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13315    }
13316
13317    fn document_highlights(
13318        &self,
13319        buffer: &Model<Buffer>,
13320        position: text::Anchor,
13321        cx: &mut AppContext,
13322    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13323        Some(self.update(cx, |project, cx| {
13324            project.document_highlights(buffer, position, cx)
13325        }))
13326    }
13327
13328    fn definitions(
13329        &self,
13330        buffer: &Model<Buffer>,
13331        position: text::Anchor,
13332        kind: GotoDefinitionKind,
13333        cx: &mut AppContext,
13334    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13335        Some(self.update(cx, |project, cx| match kind {
13336            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13337            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13338            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13339            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13340        }))
13341    }
13342
13343    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13344        // TODO: make this work for remote projects
13345        self.read(cx)
13346            .language_servers_for_buffer(buffer.read(cx), cx)
13347            .any(
13348                |(_, server)| match server.capabilities().inlay_hint_provider {
13349                    Some(lsp::OneOf::Left(enabled)) => enabled,
13350                    Some(lsp::OneOf::Right(_)) => true,
13351                    None => false,
13352                },
13353            )
13354    }
13355
13356    fn inlay_hints(
13357        &self,
13358        buffer_handle: Model<Buffer>,
13359        range: Range<text::Anchor>,
13360        cx: &mut AppContext,
13361    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13362        Some(self.update(cx, |project, cx| {
13363            project.inlay_hints(buffer_handle, range, cx)
13364        }))
13365    }
13366
13367    fn resolve_inlay_hint(
13368        &self,
13369        hint: InlayHint,
13370        buffer_handle: Model<Buffer>,
13371        server_id: LanguageServerId,
13372        cx: &mut AppContext,
13373    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13374        Some(self.update(cx, |project, cx| {
13375            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13376        }))
13377    }
13378
13379    fn range_for_rename(
13380        &self,
13381        buffer: &Model<Buffer>,
13382        position: text::Anchor,
13383        cx: &mut AppContext,
13384    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13385        Some(self.update(cx, |project, cx| {
13386            project.prepare_rename(buffer.clone(), position, cx)
13387        }))
13388    }
13389
13390    fn perform_rename(
13391        &self,
13392        buffer: &Model<Buffer>,
13393        position: text::Anchor,
13394        new_name: String,
13395        cx: &mut AppContext,
13396    ) -> Option<Task<Result<ProjectTransaction>>> {
13397        Some(self.update(cx, |project, cx| {
13398            project.perform_rename(buffer.clone(), position, new_name, cx)
13399        }))
13400    }
13401}
13402
13403fn inlay_hint_settings(
13404    location: Anchor,
13405    snapshot: &MultiBufferSnapshot,
13406    cx: &mut ViewContext<'_, Editor>,
13407) -> InlayHintSettings {
13408    let file = snapshot.file_at(location);
13409    let language = snapshot.language_at(location).map(|l| l.name());
13410    language_settings(language, file, cx).inlay_hints
13411}
13412
13413fn consume_contiguous_rows(
13414    contiguous_row_selections: &mut Vec<Selection<Point>>,
13415    selection: &Selection<Point>,
13416    display_map: &DisplaySnapshot,
13417    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13418) -> (MultiBufferRow, MultiBufferRow) {
13419    contiguous_row_selections.push(selection.clone());
13420    let start_row = MultiBufferRow(selection.start.row);
13421    let mut end_row = ending_row(selection, display_map);
13422
13423    while let Some(next_selection) = selections.peek() {
13424        if next_selection.start.row <= end_row.0 {
13425            end_row = ending_row(next_selection, display_map);
13426            contiguous_row_selections.push(selections.next().unwrap().clone());
13427        } else {
13428            break;
13429        }
13430    }
13431    (start_row, end_row)
13432}
13433
13434fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13435    if next_selection.end.column > 0 || next_selection.is_empty() {
13436        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13437    } else {
13438        MultiBufferRow(next_selection.end.row)
13439    }
13440}
13441
13442impl EditorSnapshot {
13443    pub fn remote_selections_in_range<'a>(
13444        &'a self,
13445        range: &'a Range<Anchor>,
13446        collaboration_hub: &dyn CollaborationHub,
13447        cx: &'a AppContext,
13448    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13449        let participant_names = collaboration_hub.user_names(cx);
13450        let participant_indices = collaboration_hub.user_participant_indices(cx);
13451        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13452        let collaborators_by_replica_id = collaborators_by_peer_id
13453            .iter()
13454            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13455            .collect::<HashMap<_, _>>();
13456        self.buffer_snapshot
13457            .selections_in_range(range, false)
13458            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13459                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13460                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13461                let user_name = participant_names.get(&collaborator.user_id).cloned();
13462                Some(RemoteSelection {
13463                    replica_id,
13464                    selection,
13465                    cursor_shape,
13466                    line_mode,
13467                    participant_index,
13468                    peer_id: collaborator.peer_id,
13469                    user_name,
13470                })
13471            })
13472    }
13473
13474    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13475        self.display_snapshot.buffer_snapshot.language_at(position)
13476    }
13477
13478    pub fn is_focused(&self) -> bool {
13479        self.is_focused
13480    }
13481
13482    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13483        self.placeholder_text.as_ref()
13484    }
13485
13486    pub fn scroll_position(&self) -> gpui::Point<f32> {
13487        self.scroll_anchor.scroll_position(&self.display_snapshot)
13488    }
13489
13490    fn gutter_dimensions(
13491        &self,
13492        font_id: FontId,
13493        font_size: Pixels,
13494        em_width: Pixels,
13495        em_advance: Pixels,
13496        max_line_number_width: Pixels,
13497        cx: &AppContext,
13498    ) -> GutterDimensions {
13499        if !self.show_gutter {
13500            return GutterDimensions::default();
13501        }
13502        let descent = cx.text_system().descent(font_id, font_size);
13503
13504        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13505            matches!(
13506                ProjectSettings::get_global(cx).git.git_gutter,
13507                Some(GitGutterSetting::TrackedFiles)
13508            )
13509        });
13510        let gutter_settings = EditorSettings::get_global(cx).gutter;
13511        let show_line_numbers = self
13512            .show_line_numbers
13513            .unwrap_or(gutter_settings.line_numbers);
13514        let line_gutter_width = if show_line_numbers {
13515            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13516            let min_width_for_number_on_gutter = em_advance * 4.0;
13517            max_line_number_width.max(min_width_for_number_on_gutter)
13518        } else {
13519            0.0.into()
13520        };
13521
13522        let show_code_actions = self
13523            .show_code_actions
13524            .unwrap_or(gutter_settings.code_actions);
13525
13526        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13527
13528        let git_blame_entries_width =
13529            self.git_blame_gutter_max_author_length
13530                .map(|max_author_length| {
13531                    // Length of the author name, but also space for the commit hash,
13532                    // the spacing and the timestamp.
13533                    let max_char_count = max_author_length
13534                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13535                        + 7 // length of commit sha
13536                        + 14 // length of max relative timestamp ("60 minutes ago")
13537                        + 4; // gaps and margins
13538
13539                    em_advance * max_char_count
13540                });
13541
13542        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13543        left_padding += if show_code_actions || show_runnables {
13544            em_width * 3.0
13545        } else if show_git_gutter && show_line_numbers {
13546            em_width * 2.0
13547        } else if show_git_gutter || show_line_numbers {
13548            em_width
13549        } else {
13550            px(0.)
13551        };
13552
13553        let right_padding = if gutter_settings.folds && show_line_numbers {
13554            em_width * 4.0
13555        } else if gutter_settings.folds {
13556            em_width * 3.0
13557        } else if show_line_numbers {
13558            em_width
13559        } else {
13560            px(0.)
13561        };
13562
13563        GutterDimensions {
13564            left_padding,
13565            right_padding,
13566            width: line_gutter_width + left_padding + right_padding,
13567            margin: -descent,
13568            git_blame_entries_width,
13569        }
13570    }
13571
13572    pub fn render_fold_toggle(
13573        &self,
13574        buffer_row: MultiBufferRow,
13575        row_contains_cursor: bool,
13576        editor: View<Editor>,
13577        cx: &mut WindowContext,
13578    ) -> Option<AnyElement> {
13579        let folded = self.is_line_folded(buffer_row);
13580
13581        if let Some(crease) = self
13582            .crease_snapshot
13583            .query_row(buffer_row, &self.buffer_snapshot)
13584        {
13585            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13586                if folded {
13587                    editor.update(cx, |editor, cx| {
13588                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13589                    });
13590                } else {
13591                    editor.update(cx, |editor, cx| {
13592                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13593                    });
13594                }
13595            });
13596
13597            Some((crease.render_toggle)(
13598                buffer_row,
13599                folded,
13600                toggle_callback,
13601                cx,
13602            ))
13603        } else if folded
13604            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13605        {
13606            Some(
13607                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13608                    .selected(folded)
13609                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13610                        if folded {
13611                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13612                        } else {
13613                            this.fold_at(&FoldAt { buffer_row }, cx);
13614                        }
13615                    }))
13616                    .into_any_element(),
13617            )
13618        } else {
13619            None
13620        }
13621    }
13622
13623    pub fn render_crease_trailer(
13624        &self,
13625        buffer_row: MultiBufferRow,
13626        cx: &mut WindowContext,
13627    ) -> Option<AnyElement> {
13628        let folded = self.is_line_folded(buffer_row);
13629        let crease = self
13630            .crease_snapshot
13631            .query_row(buffer_row, &self.buffer_snapshot)?;
13632        Some((crease.render_trailer)(buffer_row, folded, cx))
13633    }
13634}
13635
13636impl Deref for EditorSnapshot {
13637    type Target = DisplaySnapshot;
13638
13639    fn deref(&self) -> &Self::Target {
13640        &self.display_snapshot
13641    }
13642}
13643
13644#[derive(Clone, Debug, PartialEq, Eq)]
13645pub enum EditorEvent {
13646    InputIgnored {
13647        text: Arc<str>,
13648    },
13649    InputHandled {
13650        utf16_range_to_replace: Option<Range<isize>>,
13651        text: Arc<str>,
13652    },
13653    ExcerptsAdded {
13654        buffer: Model<Buffer>,
13655        predecessor: ExcerptId,
13656        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13657    },
13658    ExcerptsRemoved {
13659        ids: Vec<ExcerptId>,
13660    },
13661    ExcerptsEdited {
13662        ids: Vec<ExcerptId>,
13663    },
13664    ExcerptsExpanded {
13665        ids: Vec<ExcerptId>,
13666    },
13667    BufferEdited,
13668    Edited {
13669        transaction_id: clock::Lamport,
13670    },
13671    Reparsed(BufferId),
13672    Focused,
13673    FocusedIn,
13674    Blurred,
13675    DirtyChanged,
13676    Saved,
13677    TitleChanged,
13678    DiffBaseChanged,
13679    SelectionsChanged {
13680        local: bool,
13681    },
13682    ScrollPositionChanged {
13683        local: bool,
13684        autoscroll: bool,
13685    },
13686    Closed,
13687    TransactionUndone {
13688        transaction_id: clock::Lamport,
13689    },
13690    TransactionBegun {
13691        transaction_id: clock::Lamport,
13692    },
13693    Reloaded,
13694    CursorShapeChanged,
13695}
13696
13697impl EventEmitter<EditorEvent> for Editor {}
13698
13699impl FocusableView for Editor {
13700    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13701        self.focus_handle.clone()
13702    }
13703}
13704
13705impl Render for Editor {
13706    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13707        let settings = ThemeSettings::get_global(cx);
13708
13709        let mut text_style = match self.mode {
13710            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13711                color: cx.theme().colors().editor_foreground,
13712                font_family: settings.ui_font.family.clone(),
13713                font_features: settings.ui_font.features.clone(),
13714                font_fallbacks: settings.ui_font.fallbacks.clone(),
13715                font_size: rems(0.875).into(),
13716                font_weight: settings.ui_font.weight,
13717                line_height: relative(settings.buffer_line_height.value()),
13718                ..Default::default()
13719            },
13720            EditorMode::Full => TextStyle {
13721                color: cx.theme().colors().editor_foreground,
13722                font_family: settings.buffer_font.family.clone(),
13723                font_features: settings.buffer_font.features.clone(),
13724                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13725                font_size: settings.buffer_font_size(cx).into(),
13726                font_weight: settings.buffer_font.weight,
13727                line_height: relative(settings.buffer_line_height.value()),
13728                ..Default::default()
13729            },
13730        };
13731        if let Some(text_style_refinement) = &self.text_style_refinement {
13732            text_style.refine(text_style_refinement)
13733        }
13734
13735        let background = match self.mode {
13736            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13737            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13738            EditorMode::Full => cx.theme().colors().editor_background,
13739        };
13740
13741        EditorElement::new(
13742            cx.view(),
13743            EditorStyle {
13744                background,
13745                local_player: cx.theme().players().local(),
13746                text: text_style,
13747                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13748                syntax: cx.theme().syntax().clone(),
13749                status: cx.theme().status().clone(),
13750                inlay_hints_style: make_inlay_hints_style(cx),
13751                suggestions_style: HighlightStyle {
13752                    color: Some(cx.theme().status().predictive),
13753                    ..HighlightStyle::default()
13754                },
13755                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13756            },
13757        )
13758    }
13759}
13760
13761impl ViewInputHandler for Editor {
13762    fn text_for_range(
13763        &mut self,
13764        range_utf16: Range<usize>,
13765        cx: &mut ViewContext<Self>,
13766    ) -> Option<String> {
13767        Some(
13768            self.buffer
13769                .read(cx)
13770                .read(cx)
13771                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13772                .collect(),
13773        )
13774    }
13775
13776    fn selected_text_range(
13777        &mut self,
13778        ignore_disabled_input: bool,
13779        cx: &mut ViewContext<Self>,
13780    ) -> Option<UTF16Selection> {
13781        // Prevent the IME menu from appearing when holding down an alphabetic key
13782        // while input is disabled.
13783        if !ignore_disabled_input && !self.input_enabled {
13784            return None;
13785        }
13786
13787        let selection = self.selections.newest::<OffsetUtf16>(cx);
13788        let range = selection.range();
13789
13790        Some(UTF16Selection {
13791            range: range.start.0..range.end.0,
13792            reversed: selection.reversed,
13793        })
13794    }
13795
13796    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13797        let snapshot = self.buffer.read(cx).read(cx);
13798        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13799        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13800    }
13801
13802    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13803        self.clear_highlights::<InputComposition>(cx);
13804        self.ime_transaction.take();
13805    }
13806
13807    fn replace_text_in_range(
13808        &mut self,
13809        range_utf16: Option<Range<usize>>,
13810        text: &str,
13811        cx: &mut ViewContext<Self>,
13812    ) {
13813        if !self.input_enabled {
13814            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13815            return;
13816        }
13817
13818        self.transact(cx, |this, cx| {
13819            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13820                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13821                Some(this.selection_replacement_ranges(range_utf16, cx))
13822            } else {
13823                this.marked_text_ranges(cx)
13824            };
13825
13826            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13827                let newest_selection_id = this.selections.newest_anchor().id;
13828                this.selections
13829                    .all::<OffsetUtf16>(cx)
13830                    .iter()
13831                    .zip(ranges_to_replace.iter())
13832                    .find_map(|(selection, range)| {
13833                        if selection.id == newest_selection_id {
13834                            Some(
13835                                (range.start.0 as isize - selection.head().0 as isize)
13836                                    ..(range.end.0 as isize - selection.head().0 as isize),
13837                            )
13838                        } else {
13839                            None
13840                        }
13841                    })
13842            });
13843
13844            cx.emit(EditorEvent::InputHandled {
13845                utf16_range_to_replace: range_to_replace,
13846                text: text.into(),
13847            });
13848
13849            if let Some(new_selected_ranges) = new_selected_ranges {
13850                this.change_selections(None, cx, |selections| {
13851                    selections.select_ranges(new_selected_ranges)
13852                });
13853                this.backspace(&Default::default(), cx);
13854            }
13855
13856            this.handle_input(text, cx);
13857        });
13858
13859        if let Some(transaction) = self.ime_transaction {
13860            self.buffer.update(cx, |buffer, cx| {
13861                buffer.group_until_transaction(transaction, cx);
13862            });
13863        }
13864
13865        self.unmark_text(cx);
13866    }
13867
13868    fn replace_and_mark_text_in_range(
13869        &mut self,
13870        range_utf16: Option<Range<usize>>,
13871        text: &str,
13872        new_selected_range_utf16: Option<Range<usize>>,
13873        cx: &mut ViewContext<Self>,
13874    ) {
13875        if !self.input_enabled {
13876            return;
13877        }
13878
13879        let transaction = self.transact(cx, |this, cx| {
13880            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13881                let snapshot = this.buffer.read(cx).read(cx);
13882                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13883                    for marked_range in &mut marked_ranges {
13884                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13885                        marked_range.start.0 += relative_range_utf16.start;
13886                        marked_range.start =
13887                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13888                        marked_range.end =
13889                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13890                    }
13891                }
13892                Some(marked_ranges)
13893            } else if let Some(range_utf16) = range_utf16 {
13894                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13895                Some(this.selection_replacement_ranges(range_utf16, cx))
13896            } else {
13897                None
13898            };
13899
13900            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13901                let newest_selection_id = this.selections.newest_anchor().id;
13902                this.selections
13903                    .all::<OffsetUtf16>(cx)
13904                    .iter()
13905                    .zip(ranges_to_replace.iter())
13906                    .find_map(|(selection, range)| {
13907                        if selection.id == newest_selection_id {
13908                            Some(
13909                                (range.start.0 as isize - selection.head().0 as isize)
13910                                    ..(range.end.0 as isize - selection.head().0 as isize),
13911                            )
13912                        } else {
13913                            None
13914                        }
13915                    })
13916            });
13917
13918            cx.emit(EditorEvent::InputHandled {
13919                utf16_range_to_replace: range_to_replace,
13920                text: text.into(),
13921            });
13922
13923            if let Some(ranges) = ranges_to_replace {
13924                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13925            }
13926
13927            let marked_ranges = {
13928                let snapshot = this.buffer.read(cx).read(cx);
13929                this.selections
13930                    .disjoint_anchors()
13931                    .iter()
13932                    .map(|selection| {
13933                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13934                    })
13935                    .collect::<Vec<_>>()
13936            };
13937
13938            if text.is_empty() {
13939                this.unmark_text(cx);
13940            } else {
13941                this.highlight_text::<InputComposition>(
13942                    marked_ranges.clone(),
13943                    HighlightStyle {
13944                        underline: Some(UnderlineStyle {
13945                            thickness: px(1.),
13946                            color: None,
13947                            wavy: false,
13948                        }),
13949                        ..Default::default()
13950                    },
13951                    cx,
13952                );
13953            }
13954
13955            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13956            let use_autoclose = this.use_autoclose;
13957            let use_auto_surround = this.use_auto_surround;
13958            this.set_use_autoclose(false);
13959            this.set_use_auto_surround(false);
13960            this.handle_input(text, cx);
13961            this.set_use_autoclose(use_autoclose);
13962            this.set_use_auto_surround(use_auto_surround);
13963
13964            if let Some(new_selected_range) = new_selected_range_utf16 {
13965                let snapshot = this.buffer.read(cx).read(cx);
13966                let new_selected_ranges = marked_ranges
13967                    .into_iter()
13968                    .map(|marked_range| {
13969                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13970                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13971                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13972                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13973                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13974                    })
13975                    .collect::<Vec<_>>();
13976
13977                drop(snapshot);
13978                this.change_selections(None, cx, |selections| {
13979                    selections.select_ranges(new_selected_ranges)
13980                });
13981            }
13982        });
13983
13984        self.ime_transaction = self.ime_transaction.or(transaction);
13985        if let Some(transaction) = self.ime_transaction {
13986            self.buffer.update(cx, |buffer, cx| {
13987                buffer.group_until_transaction(transaction, cx);
13988            });
13989        }
13990
13991        if self.text_highlights::<InputComposition>(cx).is_none() {
13992            self.ime_transaction.take();
13993        }
13994    }
13995
13996    fn bounds_for_range(
13997        &mut self,
13998        range_utf16: Range<usize>,
13999        element_bounds: gpui::Bounds<Pixels>,
14000        cx: &mut ViewContext<Self>,
14001    ) -> Option<gpui::Bounds<Pixels>> {
14002        let text_layout_details = self.text_layout_details(cx);
14003        let style = &text_layout_details.editor_style;
14004        let font_id = cx.text_system().resolve_font(&style.text.font());
14005        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14006        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14007
14008        let em_width = cx
14009            .text_system()
14010            .typographic_bounds(font_id, font_size, 'm')
14011            .unwrap()
14012            .size
14013            .width;
14014
14015        let snapshot = self.snapshot(cx);
14016        let scroll_position = snapshot.scroll_position();
14017        let scroll_left = scroll_position.x * em_width;
14018
14019        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14020        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14021            + self.gutter_dimensions.width;
14022        let y = line_height * (start.row().as_f32() - scroll_position.y);
14023
14024        Some(Bounds {
14025            origin: element_bounds.origin + point(x, y),
14026            size: size(em_width, line_height),
14027        })
14028    }
14029}
14030
14031trait SelectionExt {
14032    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14033    fn spanned_rows(
14034        &self,
14035        include_end_if_at_line_start: bool,
14036        map: &DisplaySnapshot,
14037    ) -> Range<MultiBufferRow>;
14038}
14039
14040impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14041    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14042        let start = self
14043            .start
14044            .to_point(&map.buffer_snapshot)
14045            .to_display_point(map);
14046        let end = self
14047            .end
14048            .to_point(&map.buffer_snapshot)
14049            .to_display_point(map);
14050        if self.reversed {
14051            end..start
14052        } else {
14053            start..end
14054        }
14055    }
14056
14057    fn spanned_rows(
14058        &self,
14059        include_end_if_at_line_start: bool,
14060        map: &DisplaySnapshot,
14061    ) -> Range<MultiBufferRow> {
14062        let start = self.start.to_point(&map.buffer_snapshot);
14063        let mut end = self.end.to_point(&map.buffer_snapshot);
14064        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14065            end.row -= 1;
14066        }
14067
14068        let buffer_start = map.prev_line_boundary(start).0;
14069        let buffer_end = map.next_line_boundary(end).0;
14070        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14071    }
14072}
14073
14074impl<T: InvalidationRegion> InvalidationStack<T> {
14075    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14076    where
14077        S: Clone + ToOffset,
14078    {
14079        while let Some(region) = self.last() {
14080            let all_selections_inside_invalidation_ranges =
14081                if selections.len() == region.ranges().len() {
14082                    selections
14083                        .iter()
14084                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14085                        .all(|(selection, invalidation_range)| {
14086                            let head = selection.head().to_offset(buffer);
14087                            invalidation_range.start <= head && invalidation_range.end >= head
14088                        })
14089                } else {
14090                    false
14091                };
14092
14093            if all_selections_inside_invalidation_ranges {
14094                break;
14095            } else {
14096                self.pop();
14097            }
14098        }
14099    }
14100}
14101
14102impl<T> Default for InvalidationStack<T> {
14103    fn default() -> Self {
14104        Self(Default::default())
14105    }
14106}
14107
14108impl<T> Deref for InvalidationStack<T> {
14109    type Target = Vec<T>;
14110
14111    fn deref(&self) -> &Self::Target {
14112        &self.0
14113    }
14114}
14115
14116impl<T> DerefMut for InvalidationStack<T> {
14117    fn deref_mut(&mut self) -> &mut Self::Target {
14118        &mut self.0
14119    }
14120}
14121
14122impl InvalidationRegion for SnippetState {
14123    fn ranges(&self) -> &[Range<Anchor>] {
14124        &self.ranges[self.active_index]
14125    }
14126}
14127
14128pub fn diagnostic_block_renderer(
14129    diagnostic: Diagnostic,
14130    max_message_rows: Option<u8>,
14131    allow_closing: bool,
14132    _is_valid: bool,
14133) -> RenderBlock {
14134    let (text_without_backticks, code_ranges) =
14135        highlight_diagnostic_message(&diagnostic, max_message_rows);
14136
14137    Box::new(move |cx: &mut BlockContext| {
14138        let group_id: SharedString = cx.block_id.to_string().into();
14139
14140        let mut text_style = cx.text_style().clone();
14141        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14142        let theme_settings = ThemeSettings::get_global(cx);
14143        text_style.font_family = theme_settings.buffer_font.family.clone();
14144        text_style.font_style = theme_settings.buffer_font.style;
14145        text_style.font_features = theme_settings.buffer_font.features.clone();
14146        text_style.font_weight = theme_settings.buffer_font.weight;
14147
14148        let multi_line_diagnostic = diagnostic.message.contains('\n');
14149
14150        let buttons = |diagnostic: &Diagnostic| {
14151            if multi_line_diagnostic {
14152                v_flex()
14153            } else {
14154                h_flex()
14155            }
14156            .when(allow_closing, |div| {
14157                div.children(diagnostic.is_primary.then(|| {
14158                    IconButton::new("close-block", IconName::XCircle)
14159                        .icon_color(Color::Muted)
14160                        .size(ButtonSize::Compact)
14161                        .style(ButtonStyle::Transparent)
14162                        .visible_on_hover(group_id.clone())
14163                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14164                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14165                }))
14166            })
14167            .child(
14168                IconButton::new("copy-block", IconName::Copy)
14169                    .icon_color(Color::Muted)
14170                    .size(ButtonSize::Compact)
14171                    .style(ButtonStyle::Transparent)
14172                    .visible_on_hover(group_id.clone())
14173                    .on_click({
14174                        let message = diagnostic.message.clone();
14175                        move |_click, cx| {
14176                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14177                        }
14178                    })
14179                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14180            )
14181        };
14182
14183        let icon_size = buttons(&diagnostic)
14184            .into_any_element()
14185            .layout_as_root(AvailableSpace::min_size(), cx);
14186
14187        h_flex()
14188            .id(cx.block_id)
14189            .group(group_id.clone())
14190            .relative()
14191            .size_full()
14192            .pl(cx.gutter_dimensions.width)
14193            .w(cx.max_width + cx.gutter_dimensions.width)
14194            .child(
14195                div()
14196                    .flex()
14197                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14198                    .flex_shrink(),
14199            )
14200            .child(buttons(&diagnostic))
14201            .child(div().flex().flex_shrink_0().child(
14202                StyledText::new(text_without_backticks.clone()).with_highlights(
14203                    &text_style,
14204                    code_ranges.iter().map(|range| {
14205                        (
14206                            range.clone(),
14207                            HighlightStyle {
14208                                font_weight: Some(FontWeight::BOLD),
14209                                ..Default::default()
14210                            },
14211                        )
14212                    }),
14213                ),
14214            ))
14215            .into_any_element()
14216    })
14217}
14218
14219pub fn highlight_diagnostic_message(
14220    diagnostic: &Diagnostic,
14221    mut max_message_rows: Option<u8>,
14222) -> (SharedString, Vec<Range<usize>>) {
14223    let mut text_without_backticks = String::new();
14224    let mut code_ranges = Vec::new();
14225
14226    if let Some(source) = &diagnostic.source {
14227        text_without_backticks.push_str(source);
14228        code_ranges.push(0..source.len());
14229        text_without_backticks.push_str(": ");
14230    }
14231
14232    let mut prev_offset = 0;
14233    let mut in_code_block = false;
14234    let has_row_limit = max_message_rows.is_some();
14235    let mut newline_indices = diagnostic
14236        .message
14237        .match_indices('\n')
14238        .filter(|_| has_row_limit)
14239        .map(|(ix, _)| ix)
14240        .fuse()
14241        .peekable();
14242
14243    for (quote_ix, _) in diagnostic
14244        .message
14245        .match_indices('`')
14246        .chain([(diagnostic.message.len(), "")])
14247    {
14248        let mut first_newline_ix = None;
14249        let mut last_newline_ix = None;
14250        while let Some(newline_ix) = newline_indices.peek() {
14251            if *newline_ix < quote_ix {
14252                if first_newline_ix.is_none() {
14253                    first_newline_ix = Some(*newline_ix);
14254                }
14255                last_newline_ix = Some(*newline_ix);
14256
14257                if let Some(rows_left) = &mut max_message_rows {
14258                    if *rows_left == 0 {
14259                        break;
14260                    } else {
14261                        *rows_left -= 1;
14262                    }
14263                }
14264                let _ = newline_indices.next();
14265            } else {
14266                break;
14267            }
14268        }
14269        let prev_len = text_without_backticks.len();
14270        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14271        text_without_backticks.push_str(new_text);
14272        if in_code_block {
14273            code_ranges.push(prev_len..text_without_backticks.len());
14274        }
14275        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14276        in_code_block = !in_code_block;
14277        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14278            text_without_backticks.push_str("...");
14279            break;
14280        }
14281    }
14282
14283    (text_without_backticks.into(), code_ranges)
14284}
14285
14286fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14287    match severity {
14288        DiagnosticSeverity::ERROR => colors.error,
14289        DiagnosticSeverity::WARNING => colors.warning,
14290        DiagnosticSeverity::INFORMATION => colors.info,
14291        DiagnosticSeverity::HINT => colors.info,
14292        _ => colors.ignored,
14293    }
14294}
14295
14296pub fn styled_runs_for_code_label<'a>(
14297    label: &'a CodeLabel,
14298    syntax_theme: &'a theme::SyntaxTheme,
14299) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14300    let fade_out = HighlightStyle {
14301        fade_out: Some(0.35),
14302        ..Default::default()
14303    };
14304
14305    let mut prev_end = label.filter_range.end;
14306    label
14307        .runs
14308        .iter()
14309        .enumerate()
14310        .flat_map(move |(ix, (range, highlight_id))| {
14311            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14312                style
14313            } else {
14314                return Default::default();
14315            };
14316            let mut muted_style = style;
14317            muted_style.highlight(fade_out);
14318
14319            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14320            if range.start >= label.filter_range.end {
14321                if range.start > prev_end {
14322                    runs.push((prev_end..range.start, fade_out));
14323                }
14324                runs.push((range.clone(), muted_style));
14325            } else if range.end <= label.filter_range.end {
14326                runs.push((range.clone(), style));
14327            } else {
14328                runs.push((range.start..label.filter_range.end, style));
14329                runs.push((label.filter_range.end..range.end, muted_style));
14330            }
14331            prev_end = cmp::max(prev_end, range.end);
14332
14333            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14334                runs.push((prev_end..label.text.len(), fade_out));
14335            }
14336
14337            runs
14338        })
14339}
14340
14341pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14342    let mut prev_index = 0;
14343    let mut prev_codepoint: Option<char> = None;
14344    text.char_indices()
14345        .chain([(text.len(), '\0')])
14346        .filter_map(move |(index, codepoint)| {
14347            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14348            let is_boundary = index == text.len()
14349                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14350                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14351            if is_boundary {
14352                let chunk = &text[prev_index..index];
14353                prev_index = index;
14354                Some(chunk)
14355            } else {
14356                None
14357            }
14358        })
14359}
14360
14361pub trait RangeToAnchorExt: Sized {
14362    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14363
14364    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14365        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14366        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14367    }
14368}
14369
14370impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14371    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14372        let start_offset = self.start.to_offset(snapshot);
14373        let end_offset = self.end.to_offset(snapshot);
14374        if start_offset == end_offset {
14375            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14376        } else {
14377            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14378        }
14379    }
14380}
14381
14382pub trait RowExt {
14383    fn as_f32(&self) -> f32;
14384
14385    fn next_row(&self) -> Self;
14386
14387    fn previous_row(&self) -> Self;
14388
14389    fn minus(&self, other: Self) -> u32;
14390}
14391
14392impl RowExt for DisplayRow {
14393    fn as_f32(&self) -> f32 {
14394        self.0 as f32
14395    }
14396
14397    fn next_row(&self) -> Self {
14398        Self(self.0 + 1)
14399    }
14400
14401    fn previous_row(&self) -> Self {
14402        Self(self.0.saturating_sub(1))
14403    }
14404
14405    fn minus(&self, other: Self) -> u32 {
14406        self.0 - other.0
14407    }
14408}
14409
14410impl RowExt for MultiBufferRow {
14411    fn as_f32(&self) -> f32 {
14412        self.0 as f32
14413    }
14414
14415    fn next_row(&self) -> Self {
14416        Self(self.0 + 1)
14417    }
14418
14419    fn previous_row(&self) -> Self {
14420        Self(self.0.saturating_sub(1))
14421    }
14422
14423    fn minus(&self, other: Self) -> u32 {
14424        self.0 - other.0
14425    }
14426}
14427
14428trait RowRangeExt {
14429    type Row;
14430
14431    fn len(&self) -> usize;
14432
14433    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14434}
14435
14436impl RowRangeExt for Range<MultiBufferRow> {
14437    type Row = MultiBufferRow;
14438
14439    fn len(&self) -> usize {
14440        (self.end.0 - self.start.0) as usize
14441    }
14442
14443    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14444        (self.start.0..self.end.0).map(MultiBufferRow)
14445    }
14446}
14447
14448impl RowRangeExt for Range<DisplayRow> {
14449    type Row = DisplayRow;
14450
14451    fn len(&self) -> usize {
14452        (self.end.0 - self.start.0) as usize
14453    }
14454
14455    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14456        (self.start.0..self.end.0).map(DisplayRow)
14457    }
14458}
14459
14460fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14461    if hunk.diff_base_byte_range.is_empty() {
14462        DiffHunkStatus::Added
14463    } else if hunk.row_range.is_empty() {
14464        DiffHunkStatus::Removed
14465    } else {
14466        DiffHunkStatus::Modified
14467    }
14468}
14469
14470/// If select range has more than one line, we
14471/// just point the cursor to range.start.
14472fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14473    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14474        range
14475    } else {
14476        range.start..range.start
14477    }
14478}