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::*;
   52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use debounced_delay::DebouncedDelay;
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::{StringMatch, StringMatchCandidate};
   73use git::blame::GitBlame;
   74use gpui::{
   75    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   76    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   77    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   78    FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   79    ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   80    ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
   81    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   82    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   83};
   84use highlight_matching_bracket::refresh_matching_bracket_highlights;
   85use hover_popover::{hide_hover, HoverState};
   86pub(crate) use hunk_diff::HoveredHunk;
   87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   88use indent_guides::ActiveIndentGuidesState;
   89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   90pub use inline_completion_provider::*;
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  100use linked_editing_ranges::refresh_linked_ranges;
  101pub use proposed_changes_editor::{
  102    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  103};
  104use similar::{ChangeTag, TextDiff};
  105use std::iter::Peekable;
  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, LanguageServerName,
  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, ProjectTransaction, TaskSourceKind,
  130};
  131use rand::prelude::*;
  132use rpc::{proto::*, ErrorExt};
  133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  134use selections_collection::{
  135    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  136};
  137use serde::{Deserialize, Serialize};
  138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  139use smallvec::SmallVec;
  140use snippet::Snippet;
  141use std::{
  142    any::TypeId,
  143    borrow::Cow,
  144    cell::RefCell,
  145    cmp::{self, Ordering, Reverse},
  146    mem,
  147    num::NonZeroU32,
  148    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  149    path::{Path, PathBuf},
  150    rc::Rc,
  151    sync::Arc,
  152    time::{Duration, Instant},
  153};
  154pub use sum_tree::Bias;
  155use sum_tree::TreeMap;
  156use text::{BufferId, OffsetUtf16, Rope};
  157use theme::{
  158    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  159    ThemeColors, ThemeSettings,
  160};
  161use ui::{
  162    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  163    ListItem, Popover, PopoverMenuHandle, Tooltip,
  164};
  165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  166use workspace::item::{ItemHandle, PreviewTabsSettings};
  167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  168use workspace::{
  169    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  170};
  171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  172
  173use crate::hover_links::find_url;
  174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  175
  176pub const FILE_HEADER_HEIGHT: u32 = 2;
  177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  181const MAX_LINE_LEN: usize = 1024;
  182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  185#[doc(hidden)]
  186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  187#[doc(hidden)]
  188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub fn render_parsed_markdown(
  194    element_id: impl Into<ElementId>,
  195    parsed: &language::ParsedMarkdown,
  196    editor_style: &EditorStyle,
  197    workspace: Option<WeakView<Workspace>>,
  198    cx: &mut WindowContext,
  199) -> InteractiveText {
  200    let code_span_background_color = cx
  201        .theme()
  202        .colors()
  203        .editor_document_highlight_read_background;
  204
  205    let highlights = gpui::combine_highlights(
  206        parsed.highlights.iter().filter_map(|(range, highlight)| {
  207            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  208            Some((range.clone(), highlight))
  209        }),
  210        parsed
  211            .regions
  212            .iter()
  213            .zip(&parsed.region_ranges)
  214            .filter_map(|(region, range)| {
  215                if region.code {
  216                    Some((
  217                        range.clone(),
  218                        HighlightStyle {
  219                            background_color: Some(code_span_background_color),
  220                            ..Default::default()
  221                        },
  222                    ))
  223                } else {
  224                    None
  225                }
  226            }),
  227    );
  228
  229    let mut links = Vec::new();
  230    let mut link_ranges = Vec::new();
  231    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  232        if let Some(link) = region.link.clone() {
  233            links.push(link);
  234            link_ranges.push(range.clone());
  235        }
  236    }
  237
  238    InteractiveText::new(
  239        element_id,
  240        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  241    )
  242    .on_click(link_ranges, move |clicked_range_ix, cx| {
  243        match &links[clicked_range_ix] {
  244            markdown::Link::Web { url } => cx.open_url(url),
  245            markdown::Link::Path { path } => {
  246                if let Some(workspace) = &workspace {
  247                    _ = workspace.update(cx, |workspace, cx| {
  248                        workspace.open_abs_path(path.clone(), false, cx).detach();
  249                    });
  250                }
  251            }
  252        }
  253    })
  254}
  255
  256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  257pub(crate) enum InlayId {
  258    Suggestion(usize),
  259    Hint(usize),
  260}
  261
  262impl InlayId {
  263    fn id(&self) -> usize {
  264        match self {
  265            Self::Suggestion(id) => *id,
  266            Self::Hint(id) => *id,
  267        }
  268    }
  269}
  270
  271enum DiffRowHighlight {}
  272enum DocumentHighlightRead {}
  273enum DocumentHighlightWrite {}
  274enum InputComposition {}
  275
  276#[derive(Copy, Clone, PartialEq, Eq)]
  277pub enum Direction {
  278    Prev,
  279    Next,
  280}
  281
  282#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  283pub enum Navigated {
  284    Yes,
  285    No,
  286}
  287
  288impl Navigated {
  289    pub fn from_bool(yes: bool) -> Navigated {
  290        if yes {
  291            Navigated::Yes
  292        } else {
  293            Navigated::No
  294        }
  295    }
  296}
  297
  298pub fn init_settings(cx: &mut AppContext) {
  299    EditorSettings::register(cx);
  300}
  301
  302pub fn init(cx: &mut AppContext) {
  303    init_settings(cx);
  304
  305    workspace::register_project_item::<Editor>(cx);
  306    workspace::FollowableViewRegistry::register::<Editor>(cx);
  307    workspace::register_serializable_item::<Editor>(cx);
  308
  309    cx.observe_new_views(
  310        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  311            workspace.register_action(Editor::new_file);
  312            workspace.register_action(Editor::new_file_vertical);
  313            workspace.register_action(Editor::new_file_horizontal);
  314        },
  315    )
  316    .detach();
  317
  318    cx.on_action(move |_: &workspace::NewFile, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  322                Editor::new_file(workspace, &Default::default(), cx)
  323            })
  324            .detach();
  325        }
  326    });
  327    cx.on_action(move |_: &workspace::NewWindow, cx| {
  328        let app_state = workspace::AppState::global(cx);
  329        if let Some(app_state) = app_state.upgrade() {
  330            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  331                Editor::new_file(workspace, &Default::default(), cx)
  332            })
  333            .detach();
  334        }
  335    });
  336}
  337
  338pub struct SearchWithinRange;
  339
  340trait InvalidationRegion {
  341    fn ranges(&self) -> &[Range<Anchor>];
  342}
  343
  344#[derive(Clone, Debug, PartialEq)]
  345pub enum SelectPhase {
  346    Begin {
  347        position: DisplayPoint,
  348        add: bool,
  349        click_count: usize,
  350    },
  351    BeginColumnar {
  352        position: DisplayPoint,
  353        reset: bool,
  354        goal_column: u32,
  355    },
  356    Extend {
  357        position: DisplayPoint,
  358        click_count: usize,
  359    },
  360    Update {
  361        position: DisplayPoint,
  362        goal_column: u32,
  363        scroll_delta: gpui::Point<f32>,
  364    },
  365    End,
  366}
  367
  368#[derive(Clone, Debug)]
  369pub enum SelectMode {
  370    Character,
  371    Word(Range<Anchor>),
  372    Line(Range<Anchor>),
  373    All,
  374}
  375
  376#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  377pub enum EditorMode {
  378    SingleLine { auto_width: bool },
  379    AutoHeight { max_lines: usize },
  380    Full,
  381}
  382
  383#[derive(Copy, Clone, Debug)]
  384pub enum SoftWrap {
  385    /// Prefer not to wrap at all.
  386    ///
  387    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  388    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  389    GitDiff,
  390    /// Prefer a single line generally, unless an overly long line is encountered.
  391    None,
  392    /// Soft wrap lines that exceed the editor width.
  393    EditorWidth,
  394    /// Soft wrap lines at the preferred line length.
  395    Column(u32),
  396    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  397    Bounded(u32),
  398}
  399
  400#[derive(Clone)]
  401pub struct EditorStyle {
  402    pub background: Hsla,
  403    pub local_player: PlayerColor,
  404    pub text: TextStyle,
  405    pub scrollbar_width: Pixels,
  406    pub syntax: Arc<SyntaxTheme>,
  407    pub status: StatusColors,
  408    pub inlay_hints_style: HighlightStyle,
  409    pub suggestions_style: HighlightStyle,
  410    pub unnecessary_code_fade: f32,
  411}
  412
  413impl Default for EditorStyle {
  414    fn default() -> Self {
  415        Self {
  416            background: Hsla::default(),
  417            local_player: PlayerColor::default(),
  418            text: TextStyle::default(),
  419            scrollbar_width: Pixels::default(),
  420            syntax: Default::default(),
  421            // HACK: Status colors don't have a real default.
  422            // We should look into removing the status colors from the editor
  423            // style and retrieve them directly from the theme.
  424            status: StatusColors::dark(),
  425            inlay_hints_style: HighlightStyle::default(),
  426            suggestions_style: HighlightStyle::default(),
  427            unnecessary_code_fade: Default::default(),
  428        }
  429    }
  430}
  431
  432pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  433    let show_background = language_settings::language_settings(None, None, cx)
  434        .inlay_hints
  435        .show_background;
  436
  437    HighlightStyle {
  438        color: Some(cx.theme().status().hint),
  439        background_color: show_background.then(|| cx.theme().status().hint_background),
  440        ..HighlightStyle::default()
  441    }
  442}
  443
  444type CompletionId = usize;
  445
  446#[derive(Clone, Debug)]
  447struct CompletionState {
  448    // render_inlay_ids represents the inlay hints that are inserted
  449    // for rendering the inline completions. They may be discontinuous
  450    // in the event that the completion provider returns some intersection
  451    // with the existing content.
  452    render_inlay_ids: Vec<InlayId>,
  453    // text is the resulting rope that is inserted when the user accepts a completion.
  454    text: Rope,
  455    // position is the position of the cursor when the completion was triggered.
  456    position: multi_buffer::Anchor,
  457    // delete_range is the range of text that this completion state covers.
  458    // if the completion is accepted, this range should be deleted.
  459    delete_range: Option<Range<multi_buffer::Anchor>>,
  460}
  461
  462#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  463struct EditorActionId(usize);
  464
  465impl EditorActionId {
  466    pub fn post_inc(&mut self) -> Self {
  467        let answer = self.0;
  468
  469        *self = Self(answer + 1);
  470
  471        Self(answer)
  472    }
  473}
  474
  475// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  476// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  477
  478type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  479type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  480
  481#[derive(Default)]
  482struct ScrollbarMarkerState {
  483    scrollbar_size: Size<Pixels>,
  484    dirty: bool,
  485    markers: Arc<[PaintQuad]>,
  486    pending_refresh: Option<Task<Result<()>>>,
  487}
  488
  489impl ScrollbarMarkerState {
  490    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  491        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  492    }
  493}
  494
  495#[derive(Clone, Debug)]
  496struct RunnableTasks {
  497    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  498    offset: MultiBufferOffset,
  499    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  500    column: u32,
  501    // Values of all named captures, including those starting with '_'
  502    extra_variables: HashMap<String, String>,
  503    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  504    context_range: Range<BufferOffset>,
  505}
  506
  507impl RunnableTasks {
  508    fn resolve<'a>(
  509        &'a self,
  510        cx: &'a task::TaskContext,
  511    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  512        self.templates.iter().filter_map(|(kind, template)| {
  513            template
  514                .resolve_task(&kind.to_id_base(), cx)
  515                .map(|task| (kind.clone(), task))
  516        })
  517    }
  518}
  519
  520#[derive(Clone)]
  521struct ResolvedTasks {
  522    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  523    position: Anchor,
  524}
  525#[derive(Copy, Clone, Debug)]
  526struct MultiBufferOffset(usize);
  527#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  528struct BufferOffset(usize);
  529
  530// Addons allow storing per-editor state in other crates (e.g. Vim)
  531pub trait Addon: 'static {
  532    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  533
  534    fn to_any(&self) -> &dyn std::any::Any;
  535}
  536
  537#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  538pub enum IsVimMode {
  539    Yes,
  540    No,
  541}
  542
  543/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  544///
  545/// See the [module level documentation](self) for more information.
  546pub struct Editor {
  547    focus_handle: FocusHandle,
  548    last_focused_descendant: Option<WeakFocusHandle>,
  549    /// The text buffer being edited
  550    buffer: Model<MultiBuffer>,
  551    /// Map of how text in the buffer should be displayed.
  552    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  553    pub display_map: Model<DisplayMap>,
  554    pub selections: SelectionsCollection,
  555    pub scroll_manager: ScrollManager,
  556    /// When inline assist editors are linked, they all render cursors because
  557    /// typing enters text into each of them, even the ones that aren't focused.
  558    pub(crate) show_cursor_when_unfocused: bool,
  559    columnar_selection_tail: Option<Anchor>,
  560    add_selections_state: Option<AddSelectionsState>,
  561    select_next_state: Option<SelectNextState>,
  562    select_prev_state: Option<SelectNextState>,
  563    selection_history: SelectionHistory,
  564    autoclose_regions: Vec<AutocloseRegion>,
  565    snippet_stack: InvalidationStack<SnippetState>,
  566    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  567    ime_transaction: Option<TransactionId>,
  568    active_diagnostics: Option<ActiveDiagnosticGroup>,
  569    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  570
  571    project: Option<Model<Project>>,
  572    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  573    completion_provider: Option<Box<dyn CompletionProvider>>,
  574    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  575    blink_manager: Model<BlinkManager>,
  576    show_cursor_names: bool,
  577    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  578    pub show_local_selections: bool,
  579    mode: EditorMode,
  580    show_breadcrumbs: bool,
  581    show_gutter: bool,
  582    show_line_numbers: Option<bool>,
  583    use_relative_line_numbers: Option<bool>,
  584    show_git_diff_gutter: Option<bool>,
  585    show_code_actions: Option<bool>,
  586    show_runnables: Option<bool>,
  587    show_wrap_guides: Option<bool>,
  588    show_indent_guides: Option<bool>,
  589    placeholder_text: Option<Arc<str>>,
  590    highlight_order: usize,
  591    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  592    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  593    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  594    scrollbar_marker_state: ScrollbarMarkerState,
  595    active_indent_guides_state: ActiveIndentGuidesState,
  596    nav_history: Option<ItemNavHistory>,
  597    context_menu: RwLock<Option<ContextMenu>>,
  598    mouse_context_menu: Option<MouseContextMenu>,
  599    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  600    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  601    signature_help_state: SignatureHelpState,
  602    auto_signature_help: Option<bool>,
  603    find_all_references_task_sources: Vec<Anchor>,
  604    next_completion_id: CompletionId,
  605    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  606    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  607    code_actions_task: Option<Task<Result<()>>>,
  608    document_highlights_task: Option<Task<()>>,
  609    linked_editing_range_task: Option<Task<Option<()>>>,
  610    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  611    pending_rename: Option<RenameState>,
  612    searchable: bool,
  613    cursor_shape: CursorShape,
  614    current_line_highlight: Option<CurrentLineHighlight>,
  615    collapse_matches: bool,
  616    autoindent_mode: Option<AutoindentMode>,
  617    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  618    input_enabled: bool,
  619    use_modal_editing: bool,
  620    read_only: bool,
  621    leader_peer_id: Option<PeerId>,
  622    remote_id: Option<ViewId>,
  623    hover_state: HoverState,
  624    gutter_hovered: bool,
  625    hovered_link_state: Option<HoveredLinkState>,
  626    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  627    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  628    active_inline_completion: Option<CompletionState>,
  629    // enable_inline_completions is a switch that Vim can use to disable
  630    // inline completions based on its mode.
  631    enable_inline_completions: bool,
  632    show_inline_completions_override: Option<bool>,
  633    inlay_hint_cache: InlayHintCache,
  634    expanded_hunks: ExpandedHunks,
  635    next_inlay_id: usize,
  636    _subscriptions: Vec<Subscription>,
  637    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  638    gutter_dimensions: GutterDimensions,
  639    style: Option<EditorStyle>,
  640    text_style_refinement: Option<TextStyleRefinement>,
  641    next_editor_action_id: EditorActionId,
  642    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  643    use_autoclose: bool,
  644    use_auto_surround: bool,
  645    auto_replace_emoji_shortcode: bool,
  646    show_git_blame_gutter: bool,
  647    show_git_blame_inline: bool,
  648    show_git_blame_inline_delay_task: Option<Task<()>>,
  649    git_blame_inline_enabled: bool,
  650    serialize_dirty_buffers: bool,
  651    show_selection_menu: Option<bool>,
  652    blame: Option<Model<GitBlame>>,
  653    blame_subscription: Option<Subscription>,
  654    custom_context_menu: Option<
  655        Box<
  656            dyn 'static
  657                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  658        >,
  659    >,
  660    last_bounds: Option<Bounds<Pixels>>,
  661    expect_bounds_change: Option<Bounds<Pixels>>,
  662    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  663    tasks_update_task: Option<Task<()>>,
  664    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  665    breadcrumb_header: Option<String>,
  666    focused_block: Option<FocusedBlock>,
  667    next_scroll_position: NextScrollCursorCenterTopBottom,
  668    addons: HashMap<TypeId, Box<dyn Addon>>,
  669    _scroll_cursor_center_top_bottom_task: Task<()>,
  670}
  671
  672#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  673enum NextScrollCursorCenterTopBottom {
  674    #[default]
  675    Center,
  676    Top,
  677    Bottom,
  678}
  679
  680impl NextScrollCursorCenterTopBottom {
  681    fn next(&self) -> Self {
  682        match self {
  683            Self::Center => Self::Top,
  684            Self::Top => Self::Bottom,
  685            Self::Bottom => Self::Center,
  686        }
  687    }
  688}
  689
  690#[derive(Clone)]
  691pub struct EditorSnapshot {
  692    pub mode: EditorMode,
  693    show_gutter: bool,
  694    show_line_numbers: Option<bool>,
  695    show_git_diff_gutter: Option<bool>,
  696    show_code_actions: Option<bool>,
  697    show_runnables: Option<bool>,
  698    git_blame_gutter_max_author_length: Option<usize>,
  699    pub display_snapshot: DisplaySnapshot,
  700    pub placeholder_text: Option<Arc<str>>,
  701    is_focused: bool,
  702    scroll_anchor: ScrollAnchor,
  703    ongoing_scroll: OngoingScroll,
  704    current_line_highlight: CurrentLineHighlight,
  705    gutter_hovered: bool,
  706}
  707
  708const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  709
  710#[derive(Default, Debug, Clone, Copy)]
  711pub struct GutterDimensions {
  712    pub left_padding: Pixels,
  713    pub right_padding: Pixels,
  714    pub width: Pixels,
  715    pub margin: Pixels,
  716    pub git_blame_entries_width: Option<Pixels>,
  717}
  718
  719impl GutterDimensions {
  720    /// The full width of the space taken up by the gutter.
  721    pub fn full_width(&self) -> Pixels {
  722        self.margin + self.width
  723    }
  724
  725    /// The width of the space reserved for the fold indicators,
  726    /// use alongside 'justify_end' and `gutter_width` to
  727    /// right align content with the line numbers
  728    pub fn fold_area_width(&self) -> Pixels {
  729        self.margin + self.right_padding
  730    }
  731}
  732
  733#[derive(Debug)]
  734pub struct RemoteSelection {
  735    pub replica_id: ReplicaId,
  736    pub selection: Selection<Anchor>,
  737    pub cursor_shape: CursorShape,
  738    pub peer_id: PeerId,
  739    pub line_mode: bool,
  740    pub participant_index: Option<ParticipantIndex>,
  741    pub user_name: Option<SharedString>,
  742}
  743
  744#[derive(Clone, Debug)]
  745struct SelectionHistoryEntry {
  746    selections: Arc<[Selection<Anchor>]>,
  747    select_next_state: Option<SelectNextState>,
  748    select_prev_state: Option<SelectNextState>,
  749    add_selections_state: Option<AddSelectionsState>,
  750}
  751
  752enum SelectionHistoryMode {
  753    Normal,
  754    Undoing,
  755    Redoing,
  756}
  757
  758#[derive(Clone, PartialEq, Eq, Hash)]
  759struct HoveredCursor {
  760    replica_id: u16,
  761    selection_id: usize,
  762}
  763
  764impl Default for SelectionHistoryMode {
  765    fn default() -> Self {
  766        Self::Normal
  767    }
  768}
  769
  770#[derive(Default)]
  771struct SelectionHistory {
  772    #[allow(clippy::type_complexity)]
  773    selections_by_transaction:
  774        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  775    mode: SelectionHistoryMode,
  776    undo_stack: VecDeque<SelectionHistoryEntry>,
  777    redo_stack: VecDeque<SelectionHistoryEntry>,
  778}
  779
  780impl SelectionHistory {
  781    fn insert_transaction(
  782        &mut self,
  783        transaction_id: TransactionId,
  784        selections: Arc<[Selection<Anchor>]>,
  785    ) {
  786        self.selections_by_transaction
  787            .insert(transaction_id, (selections, None));
  788    }
  789
  790    #[allow(clippy::type_complexity)]
  791    fn transaction(
  792        &self,
  793        transaction_id: TransactionId,
  794    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  795        self.selections_by_transaction.get(&transaction_id)
  796    }
  797
  798    #[allow(clippy::type_complexity)]
  799    fn transaction_mut(
  800        &mut self,
  801        transaction_id: TransactionId,
  802    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  803        self.selections_by_transaction.get_mut(&transaction_id)
  804    }
  805
  806    fn push(&mut self, entry: SelectionHistoryEntry) {
  807        if !entry.selections.is_empty() {
  808            match self.mode {
  809                SelectionHistoryMode::Normal => {
  810                    self.push_undo(entry);
  811                    self.redo_stack.clear();
  812                }
  813                SelectionHistoryMode::Undoing => self.push_redo(entry),
  814                SelectionHistoryMode::Redoing => self.push_undo(entry),
  815            }
  816        }
  817    }
  818
  819    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  820        if self
  821            .undo_stack
  822            .back()
  823            .map_or(true, |e| e.selections != entry.selections)
  824        {
  825            self.undo_stack.push_back(entry);
  826            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  827                self.undo_stack.pop_front();
  828            }
  829        }
  830    }
  831
  832    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  833        if self
  834            .redo_stack
  835            .back()
  836            .map_or(true, |e| e.selections != entry.selections)
  837        {
  838            self.redo_stack.push_back(entry);
  839            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  840                self.redo_stack.pop_front();
  841            }
  842        }
  843    }
  844}
  845
  846struct RowHighlight {
  847    index: usize,
  848    range: Range<Anchor>,
  849    color: Hsla,
  850    should_autoscroll: bool,
  851}
  852
  853#[derive(Clone, Debug)]
  854struct AddSelectionsState {
  855    above: bool,
  856    stack: Vec<usize>,
  857}
  858
  859#[derive(Clone)]
  860struct SelectNextState {
  861    query: AhoCorasick,
  862    wordwise: bool,
  863    done: bool,
  864}
  865
  866impl std::fmt::Debug for SelectNextState {
  867    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  868        f.debug_struct(std::any::type_name::<Self>())
  869            .field("wordwise", &self.wordwise)
  870            .field("done", &self.done)
  871            .finish()
  872    }
  873}
  874
  875#[derive(Debug)]
  876struct AutocloseRegion {
  877    selection_id: usize,
  878    range: Range<Anchor>,
  879    pair: BracketPair,
  880}
  881
  882#[derive(Debug)]
  883struct SnippetState {
  884    ranges: Vec<Vec<Range<Anchor>>>,
  885    active_index: usize,
  886}
  887
  888#[doc(hidden)]
  889pub struct RenameState {
  890    pub range: Range<Anchor>,
  891    pub old_name: Arc<str>,
  892    pub editor: View<Editor>,
  893    block_id: CustomBlockId,
  894}
  895
  896struct InvalidationStack<T>(Vec<T>);
  897
  898struct RegisteredInlineCompletionProvider {
  899    provider: Arc<dyn InlineCompletionProviderHandle>,
  900    _subscription: Subscription,
  901}
  902
  903enum ContextMenu {
  904    Completions(CompletionsMenu),
  905    CodeActions(CodeActionsMenu),
  906}
  907
  908impl ContextMenu {
  909    fn select_first(
  910        &mut self,
  911        provider: Option<&dyn CompletionProvider>,
  912        cx: &mut ViewContext<Editor>,
  913    ) -> bool {
  914        if self.visible() {
  915            match self {
  916                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  917                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  918            }
  919            true
  920        } else {
  921            false
  922        }
  923    }
  924
  925    fn select_prev(
  926        &mut self,
  927        provider: Option<&dyn CompletionProvider>,
  928        cx: &mut ViewContext<Editor>,
  929    ) -> bool {
  930        if self.visible() {
  931            match self {
  932                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  933                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  934            }
  935            true
  936        } else {
  937            false
  938        }
  939    }
  940
  941    fn select_next(
  942        &mut self,
  943        provider: Option<&dyn CompletionProvider>,
  944        cx: &mut ViewContext<Editor>,
  945    ) -> bool {
  946        if self.visible() {
  947            match self {
  948                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  949                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  950            }
  951            true
  952        } else {
  953            false
  954        }
  955    }
  956
  957    fn select_last(
  958        &mut self,
  959        provider: Option<&dyn CompletionProvider>,
  960        cx: &mut ViewContext<Editor>,
  961    ) -> bool {
  962        if self.visible() {
  963            match self {
  964                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  965                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  966            }
  967            true
  968        } else {
  969            false
  970        }
  971    }
  972
  973    fn visible(&self) -> bool {
  974        match self {
  975            ContextMenu::Completions(menu) => menu.visible(),
  976            ContextMenu::CodeActions(menu) => menu.visible(),
  977        }
  978    }
  979
  980    fn render(
  981        &self,
  982        cursor_position: DisplayPoint,
  983        style: &EditorStyle,
  984        max_height: Pixels,
  985        workspace: Option<WeakView<Workspace>>,
  986        cx: &mut ViewContext<Editor>,
  987    ) -> (ContextMenuOrigin, AnyElement) {
  988        match self {
  989            ContextMenu::Completions(menu) => (
  990                ContextMenuOrigin::EditorPoint(cursor_position),
  991                menu.render(style, max_height, workspace, cx),
  992            ),
  993            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  994        }
  995    }
  996}
  997
  998enum ContextMenuOrigin {
  999    EditorPoint(DisplayPoint),
 1000    GutterIndicator(DisplayRow),
 1001}
 1002
 1003#[derive(Clone)]
 1004struct CompletionsMenu {
 1005    id: CompletionId,
 1006    sort_completions: bool,
 1007    initial_position: Anchor,
 1008    buffer: Model<Buffer>,
 1009    completions: Arc<RwLock<Box<[Completion]>>>,
 1010    match_candidates: Arc<[StringMatchCandidate]>,
 1011    matches: Arc<[StringMatch]>,
 1012    selected_item: usize,
 1013    scroll_handle: UniformListScrollHandle,
 1014    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
 1015}
 1016
 1017impl CompletionsMenu {
 1018    fn select_first(
 1019        &mut self,
 1020        provider: Option<&dyn CompletionProvider>,
 1021        cx: &mut ViewContext<Editor>,
 1022    ) {
 1023        self.selected_item = 0;
 1024        self.scroll_handle
 1025            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1026        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1027        cx.notify();
 1028    }
 1029
 1030    fn select_prev(
 1031        &mut self,
 1032        provider: Option<&dyn CompletionProvider>,
 1033        cx: &mut ViewContext<Editor>,
 1034    ) {
 1035        if self.selected_item > 0 {
 1036            self.selected_item -= 1;
 1037        } else {
 1038            self.selected_item = self.matches.len() - 1;
 1039        }
 1040        self.scroll_handle
 1041            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1042        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1043        cx.notify();
 1044    }
 1045
 1046    fn select_next(
 1047        &mut self,
 1048        provider: Option<&dyn CompletionProvider>,
 1049        cx: &mut ViewContext<Editor>,
 1050    ) {
 1051        if self.selected_item + 1 < self.matches.len() {
 1052            self.selected_item += 1;
 1053        } else {
 1054            self.selected_item = 0;
 1055        }
 1056        self.scroll_handle
 1057            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1058        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1059        cx.notify();
 1060    }
 1061
 1062    fn select_last(
 1063        &mut self,
 1064        provider: Option<&dyn CompletionProvider>,
 1065        cx: &mut ViewContext<Editor>,
 1066    ) {
 1067        self.selected_item = self.matches.len() - 1;
 1068        self.scroll_handle
 1069            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1070        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1071        cx.notify();
 1072    }
 1073
 1074    fn pre_resolve_completion_documentation(
 1075        buffer: Model<Buffer>,
 1076        completions: Arc<RwLock<Box<[Completion]>>>,
 1077        matches: Arc<[StringMatch]>,
 1078        editor: &Editor,
 1079        cx: &mut ViewContext<Editor>,
 1080    ) -> Task<()> {
 1081        let settings = EditorSettings::get_global(cx);
 1082        if !settings.show_completion_documentation {
 1083            return Task::ready(());
 1084        }
 1085
 1086        let Some(provider) = editor.completion_provider.as_ref() else {
 1087            return Task::ready(());
 1088        };
 1089
 1090        let resolve_task = provider.resolve_completions(
 1091            buffer,
 1092            matches.iter().map(|m| m.candidate_id).collect(),
 1093            completions.clone(),
 1094            cx,
 1095        );
 1096
 1097        cx.spawn(move |this, mut cx| async move {
 1098            if let Some(true) = resolve_task.await.log_err() {
 1099                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1100            }
 1101        })
 1102    }
 1103
 1104    fn attempt_resolve_selected_completion_documentation(
 1105        &mut self,
 1106        provider: Option<&dyn CompletionProvider>,
 1107        cx: &mut ViewContext<Editor>,
 1108    ) {
 1109        let settings = EditorSettings::get_global(cx);
 1110        if !settings.show_completion_documentation {
 1111            return;
 1112        }
 1113
 1114        let completion_index = self.matches[self.selected_item].candidate_id;
 1115        let Some(provider) = provider else {
 1116            return;
 1117        };
 1118
 1119        let resolve_task = provider.resolve_completions(
 1120            self.buffer.clone(),
 1121            vec![completion_index],
 1122            self.completions.clone(),
 1123            cx,
 1124        );
 1125
 1126        let delay_ms =
 1127            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1128        let delay = Duration::from_millis(delay_ms);
 1129
 1130        self.selected_completion_documentation_resolve_debounce
 1131            .lock()
 1132            .fire_new(delay, cx, |_, cx| {
 1133                cx.spawn(move |this, mut cx| async move {
 1134                    if let Some(true) = resolve_task.await.log_err() {
 1135                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1136                    }
 1137                })
 1138            });
 1139    }
 1140
 1141    fn visible(&self) -> bool {
 1142        !self.matches.is_empty()
 1143    }
 1144
 1145    fn render(
 1146        &self,
 1147        style: &EditorStyle,
 1148        max_height: Pixels,
 1149        workspace: Option<WeakView<Workspace>>,
 1150        cx: &mut ViewContext<Editor>,
 1151    ) -> AnyElement {
 1152        let settings = EditorSettings::get_global(cx);
 1153        let show_completion_documentation = settings.show_completion_documentation;
 1154
 1155        let widest_completion_ix = self
 1156            .matches
 1157            .iter()
 1158            .enumerate()
 1159            .max_by_key(|(_, mat)| {
 1160                let completions = self.completions.read();
 1161                let completion = &completions[mat.candidate_id];
 1162                let documentation = &completion.documentation;
 1163
 1164                let mut len = completion.label.text.chars().count();
 1165                if let Some(Documentation::SingleLine(text)) = documentation {
 1166                    if show_completion_documentation {
 1167                        len += text.chars().count();
 1168                    }
 1169                }
 1170
 1171                len
 1172            })
 1173            .map(|(ix, _)| ix);
 1174
 1175        let completions = self.completions.clone();
 1176        let matches = self.matches.clone();
 1177        let selected_item = self.selected_item;
 1178        let style = style.clone();
 1179
 1180        let multiline_docs = if show_completion_documentation {
 1181            let mat = &self.matches[selected_item];
 1182            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1183                Some(Documentation::MultiLinePlainText(text)) => {
 1184                    Some(div().child(SharedString::from(text.clone())))
 1185                }
 1186                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1187                    Some(div().child(render_parsed_markdown(
 1188                        "completions_markdown",
 1189                        parsed,
 1190                        &style,
 1191                        workspace,
 1192                        cx,
 1193                    )))
 1194                }
 1195                _ => None,
 1196            };
 1197            multiline_docs.map(|div| {
 1198                div.id("multiline_docs")
 1199                    .max_h(max_height)
 1200                    .flex_1()
 1201                    .px_1p5()
 1202                    .py_1()
 1203                    .min_w(px(260.))
 1204                    .max_w(px(640.))
 1205                    .w(px(500.))
 1206                    .overflow_y_scroll()
 1207                    .occlude()
 1208            })
 1209        } else {
 1210            None
 1211        };
 1212
 1213        let list = uniform_list(
 1214            cx.view().clone(),
 1215            "completions",
 1216            matches.len(),
 1217            move |_editor, range, cx| {
 1218                let start_ix = range.start;
 1219                let completions_guard = completions.read();
 1220
 1221                matches[range]
 1222                    .iter()
 1223                    .enumerate()
 1224                    .map(|(ix, mat)| {
 1225                        let item_ix = start_ix + ix;
 1226                        let candidate_id = mat.candidate_id;
 1227                        let completion = &completions_guard[candidate_id];
 1228
 1229                        let documentation = if show_completion_documentation {
 1230                            &completion.documentation
 1231                        } else {
 1232                            &None
 1233                        };
 1234
 1235                        let highlights = gpui::combine_highlights(
 1236                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1237                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1238                                |(range, mut highlight)| {
 1239                                    // Ignore font weight for syntax highlighting, as we'll use it
 1240                                    // for fuzzy matches.
 1241                                    highlight.font_weight = None;
 1242
 1243                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1244                                        highlight.strikethrough = Some(StrikethroughStyle {
 1245                                            thickness: 1.0.into(),
 1246                                            ..Default::default()
 1247                                        });
 1248                                        highlight.color = Some(cx.theme().colors().text_muted);
 1249                                    }
 1250
 1251                                    (range, highlight)
 1252                                },
 1253                            ),
 1254                        );
 1255                        let completion_label = StyledText::new(completion.label.text.clone())
 1256                            .with_highlights(&style.text, highlights);
 1257                        let documentation_label =
 1258                            if let Some(Documentation::SingleLine(text)) = documentation {
 1259                                if text.trim().is_empty() {
 1260                                    None
 1261                                } else {
 1262                                    Some(
 1263                                        Label::new(text.clone())
 1264                                            .ml_4()
 1265                                            .size(LabelSize::Small)
 1266                                            .color(Color::Muted),
 1267                                    )
 1268                                }
 1269                            } else {
 1270                                None
 1271                            };
 1272
 1273                        let color_swatch = completion
 1274                            .color()
 1275                            .map(|color| div().size_4().bg(color).rounded_sm());
 1276
 1277                        div().min_w(px(220.)).max_w(px(540.)).child(
 1278                            ListItem::new(mat.candidate_id)
 1279                                .inset(true)
 1280                                .selected(item_ix == selected_item)
 1281                                .on_click(cx.listener(move |editor, _event, cx| {
 1282                                    cx.stop_propagation();
 1283                                    if let Some(task) = editor.confirm_completion(
 1284                                        &ConfirmCompletion {
 1285                                            item_ix: Some(item_ix),
 1286                                        },
 1287                                        cx,
 1288                                    ) {
 1289                                        task.detach_and_log_err(cx)
 1290                                    }
 1291                                }))
 1292                                .start_slot::<Div>(color_swatch)
 1293                                .child(h_flex().overflow_hidden().child(completion_label))
 1294                                .end_slot::<Label>(documentation_label),
 1295                        )
 1296                    })
 1297                    .collect()
 1298            },
 1299        )
 1300        .occlude()
 1301        .max_h(max_height)
 1302        .track_scroll(self.scroll_handle.clone())
 1303        .with_width_from_item(widest_completion_ix)
 1304        .with_sizing_behavior(ListSizingBehavior::Infer);
 1305
 1306        Popover::new()
 1307            .child(list)
 1308            .when_some(multiline_docs, |popover, multiline_docs| {
 1309                popover.aside(multiline_docs)
 1310            })
 1311            .into_any_element()
 1312    }
 1313
 1314    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1315        let mut matches = if let Some(query) = query {
 1316            fuzzy::match_strings(
 1317                &self.match_candidates,
 1318                query,
 1319                query.chars().any(|c| c.is_uppercase()),
 1320                100,
 1321                &Default::default(),
 1322                executor,
 1323            )
 1324            .await
 1325        } else {
 1326            self.match_candidates
 1327                .iter()
 1328                .enumerate()
 1329                .map(|(candidate_id, candidate)| StringMatch {
 1330                    candidate_id,
 1331                    score: Default::default(),
 1332                    positions: Default::default(),
 1333                    string: candidate.string.clone(),
 1334                })
 1335                .collect()
 1336        };
 1337
 1338        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1339        if let Some(query) = query {
 1340            if let Some(query_start) = query.chars().next() {
 1341                matches.retain(|string_match| {
 1342                    split_words(&string_match.string).any(|word| {
 1343                        // Check that the first codepoint of the word as lowercase matches the first
 1344                        // codepoint of the query as lowercase
 1345                        word.chars()
 1346                            .flat_map(|codepoint| codepoint.to_lowercase())
 1347                            .zip(query_start.to_lowercase())
 1348                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1349                    })
 1350                });
 1351            }
 1352        }
 1353
 1354        let completions = self.completions.read();
 1355        if self.sort_completions {
 1356            matches.sort_unstable_by_key(|mat| {
 1357                // We do want to strike a balance here between what the language server tells us
 1358                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1359                // `Creat` and there is a local variable called `CreateComponent`).
 1360                // So what we do is: we bucket all matches into two buckets
 1361                // - Strong matches
 1362                // - Weak matches
 1363                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1364                // and the Weak matches are the rest.
 1365                //
 1366                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1367                // matches, we prefer language-server sort_text first.
 1368                //
 1369                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1370                // Rest of the matches(weak) can be sorted as language-server expects.
 1371
 1372                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1373                enum MatchScore<'a> {
 1374                    Strong {
 1375                        score: Reverse<OrderedFloat<f64>>,
 1376                        sort_text: Option<&'a str>,
 1377                        sort_key: (usize, &'a str),
 1378                    },
 1379                    Weak {
 1380                        sort_text: Option<&'a str>,
 1381                        score: Reverse<OrderedFloat<f64>>,
 1382                        sort_key: (usize, &'a str),
 1383                    },
 1384                }
 1385
 1386                let completion = &completions[mat.candidate_id];
 1387                let sort_key = completion.sort_key();
 1388                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1389                let score = Reverse(OrderedFloat(mat.score));
 1390
 1391                if mat.score >= 0.2 {
 1392                    MatchScore::Strong {
 1393                        score,
 1394                        sort_text,
 1395                        sort_key,
 1396                    }
 1397                } else {
 1398                    MatchScore::Weak {
 1399                        sort_text,
 1400                        score,
 1401                        sort_key,
 1402                    }
 1403                }
 1404            });
 1405        }
 1406
 1407        for mat in &mut matches {
 1408            let completion = &completions[mat.candidate_id];
 1409            mat.string.clone_from(&completion.label.text);
 1410            for position in &mut mat.positions {
 1411                *position += completion.label.filter_range.start;
 1412            }
 1413        }
 1414        drop(completions);
 1415
 1416        self.matches = matches.into();
 1417        self.selected_item = 0;
 1418    }
 1419}
 1420
 1421struct AvailableCodeAction {
 1422    excerpt_id: ExcerptId,
 1423    action: CodeAction,
 1424    provider: Arc<dyn CodeActionProvider>,
 1425}
 1426
 1427#[derive(Clone)]
 1428struct CodeActionContents {
 1429    tasks: Option<Arc<ResolvedTasks>>,
 1430    actions: Option<Arc<[AvailableCodeAction]>>,
 1431}
 1432
 1433impl CodeActionContents {
 1434    fn len(&self) -> usize {
 1435        match (&self.tasks, &self.actions) {
 1436            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1437            (Some(tasks), None) => tasks.templates.len(),
 1438            (None, Some(actions)) => actions.len(),
 1439            (None, None) => 0,
 1440        }
 1441    }
 1442
 1443    fn is_empty(&self) -> bool {
 1444        match (&self.tasks, &self.actions) {
 1445            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1446            (Some(tasks), None) => tasks.templates.is_empty(),
 1447            (None, Some(actions)) => actions.is_empty(),
 1448            (None, None) => true,
 1449        }
 1450    }
 1451
 1452    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1453        self.tasks
 1454            .iter()
 1455            .flat_map(|tasks| {
 1456                tasks
 1457                    .templates
 1458                    .iter()
 1459                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1460            })
 1461            .chain(self.actions.iter().flat_map(|actions| {
 1462                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1463                    excerpt_id: available.excerpt_id,
 1464                    action: available.action.clone(),
 1465                    provider: available.provider.clone(),
 1466                })
 1467            }))
 1468    }
 1469    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1470        match (&self.tasks, &self.actions) {
 1471            (Some(tasks), Some(actions)) => {
 1472                if index < tasks.templates.len() {
 1473                    tasks
 1474                        .templates
 1475                        .get(index)
 1476                        .cloned()
 1477                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1478                } else {
 1479                    actions.get(index - tasks.templates.len()).map(|available| {
 1480                        CodeActionsItem::CodeAction {
 1481                            excerpt_id: available.excerpt_id,
 1482                            action: available.action.clone(),
 1483                            provider: available.provider.clone(),
 1484                        }
 1485                    })
 1486                }
 1487            }
 1488            (Some(tasks), None) => tasks
 1489                .templates
 1490                .get(index)
 1491                .cloned()
 1492                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1493            (None, Some(actions)) => {
 1494                actions
 1495                    .get(index)
 1496                    .map(|available| CodeActionsItem::CodeAction {
 1497                        excerpt_id: available.excerpt_id,
 1498                        action: available.action.clone(),
 1499                        provider: available.provider.clone(),
 1500                    })
 1501            }
 1502            (None, None) => None,
 1503        }
 1504    }
 1505}
 1506
 1507#[allow(clippy::large_enum_variant)]
 1508#[derive(Clone)]
 1509enum CodeActionsItem {
 1510    Task(TaskSourceKind, ResolvedTask),
 1511    CodeAction {
 1512        excerpt_id: ExcerptId,
 1513        action: CodeAction,
 1514        provider: Arc<dyn CodeActionProvider>,
 1515    },
 1516}
 1517
 1518impl CodeActionsItem {
 1519    fn as_task(&self) -> Option<&ResolvedTask> {
 1520        let Self::Task(_, task) = self else {
 1521            return None;
 1522        };
 1523        Some(task)
 1524    }
 1525    fn as_code_action(&self) -> Option<&CodeAction> {
 1526        let Self::CodeAction { action, .. } = self else {
 1527            return None;
 1528        };
 1529        Some(action)
 1530    }
 1531    fn label(&self) -> String {
 1532        match self {
 1533            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1534            Self::Task(_, task) => task.resolved_label.clone(),
 1535        }
 1536    }
 1537}
 1538
 1539struct CodeActionsMenu {
 1540    actions: CodeActionContents,
 1541    buffer: Model<Buffer>,
 1542    selected_item: usize,
 1543    scroll_handle: UniformListScrollHandle,
 1544    deployed_from_indicator: Option<DisplayRow>,
 1545}
 1546
 1547impl CodeActionsMenu {
 1548    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1549        self.selected_item = 0;
 1550        self.scroll_handle
 1551            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1552        cx.notify()
 1553    }
 1554
 1555    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1556        if self.selected_item > 0 {
 1557            self.selected_item -= 1;
 1558        } else {
 1559            self.selected_item = self.actions.len() - 1;
 1560        }
 1561        self.scroll_handle
 1562            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1563        cx.notify();
 1564    }
 1565
 1566    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1567        if self.selected_item + 1 < self.actions.len() {
 1568            self.selected_item += 1;
 1569        } else {
 1570            self.selected_item = 0;
 1571        }
 1572        self.scroll_handle
 1573            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1574        cx.notify();
 1575    }
 1576
 1577    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1578        self.selected_item = self.actions.len() - 1;
 1579        self.scroll_handle
 1580            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1581        cx.notify()
 1582    }
 1583
 1584    fn visible(&self) -> bool {
 1585        !self.actions.is_empty()
 1586    }
 1587
 1588    fn render(
 1589        &self,
 1590        cursor_position: DisplayPoint,
 1591        _style: &EditorStyle,
 1592        max_height: Pixels,
 1593        cx: &mut ViewContext<Editor>,
 1594    ) -> (ContextMenuOrigin, AnyElement) {
 1595        let actions = self.actions.clone();
 1596        let selected_item = self.selected_item;
 1597        let element = uniform_list(
 1598            cx.view().clone(),
 1599            "code_actions_menu",
 1600            self.actions.len(),
 1601            move |_this, range, cx| {
 1602                actions
 1603                    .iter()
 1604                    .skip(range.start)
 1605                    .take(range.end - range.start)
 1606                    .enumerate()
 1607                    .map(|(ix, action)| {
 1608                        let item_ix = range.start + ix;
 1609                        let selected = selected_item == item_ix;
 1610                        let colors = cx.theme().colors();
 1611                        div()
 1612                            .px_1()
 1613                            .rounded_md()
 1614                            .text_color(colors.text)
 1615                            .when(selected, |style| {
 1616                                style
 1617                                    .bg(colors.element_active)
 1618                                    .text_color(colors.text_accent)
 1619                            })
 1620                            .hover(|style| {
 1621                                style
 1622                                    .bg(colors.element_hover)
 1623                                    .text_color(colors.text_accent)
 1624                            })
 1625                            .whitespace_nowrap()
 1626                            .when_some(action.as_code_action(), |this, action| {
 1627                                this.on_mouse_down(
 1628                                    MouseButton::Left,
 1629                                    cx.listener(move |editor, _, cx| {
 1630                                        cx.stop_propagation();
 1631                                        if let Some(task) = editor.confirm_code_action(
 1632                                            &ConfirmCodeAction {
 1633                                                item_ix: Some(item_ix),
 1634                                            },
 1635                                            cx,
 1636                                        ) {
 1637                                            task.detach_and_log_err(cx)
 1638                                        }
 1639                                    }),
 1640                                )
 1641                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1642                                .child(SharedString::from(action.lsp_action.title.clone()))
 1643                            })
 1644                            .when_some(action.as_task(), |this, task| {
 1645                                this.on_mouse_down(
 1646                                    MouseButton::Left,
 1647                                    cx.listener(move |editor, _, cx| {
 1648                                        cx.stop_propagation();
 1649                                        if let Some(task) = editor.confirm_code_action(
 1650                                            &ConfirmCodeAction {
 1651                                                item_ix: Some(item_ix),
 1652                                            },
 1653                                            cx,
 1654                                        ) {
 1655                                            task.detach_and_log_err(cx)
 1656                                        }
 1657                                    }),
 1658                                )
 1659                                .child(SharedString::from(task.resolved_label.clone()))
 1660                            })
 1661                    })
 1662                    .collect()
 1663            },
 1664        )
 1665        .elevation_1(cx)
 1666        .p_1()
 1667        .max_h(max_height)
 1668        .occlude()
 1669        .track_scroll(self.scroll_handle.clone())
 1670        .with_width_from_item(
 1671            self.actions
 1672                .iter()
 1673                .enumerate()
 1674                .max_by_key(|(_, action)| match action {
 1675                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1676                    CodeActionsItem::CodeAction { action, .. } => {
 1677                        action.lsp_action.title.chars().count()
 1678                    }
 1679                })
 1680                .map(|(ix, _)| ix),
 1681        )
 1682        .with_sizing_behavior(ListSizingBehavior::Infer)
 1683        .into_any_element();
 1684
 1685        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1686            ContextMenuOrigin::GutterIndicator(row)
 1687        } else {
 1688            ContextMenuOrigin::EditorPoint(cursor_position)
 1689        };
 1690
 1691        (cursor_position, element)
 1692    }
 1693}
 1694
 1695#[derive(Debug)]
 1696struct ActiveDiagnosticGroup {
 1697    primary_range: Range<Anchor>,
 1698    primary_message: String,
 1699    group_id: usize,
 1700    blocks: HashMap<CustomBlockId, Diagnostic>,
 1701    is_valid: bool,
 1702}
 1703
 1704#[derive(Serialize, Deserialize, Clone, Debug)]
 1705pub struct ClipboardSelection {
 1706    pub len: usize,
 1707    pub is_entire_line: bool,
 1708    pub first_line_indent: u32,
 1709}
 1710
 1711#[derive(Debug)]
 1712pub(crate) struct NavigationData {
 1713    cursor_anchor: Anchor,
 1714    cursor_position: Point,
 1715    scroll_anchor: ScrollAnchor,
 1716    scroll_top_row: u32,
 1717}
 1718
 1719#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1720pub enum GotoDefinitionKind {
 1721    Symbol,
 1722    Declaration,
 1723    Type,
 1724    Implementation,
 1725}
 1726
 1727#[derive(Debug, Clone)]
 1728enum InlayHintRefreshReason {
 1729    Toggle(bool),
 1730    SettingsChange(InlayHintSettings),
 1731    NewLinesShown,
 1732    BufferEdited(HashSet<Arc<Language>>),
 1733    RefreshRequested,
 1734    ExcerptsRemoved(Vec<ExcerptId>),
 1735}
 1736
 1737impl InlayHintRefreshReason {
 1738    fn description(&self) -> &'static str {
 1739        match self {
 1740            Self::Toggle(_) => "toggle",
 1741            Self::SettingsChange(_) => "settings change",
 1742            Self::NewLinesShown => "new lines shown",
 1743            Self::BufferEdited(_) => "buffer edited",
 1744            Self::RefreshRequested => "refresh requested",
 1745            Self::ExcerptsRemoved(_) => "excerpts removed",
 1746        }
 1747    }
 1748}
 1749
 1750pub(crate) struct FocusedBlock {
 1751    id: BlockId,
 1752    focus_handle: WeakFocusHandle,
 1753}
 1754
 1755#[derive(Clone)]
 1756struct JumpData {
 1757    excerpt_id: ExcerptId,
 1758    position: Point,
 1759    anchor: text::Anchor,
 1760    path: Option<project::ProjectPath>,
 1761    line_offset_from_top: u32,
 1762}
 1763
 1764impl Editor {
 1765    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1766        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1767        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1768        Self::new(
 1769            EditorMode::SingleLine { auto_width: false },
 1770            buffer,
 1771            None,
 1772            false,
 1773            cx,
 1774        )
 1775    }
 1776
 1777    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1778        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1779        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1780        Self::new(EditorMode::Full, buffer, None, false, cx)
 1781    }
 1782
 1783    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1784        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1785        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1786        Self::new(
 1787            EditorMode::SingleLine { auto_width: true },
 1788            buffer,
 1789            None,
 1790            false,
 1791            cx,
 1792        )
 1793    }
 1794
 1795    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1796        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1797        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1798        Self::new(
 1799            EditorMode::AutoHeight { max_lines },
 1800            buffer,
 1801            None,
 1802            false,
 1803            cx,
 1804        )
 1805    }
 1806
 1807    pub fn for_buffer(
 1808        buffer: Model<Buffer>,
 1809        project: Option<Model<Project>>,
 1810        cx: &mut ViewContext<Self>,
 1811    ) -> Self {
 1812        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1813        Self::new(EditorMode::Full, buffer, project, false, cx)
 1814    }
 1815
 1816    pub fn for_multibuffer(
 1817        buffer: Model<MultiBuffer>,
 1818        project: Option<Model<Project>>,
 1819        show_excerpt_controls: bool,
 1820        cx: &mut ViewContext<Self>,
 1821    ) -> Self {
 1822        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1823    }
 1824
 1825    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1826        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1827        let mut clone = Self::new(
 1828            self.mode,
 1829            self.buffer.clone(),
 1830            self.project.clone(),
 1831            show_excerpt_controls,
 1832            cx,
 1833        );
 1834        self.display_map.update(cx, |display_map, cx| {
 1835            let snapshot = display_map.snapshot(cx);
 1836            clone.display_map.update(cx, |display_map, cx| {
 1837                display_map.set_state(&snapshot, cx);
 1838            });
 1839        });
 1840        clone.selections.clone_state(&self.selections);
 1841        clone.scroll_manager.clone_state(&self.scroll_manager);
 1842        clone.searchable = self.searchable;
 1843        clone
 1844    }
 1845
 1846    pub fn new(
 1847        mode: EditorMode,
 1848        buffer: Model<MultiBuffer>,
 1849        project: Option<Model<Project>>,
 1850        show_excerpt_controls: bool,
 1851        cx: &mut ViewContext<Self>,
 1852    ) -> Self {
 1853        let style = cx.text_style();
 1854        let font_size = style.font_size.to_pixels(cx.rem_size());
 1855        let editor = cx.view().downgrade();
 1856        let fold_placeholder = FoldPlaceholder {
 1857            constrain_width: true,
 1858            render: Arc::new(move |fold_id, fold_range, cx| {
 1859                let editor = editor.clone();
 1860                div()
 1861                    .id(fold_id)
 1862                    .bg(cx.theme().colors().ghost_element_background)
 1863                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1864                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1865                    .rounded_sm()
 1866                    .size_full()
 1867                    .cursor_pointer()
 1868                    .child("")
 1869                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1870                    .on_click(move |_, cx| {
 1871                        editor
 1872                            .update(cx, |editor, cx| {
 1873                                editor.unfold_ranges(
 1874                                    &[fold_range.start..fold_range.end],
 1875                                    true,
 1876                                    false,
 1877                                    cx,
 1878                                );
 1879                                cx.stop_propagation();
 1880                            })
 1881                            .ok();
 1882                    })
 1883                    .into_any()
 1884            }),
 1885            merge_adjacent: true,
 1886            ..Default::default()
 1887        };
 1888        let display_map = cx.new_model(|cx| {
 1889            DisplayMap::new(
 1890                buffer.clone(),
 1891                style.font(),
 1892                font_size,
 1893                None,
 1894                show_excerpt_controls,
 1895                FILE_HEADER_HEIGHT,
 1896                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1897                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1898                fold_placeholder,
 1899                cx,
 1900            )
 1901        });
 1902
 1903        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1904
 1905        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1906
 1907        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1908            .then(|| language_settings::SoftWrap::None);
 1909
 1910        let mut project_subscriptions = Vec::new();
 1911        if mode == EditorMode::Full {
 1912            if let Some(project) = project.as_ref() {
 1913                if buffer.read(cx).is_singleton() {
 1914                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1915                        cx.emit(EditorEvent::TitleChanged);
 1916                    }));
 1917                }
 1918                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1919                    if let project::Event::RefreshInlayHints = event {
 1920                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1921                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1922                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1923                            let focus_handle = editor.focus_handle(cx);
 1924                            if focus_handle.is_focused(cx) {
 1925                                let snapshot = buffer.read(cx).snapshot();
 1926                                for (range, snippet) in snippet_edits {
 1927                                    let editor_range =
 1928                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1929                                    editor
 1930                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1931                                        .ok();
 1932                                }
 1933                            }
 1934                        }
 1935                    }
 1936                }));
 1937                if let Some(task_inventory) = project
 1938                    .read(cx)
 1939                    .task_store()
 1940                    .read(cx)
 1941                    .task_inventory()
 1942                    .cloned()
 1943                {
 1944                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1945                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1946                    }));
 1947                }
 1948            }
 1949        }
 1950
 1951        let inlay_hint_settings = inlay_hint_settings(
 1952            selections.newest_anchor().head(),
 1953            &buffer.read(cx).snapshot(cx),
 1954            cx,
 1955        );
 1956        let focus_handle = cx.focus_handle();
 1957        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1958        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1959            .detach();
 1960        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1961            .detach();
 1962        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1963
 1964        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1965            Some(false)
 1966        } else {
 1967            None
 1968        };
 1969
 1970        let mut code_action_providers = Vec::new();
 1971        if let Some(project) = project.clone() {
 1972            code_action_providers.push(Arc::new(project) as Arc<_>);
 1973        }
 1974
 1975        let mut this = Self {
 1976            focus_handle,
 1977            show_cursor_when_unfocused: false,
 1978            last_focused_descendant: None,
 1979            buffer: buffer.clone(),
 1980            display_map: display_map.clone(),
 1981            selections,
 1982            scroll_manager: ScrollManager::new(cx),
 1983            columnar_selection_tail: None,
 1984            add_selections_state: None,
 1985            select_next_state: None,
 1986            select_prev_state: None,
 1987            selection_history: Default::default(),
 1988            autoclose_regions: Default::default(),
 1989            snippet_stack: Default::default(),
 1990            select_larger_syntax_node_stack: Vec::new(),
 1991            ime_transaction: Default::default(),
 1992            active_diagnostics: None,
 1993            soft_wrap_mode_override,
 1994            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1995            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1996            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1997            project,
 1998            blink_manager: blink_manager.clone(),
 1999            show_local_selections: true,
 2000            mode,
 2001            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2002            show_gutter: mode == EditorMode::Full,
 2003            show_line_numbers: None,
 2004            use_relative_line_numbers: None,
 2005            show_git_diff_gutter: None,
 2006            show_code_actions: None,
 2007            show_runnables: None,
 2008            show_wrap_guides: None,
 2009            show_indent_guides,
 2010            placeholder_text: None,
 2011            highlight_order: 0,
 2012            highlighted_rows: HashMap::default(),
 2013            background_highlights: Default::default(),
 2014            gutter_highlights: TreeMap::default(),
 2015            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2016            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2017            nav_history: None,
 2018            context_menu: RwLock::new(None),
 2019            mouse_context_menu: None,
 2020            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2021            completion_tasks: Default::default(),
 2022            signature_help_state: SignatureHelpState::default(),
 2023            auto_signature_help: None,
 2024            find_all_references_task_sources: Vec::new(),
 2025            next_completion_id: 0,
 2026            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2027            next_inlay_id: 0,
 2028            code_action_providers,
 2029            available_code_actions: Default::default(),
 2030            code_actions_task: Default::default(),
 2031            document_highlights_task: Default::default(),
 2032            linked_editing_range_task: Default::default(),
 2033            pending_rename: Default::default(),
 2034            searchable: true,
 2035            cursor_shape: EditorSettings::get_global(cx)
 2036                .cursor_shape
 2037                .unwrap_or_default(),
 2038            current_line_highlight: None,
 2039            autoindent_mode: Some(AutoindentMode::EachLine),
 2040            collapse_matches: false,
 2041            workspace: None,
 2042            input_enabled: true,
 2043            use_modal_editing: mode == EditorMode::Full,
 2044            read_only: false,
 2045            use_autoclose: true,
 2046            use_auto_surround: true,
 2047            auto_replace_emoji_shortcode: false,
 2048            leader_peer_id: None,
 2049            remote_id: None,
 2050            hover_state: Default::default(),
 2051            hovered_link_state: Default::default(),
 2052            inline_completion_provider: None,
 2053            active_inline_completion: None,
 2054            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2055            expanded_hunks: ExpandedHunks::default(),
 2056            gutter_hovered: false,
 2057            pixel_position_of_newest_cursor: None,
 2058            last_bounds: None,
 2059            expect_bounds_change: None,
 2060            gutter_dimensions: GutterDimensions::default(),
 2061            style: None,
 2062            show_cursor_names: false,
 2063            hovered_cursors: Default::default(),
 2064            next_editor_action_id: EditorActionId::default(),
 2065            editor_actions: Rc::default(),
 2066            show_inline_completions_override: None,
 2067            enable_inline_completions: true,
 2068            custom_context_menu: None,
 2069            show_git_blame_gutter: false,
 2070            show_git_blame_inline: false,
 2071            show_selection_menu: None,
 2072            show_git_blame_inline_delay_task: None,
 2073            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2074            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2075                .session
 2076                .restore_unsaved_buffers,
 2077            blame: None,
 2078            blame_subscription: None,
 2079            tasks: Default::default(),
 2080            _subscriptions: vec![
 2081                cx.observe(&buffer, Self::on_buffer_changed),
 2082                cx.subscribe(&buffer, Self::on_buffer_event),
 2083                cx.observe(&display_map, Self::on_display_map_changed),
 2084                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2085                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2086                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2087                cx.observe_window_activation(|editor, cx| {
 2088                    let active = cx.is_window_active();
 2089                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2090                        if active {
 2091                            blink_manager.enable(cx);
 2092                        } else {
 2093                            blink_manager.disable(cx);
 2094                        }
 2095                    });
 2096                }),
 2097            ],
 2098            tasks_update_task: None,
 2099            linked_edit_ranges: Default::default(),
 2100            previous_search_ranges: None,
 2101            breadcrumb_header: None,
 2102            focused_block: None,
 2103            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2104            addons: HashMap::default(),
 2105            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2106            text_style_refinement: None,
 2107        };
 2108        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2109        this._subscriptions.extend(project_subscriptions);
 2110
 2111        this.end_selection(cx);
 2112        this.scroll_manager.show_scrollbar(cx);
 2113
 2114        if mode == EditorMode::Full {
 2115            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2116            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2117
 2118            if this.git_blame_inline_enabled {
 2119                this.git_blame_inline_enabled = true;
 2120                this.start_git_blame_inline(false, cx);
 2121            }
 2122        }
 2123
 2124        this.report_editor_event("open", None, cx);
 2125        this
 2126    }
 2127
 2128    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2129        self.mouse_context_menu
 2130            .as_ref()
 2131            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2132    }
 2133
 2134    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2135        let mut key_context = KeyContext::new_with_defaults();
 2136        key_context.add("Editor");
 2137        let mode = match self.mode {
 2138            EditorMode::SingleLine { .. } => "single_line",
 2139            EditorMode::AutoHeight { .. } => "auto_height",
 2140            EditorMode::Full => "full",
 2141        };
 2142
 2143        if EditorSettings::jupyter_enabled(cx) {
 2144            key_context.add("jupyter");
 2145        }
 2146
 2147        key_context.set("mode", mode);
 2148        if self.pending_rename.is_some() {
 2149            key_context.add("renaming");
 2150        }
 2151        if self.context_menu_visible() {
 2152            match self.context_menu.read().as_ref() {
 2153                Some(ContextMenu::Completions(_)) => {
 2154                    key_context.add("menu");
 2155                    key_context.add("showing_completions")
 2156                }
 2157                Some(ContextMenu::CodeActions(_)) => {
 2158                    key_context.add("menu");
 2159                    key_context.add("showing_code_actions")
 2160                }
 2161                None => {}
 2162            }
 2163        }
 2164
 2165        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2166        if !self.focus_handle(cx).contains_focused(cx)
 2167            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2168        {
 2169            for addon in self.addons.values() {
 2170                addon.extend_key_context(&mut key_context, cx)
 2171            }
 2172        }
 2173
 2174        if let Some(extension) = self
 2175            .buffer
 2176            .read(cx)
 2177            .as_singleton()
 2178            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2179        {
 2180            key_context.set("extension", extension.to_string());
 2181        }
 2182
 2183        if self.has_active_inline_completion(cx) {
 2184            key_context.add("copilot_suggestion");
 2185            key_context.add("inline_completion");
 2186        }
 2187
 2188        key_context
 2189    }
 2190
 2191    pub fn new_file(
 2192        workspace: &mut Workspace,
 2193        _: &workspace::NewFile,
 2194        cx: &mut ViewContext<Workspace>,
 2195    ) {
 2196        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2197            "Failed to create buffer",
 2198            cx,
 2199            |e, _| match e.error_code() {
 2200                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2201                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2202                e.error_tag("required").unwrap_or("the latest version")
 2203            )),
 2204                _ => None,
 2205            },
 2206        );
 2207    }
 2208
 2209    pub fn new_in_workspace(
 2210        workspace: &mut Workspace,
 2211        cx: &mut ViewContext<Workspace>,
 2212    ) -> Task<Result<View<Editor>>> {
 2213        let project = workspace.project().clone();
 2214        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2215
 2216        cx.spawn(|workspace, mut cx| async move {
 2217            let buffer = create.await?;
 2218            workspace.update(&mut cx, |workspace, cx| {
 2219                let editor =
 2220                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2221                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2222                editor
 2223            })
 2224        })
 2225    }
 2226
 2227    fn new_file_vertical(
 2228        workspace: &mut Workspace,
 2229        _: &workspace::NewFileSplitVertical,
 2230        cx: &mut ViewContext<Workspace>,
 2231    ) {
 2232        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2233    }
 2234
 2235    fn new_file_horizontal(
 2236        workspace: &mut Workspace,
 2237        _: &workspace::NewFileSplitHorizontal,
 2238        cx: &mut ViewContext<Workspace>,
 2239    ) {
 2240        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2241    }
 2242
 2243    fn new_file_in_direction(
 2244        workspace: &mut Workspace,
 2245        direction: SplitDirection,
 2246        cx: &mut ViewContext<Workspace>,
 2247    ) {
 2248        let project = workspace.project().clone();
 2249        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2250
 2251        cx.spawn(|workspace, mut cx| async move {
 2252            let buffer = create.await?;
 2253            workspace.update(&mut cx, move |workspace, cx| {
 2254                workspace.split_item(
 2255                    direction,
 2256                    Box::new(
 2257                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2258                    ),
 2259                    cx,
 2260                )
 2261            })?;
 2262            anyhow::Ok(())
 2263        })
 2264        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2265            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2266                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2267                e.error_tag("required").unwrap_or("the latest version")
 2268            )),
 2269            _ => None,
 2270        });
 2271    }
 2272
 2273    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2274        self.leader_peer_id
 2275    }
 2276
 2277    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2278        &self.buffer
 2279    }
 2280
 2281    pub fn workspace(&self) -> Option<View<Workspace>> {
 2282        self.workspace.as_ref()?.0.upgrade()
 2283    }
 2284
 2285    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2286        self.buffer().read(cx).title(cx)
 2287    }
 2288
 2289    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2290        let git_blame_gutter_max_author_length = self
 2291            .render_git_blame_gutter(cx)
 2292            .then(|| {
 2293                if let Some(blame) = self.blame.as_ref() {
 2294                    let max_author_length =
 2295                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2296                    Some(max_author_length)
 2297                } else {
 2298                    None
 2299                }
 2300            })
 2301            .flatten();
 2302
 2303        EditorSnapshot {
 2304            mode: self.mode,
 2305            show_gutter: self.show_gutter,
 2306            show_line_numbers: self.show_line_numbers,
 2307            show_git_diff_gutter: self.show_git_diff_gutter,
 2308            show_code_actions: self.show_code_actions,
 2309            show_runnables: self.show_runnables,
 2310            git_blame_gutter_max_author_length,
 2311            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2312            scroll_anchor: self.scroll_manager.anchor(),
 2313            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2314            placeholder_text: self.placeholder_text.clone(),
 2315            is_focused: self.focus_handle.is_focused(cx),
 2316            current_line_highlight: self
 2317                .current_line_highlight
 2318                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2319            gutter_hovered: self.gutter_hovered,
 2320        }
 2321    }
 2322
 2323    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2324        self.buffer.read(cx).language_at(point, cx)
 2325    }
 2326
 2327    pub fn file_at<T: ToOffset>(
 2328        &self,
 2329        point: T,
 2330        cx: &AppContext,
 2331    ) -> Option<Arc<dyn language::File>> {
 2332        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2333    }
 2334
 2335    pub fn active_excerpt(
 2336        &self,
 2337        cx: &AppContext,
 2338    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2339        self.buffer
 2340            .read(cx)
 2341            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2342    }
 2343
 2344    pub fn mode(&self) -> EditorMode {
 2345        self.mode
 2346    }
 2347
 2348    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2349        self.collaboration_hub.as_deref()
 2350    }
 2351
 2352    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2353        self.collaboration_hub = Some(hub);
 2354    }
 2355
 2356    pub fn set_custom_context_menu(
 2357        &mut self,
 2358        f: impl 'static
 2359            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2360    ) {
 2361        self.custom_context_menu = Some(Box::new(f))
 2362    }
 2363
 2364    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2365        self.completion_provider = provider;
 2366    }
 2367
 2368    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2369        self.semantics_provider.clone()
 2370    }
 2371
 2372    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2373        self.semantics_provider = provider;
 2374    }
 2375
 2376    pub fn set_inline_completion_provider<T>(
 2377        &mut self,
 2378        provider: Option<Model<T>>,
 2379        cx: &mut ViewContext<Self>,
 2380    ) where
 2381        T: InlineCompletionProvider,
 2382    {
 2383        self.inline_completion_provider =
 2384            provider.map(|provider| RegisteredInlineCompletionProvider {
 2385                _subscription: cx.observe(&provider, |this, _, cx| {
 2386                    if this.focus_handle.is_focused(cx) {
 2387                        this.update_visible_inline_completion(cx);
 2388                    }
 2389                }),
 2390                provider: Arc::new(provider),
 2391            });
 2392        self.refresh_inline_completion(false, false, cx);
 2393    }
 2394
 2395    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2396        self.placeholder_text.as_deref()
 2397    }
 2398
 2399    pub fn set_placeholder_text(
 2400        &mut self,
 2401        placeholder_text: impl Into<Arc<str>>,
 2402        cx: &mut ViewContext<Self>,
 2403    ) {
 2404        let placeholder_text = Some(placeholder_text.into());
 2405        if self.placeholder_text != placeholder_text {
 2406            self.placeholder_text = placeholder_text;
 2407            cx.notify();
 2408        }
 2409    }
 2410
 2411    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2412        self.cursor_shape = cursor_shape;
 2413
 2414        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2415        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2416
 2417        cx.notify();
 2418    }
 2419
 2420    pub fn set_current_line_highlight(
 2421        &mut self,
 2422        current_line_highlight: Option<CurrentLineHighlight>,
 2423    ) {
 2424        self.current_line_highlight = current_line_highlight;
 2425    }
 2426
 2427    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2428        self.collapse_matches = collapse_matches;
 2429    }
 2430
 2431    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2432        if self.collapse_matches {
 2433            return range.start..range.start;
 2434        }
 2435        range.clone()
 2436    }
 2437
 2438    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2439        if self.display_map.read(cx).clip_at_line_ends != clip {
 2440            self.display_map
 2441                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2442        }
 2443    }
 2444
 2445    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2446        self.input_enabled = input_enabled;
 2447    }
 2448
 2449    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2450        self.enable_inline_completions = enabled;
 2451    }
 2452
 2453    pub fn set_autoindent(&mut self, autoindent: bool) {
 2454        if autoindent {
 2455            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2456        } else {
 2457            self.autoindent_mode = None;
 2458        }
 2459    }
 2460
 2461    pub fn read_only(&self, cx: &AppContext) -> bool {
 2462        self.read_only || self.buffer.read(cx).read_only()
 2463    }
 2464
 2465    pub fn set_read_only(&mut self, read_only: bool) {
 2466        self.read_only = read_only;
 2467    }
 2468
 2469    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2470        self.use_autoclose = autoclose;
 2471    }
 2472
 2473    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2474        self.use_auto_surround = auto_surround;
 2475    }
 2476
 2477    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2478        self.auto_replace_emoji_shortcode = auto_replace;
 2479    }
 2480
 2481    pub fn toggle_inline_completions(
 2482        &mut self,
 2483        _: &ToggleInlineCompletions,
 2484        cx: &mut ViewContext<Self>,
 2485    ) {
 2486        if self.show_inline_completions_override.is_some() {
 2487            self.set_show_inline_completions(None, cx);
 2488        } else {
 2489            let cursor = self.selections.newest_anchor().head();
 2490            if let Some((buffer, cursor_buffer_position)) =
 2491                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2492            {
 2493                let show_inline_completions =
 2494                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2495                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2496            }
 2497        }
 2498    }
 2499
 2500    pub fn set_show_inline_completions(
 2501        &mut self,
 2502        show_inline_completions: Option<bool>,
 2503        cx: &mut ViewContext<Self>,
 2504    ) {
 2505        self.show_inline_completions_override = show_inline_completions;
 2506        self.refresh_inline_completion(false, true, cx);
 2507    }
 2508
 2509    fn should_show_inline_completions(
 2510        &self,
 2511        buffer: &Model<Buffer>,
 2512        buffer_position: language::Anchor,
 2513        cx: &AppContext,
 2514    ) -> bool {
 2515        if !self.snippet_stack.is_empty() {
 2516            return false;
 2517        }
 2518
 2519        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2520            return false;
 2521        }
 2522
 2523        if let Some(provider) = self.inline_completion_provider() {
 2524            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2525                show_inline_completions
 2526            } else {
 2527                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2528            }
 2529        } else {
 2530            false
 2531        }
 2532    }
 2533
 2534    fn inline_completions_disabled_in_scope(
 2535        &self,
 2536        buffer: &Model<Buffer>,
 2537        buffer_position: language::Anchor,
 2538        cx: &AppContext,
 2539    ) -> bool {
 2540        let snapshot = buffer.read(cx).snapshot();
 2541        let settings = snapshot.settings_at(buffer_position, cx);
 2542
 2543        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2544            return false;
 2545        };
 2546
 2547        scope.override_name().map_or(false, |scope_name| {
 2548            settings
 2549                .inline_completions_disabled_in
 2550                .iter()
 2551                .any(|s| s == scope_name)
 2552        })
 2553    }
 2554
 2555    pub fn set_use_modal_editing(&mut self, to: bool) {
 2556        self.use_modal_editing = to;
 2557    }
 2558
 2559    pub fn use_modal_editing(&self) -> bool {
 2560        self.use_modal_editing
 2561    }
 2562
 2563    fn selections_did_change(
 2564        &mut self,
 2565        local: bool,
 2566        old_cursor_position: &Anchor,
 2567        show_completions: bool,
 2568        cx: &mut ViewContext<Self>,
 2569    ) {
 2570        cx.invalidate_character_coordinates();
 2571
 2572        // Copy selections to primary selection buffer
 2573        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2574        if local {
 2575            let selections = self.selections.all::<usize>(cx);
 2576            let buffer_handle = self.buffer.read(cx).read(cx);
 2577
 2578            let mut text = String::new();
 2579            for (index, selection) in selections.iter().enumerate() {
 2580                let text_for_selection = buffer_handle
 2581                    .text_for_range(selection.start..selection.end)
 2582                    .collect::<String>();
 2583
 2584                text.push_str(&text_for_selection);
 2585                if index != selections.len() - 1 {
 2586                    text.push('\n');
 2587                }
 2588            }
 2589
 2590            if !text.is_empty() {
 2591                cx.write_to_primary(ClipboardItem::new_string(text));
 2592            }
 2593        }
 2594
 2595        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2596            self.buffer.update(cx, |buffer, cx| {
 2597                buffer.set_active_selections(
 2598                    &self.selections.disjoint_anchors(),
 2599                    self.selections.line_mode,
 2600                    self.cursor_shape,
 2601                    cx,
 2602                )
 2603            });
 2604        }
 2605        let display_map = self
 2606            .display_map
 2607            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2608        let buffer = &display_map.buffer_snapshot;
 2609        self.add_selections_state = None;
 2610        self.select_next_state = None;
 2611        self.select_prev_state = None;
 2612        self.select_larger_syntax_node_stack.clear();
 2613        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2614        self.snippet_stack
 2615            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2616        self.take_rename(false, cx);
 2617
 2618        let new_cursor_position = self.selections.newest_anchor().head();
 2619
 2620        self.push_to_nav_history(
 2621            *old_cursor_position,
 2622            Some(new_cursor_position.to_point(buffer)),
 2623            cx,
 2624        );
 2625
 2626        if local {
 2627            let new_cursor_position = self.selections.newest_anchor().head();
 2628            let mut context_menu = self.context_menu.write();
 2629            let completion_menu = match context_menu.as_ref() {
 2630                Some(ContextMenu::Completions(menu)) => Some(menu),
 2631
 2632                _ => {
 2633                    *context_menu = None;
 2634                    None
 2635                }
 2636            };
 2637
 2638            if let Some(completion_menu) = completion_menu {
 2639                let cursor_position = new_cursor_position.to_offset(buffer);
 2640                let (word_range, kind) =
 2641                    buffer.surrounding_word(completion_menu.initial_position, true);
 2642                if kind == Some(CharKind::Word)
 2643                    && word_range.to_inclusive().contains(&cursor_position)
 2644                {
 2645                    let mut completion_menu = completion_menu.clone();
 2646                    drop(context_menu);
 2647
 2648                    let query = Self::completion_query(buffer, cursor_position);
 2649                    cx.spawn(move |this, mut cx| async move {
 2650                        completion_menu
 2651                            .filter(query.as_deref(), cx.background_executor().clone())
 2652                            .await;
 2653
 2654                        this.update(&mut cx, |this, cx| {
 2655                            let mut context_menu = this.context_menu.write();
 2656                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2657                                return;
 2658                            };
 2659
 2660                            if menu.id > completion_menu.id {
 2661                                return;
 2662                            }
 2663
 2664                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2665                            drop(context_menu);
 2666                            cx.notify();
 2667                        })
 2668                    })
 2669                    .detach();
 2670
 2671                    if show_completions {
 2672                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2673                    }
 2674                } else {
 2675                    drop(context_menu);
 2676                    self.hide_context_menu(cx);
 2677                }
 2678            } else {
 2679                drop(context_menu);
 2680            }
 2681
 2682            hide_hover(self, cx);
 2683
 2684            if old_cursor_position.to_display_point(&display_map).row()
 2685                != new_cursor_position.to_display_point(&display_map).row()
 2686            {
 2687                self.available_code_actions.take();
 2688            }
 2689            self.refresh_code_actions(cx);
 2690            self.refresh_document_highlights(cx);
 2691            refresh_matching_bracket_highlights(self, cx);
 2692            self.discard_inline_completion(false, cx);
 2693            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2694            if self.git_blame_inline_enabled {
 2695                self.start_inline_blame_timer(cx);
 2696            }
 2697        }
 2698
 2699        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2700        cx.emit(EditorEvent::SelectionsChanged { local });
 2701
 2702        if self.selections.disjoint_anchors().len() == 1 {
 2703            cx.emit(SearchEvent::ActiveMatchChanged)
 2704        }
 2705        cx.notify();
 2706    }
 2707
 2708    pub fn change_selections<R>(
 2709        &mut self,
 2710        autoscroll: Option<Autoscroll>,
 2711        cx: &mut ViewContext<Self>,
 2712        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2713    ) -> R {
 2714        self.change_selections_inner(autoscroll, true, cx, change)
 2715    }
 2716
 2717    pub fn change_selections_inner<R>(
 2718        &mut self,
 2719        autoscroll: Option<Autoscroll>,
 2720        request_completions: bool,
 2721        cx: &mut ViewContext<Self>,
 2722        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2723    ) -> R {
 2724        let old_cursor_position = self.selections.newest_anchor().head();
 2725        self.push_to_selection_history();
 2726
 2727        let (changed, result) = self.selections.change_with(cx, change);
 2728
 2729        if changed {
 2730            if let Some(autoscroll) = autoscroll {
 2731                self.request_autoscroll(autoscroll, cx);
 2732            }
 2733            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2734
 2735            if self.should_open_signature_help_automatically(
 2736                &old_cursor_position,
 2737                self.signature_help_state.backspace_pressed(),
 2738                cx,
 2739            ) {
 2740                self.show_signature_help(&ShowSignatureHelp, cx);
 2741            }
 2742            self.signature_help_state.set_backspace_pressed(false);
 2743        }
 2744
 2745        result
 2746    }
 2747
 2748    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2749    where
 2750        I: IntoIterator<Item = (Range<S>, T)>,
 2751        S: ToOffset,
 2752        T: Into<Arc<str>>,
 2753    {
 2754        if self.read_only(cx) {
 2755            return;
 2756        }
 2757
 2758        self.buffer
 2759            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2760    }
 2761
 2762    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2763    where
 2764        I: IntoIterator<Item = (Range<S>, T)>,
 2765        S: ToOffset,
 2766        T: Into<Arc<str>>,
 2767    {
 2768        if self.read_only(cx) {
 2769            return;
 2770        }
 2771
 2772        self.buffer.update(cx, |buffer, cx| {
 2773            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2774        });
 2775    }
 2776
 2777    pub fn edit_with_block_indent<I, S, T>(
 2778        &mut self,
 2779        edits: I,
 2780        original_indent_columns: Vec<u32>,
 2781        cx: &mut ViewContext<Self>,
 2782    ) where
 2783        I: IntoIterator<Item = (Range<S>, T)>,
 2784        S: ToOffset,
 2785        T: Into<Arc<str>>,
 2786    {
 2787        if self.read_only(cx) {
 2788            return;
 2789        }
 2790
 2791        self.buffer.update(cx, |buffer, cx| {
 2792            buffer.edit(
 2793                edits,
 2794                Some(AutoindentMode::Block {
 2795                    original_indent_columns,
 2796                }),
 2797                cx,
 2798            )
 2799        });
 2800    }
 2801
 2802    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2803        self.hide_context_menu(cx);
 2804
 2805        match phase {
 2806            SelectPhase::Begin {
 2807                position,
 2808                add,
 2809                click_count,
 2810            } => self.begin_selection(position, add, click_count, cx),
 2811            SelectPhase::BeginColumnar {
 2812                position,
 2813                goal_column,
 2814                reset,
 2815            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2816            SelectPhase::Extend {
 2817                position,
 2818                click_count,
 2819            } => self.extend_selection(position, click_count, cx),
 2820            SelectPhase::Update {
 2821                position,
 2822                goal_column,
 2823                scroll_delta,
 2824            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2825            SelectPhase::End => self.end_selection(cx),
 2826        }
 2827    }
 2828
 2829    fn extend_selection(
 2830        &mut self,
 2831        position: DisplayPoint,
 2832        click_count: usize,
 2833        cx: &mut ViewContext<Self>,
 2834    ) {
 2835        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2836        let tail = self.selections.newest::<usize>(cx).tail();
 2837        self.begin_selection(position, false, click_count, cx);
 2838
 2839        let position = position.to_offset(&display_map, Bias::Left);
 2840        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2841
 2842        let mut pending_selection = self
 2843            .selections
 2844            .pending_anchor()
 2845            .expect("extend_selection not called with pending selection");
 2846        if position >= tail {
 2847            pending_selection.start = tail_anchor;
 2848        } else {
 2849            pending_selection.end = tail_anchor;
 2850            pending_selection.reversed = true;
 2851        }
 2852
 2853        let mut pending_mode = self.selections.pending_mode().unwrap();
 2854        match &mut pending_mode {
 2855            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2856            _ => {}
 2857        }
 2858
 2859        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2860            s.set_pending(pending_selection, pending_mode)
 2861        });
 2862    }
 2863
 2864    fn begin_selection(
 2865        &mut self,
 2866        position: DisplayPoint,
 2867        add: bool,
 2868        click_count: usize,
 2869        cx: &mut ViewContext<Self>,
 2870    ) {
 2871        if !self.focus_handle.is_focused(cx) {
 2872            self.last_focused_descendant = None;
 2873            cx.focus(&self.focus_handle);
 2874        }
 2875
 2876        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2877        let buffer = &display_map.buffer_snapshot;
 2878        let newest_selection = self.selections.newest_anchor().clone();
 2879        let position = display_map.clip_point(position, Bias::Left);
 2880
 2881        let start;
 2882        let end;
 2883        let mode;
 2884        let auto_scroll;
 2885        match click_count {
 2886            1 => {
 2887                start = buffer.anchor_before(position.to_point(&display_map));
 2888                end = start;
 2889                mode = SelectMode::Character;
 2890                auto_scroll = true;
 2891            }
 2892            2 => {
 2893                let range = movement::surrounding_word(&display_map, position);
 2894                start = buffer.anchor_before(range.start.to_point(&display_map));
 2895                end = buffer.anchor_before(range.end.to_point(&display_map));
 2896                mode = SelectMode::Word(start..end);
 2897                auto_scroll = true;
 2898            }
 2899            3 => {
 2900                let position = display_map
 2901                    .clip_point(position, Bias::Left)
 2902                    .to_point(&display_map);
 2903                let line_start = display_map.prev_line_boundary(position).0;
 2904                let next_line_start = buffer.clip_point(
 2905                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2906                    Bias::Left,
 2907                );
 2908                start = buffer.anchor_before(line_start);
 2909                end = buffer.anchor_before(next_line_start);
 2910                mode = SelectMode::Line(start..end);
 2911                auto_scroll = true;
 2912            }
 2913            _ => {
 2914                start = buffer.anchor_before(0);
 2915                end = buffer.anchor_before(buffer.len());
 2916                mode = SelectMode::All;
 2917                auto_scroll = false;
 2918            }
 2919        }
 2920
 2921        let point_to_delete: Option<usize> = {
 2922            let selected_points: Vec<Selection<Point>> =
 2923                self.selections.disjoint_in_range(start..end, cx);
 2924
 2925            if !add || click_count > 1 {
 2926                None
 2927            } else if !selected_points.is_empty() {
 2928                Some(selected_points[0].id)
 2929            } else {
 2930                let clicked_point_already_selected =
 2931                    self.selections.disjoint.iter().find(|selection| {
 2932                        selection.start.to_point(buffer) == start.to_point(buffer)
 2933                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2934                    });
 2935
 2936                clicked_point_already_selected.map(|selection| selection.id)
 2937            }
 2938        };
 2939
 2940        let selections_count = self.selections.count();
 2941
 2942        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2943            if let Some(point_to_delete) = point_to_delete {
 2944                s.delete(point_to_delete);
 2945
 2946                if selections_count == 1 {
 2947                    s.set_pending_anchor_range(start..end, mode);
 2948                }
 2949            } else {
 2950                if !add {
 2951                    s.clear_disjoint();
 2952                } else if click_count > 1 {
 2953                    s.delete(newest_selection.id)
 2954                }
 2955
 2956                s.set_pending_anchor_range(start..end, mode);
 2957            }
 2958        });
 2959    }
 2960
 2961    fn begin_columnar_selection(
 2962        &mut self,
 2963        position: DisplayPoint,
 2964        goal_column: u32,
 2965        reset: bool,
 2966        cx: &mut ViewContext<Self>,
 2967    ) {
 2968        if !self.focus_handle.is_focused(cx) {
 2969            self.last_focused_descendant = None;
 2970            cx.focus(&self.focus_handle);
 2971        }
 2972
 2973        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2974
 2975        if reset {
 2976            let pointer_position = display_map
 2977                .buffer_snapshot
 2978                .anchor_before(position.to_point(&display_map));
 2979
 2980            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2981                s.clear_disjoint();
 2982                s.set_pending_anchor_range(
 2983                    pointer_position..pointer_position,
 2984                    SelectMode::Character,
 2985                );
 2986            });
 2987        }
 2988
 2989        let tail = self.selections.newest::<Point>(cx).tail();
 2990        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2991
 2992        if !reset {
 2993            self.select_columns(
 2994                tail.to_display_point(&display_map),
 2995                position,
 2996                goal_column,
 2997                &display_map,
 2998                cx,
 2999            );
 3000        }
 3001    }
 3002
 3003    fn update_selection(
 3004        &mut self,
 3005        position: DisplayPoint,
 3006        goal_column: u32,
 3007        scroll_delta: gpui::Point<f32>,
 3008        cx: &mut ViewContext<Self>,
 3009    ) {
 3010        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3011
 3012        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3013            let tail = tail.to_display_point(&display_map);
 3014            self.select_columns(tail, position, goal_column, &display_map, cx);
 3015        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3016            let buffer = self.buffer.read(cx).snapshot(cx);
 3017            let head;
 3018            let tail;
 3019            let mode = self.selections.pending_mode().unwrap();
 3020            match &mode {
 3021                SelectMode::Character => {
 3022                    head = position.to_point(&display_map);
 3023                    tail = pending.tail().to_point(&buffer);
 3024                }
 3025                SelectMode::Word(original_range) => {
 3026                    let original_display_range = original_range.start.to_display_point(&display_map)
 3027                        ..original_range.end.to_display_point(&display_map);
 3028                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3029                        ..original_display_range.end.to_point(&display_map);
 3030                    if movement::is_inside_word(&display_map, position)
 3031                        || original_display_range.contains(&position)
 3032                    {
 3033                        let word_range = movement::surrounding_word(&display_map, position);
 3034                        if word_range.start < original_display_range.start {
 3035                            head = word_range.start.to_point(&display_map);
 3036                        } else {
 3037                            head = word_range.end.to_point(&display_map);
 3038                        }
 3039                    } else {
 3040                        head = position.to_point(&display_map);
 3041                    }
 3042
 3043                    if head <= original_buffer_range.start {
 3044                        tail = original_buffer_range.end;
 3045                    } else {
 3046                        tail = original_buffer_range.start;
 3047                    }
 3048                }
 3049                SelectMode::Line(original_range) => {
 3050                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3051
 3052                    let position = display_map
 3053                        .clip_point(position, Bias::Left)
 3054                        .to_point(&display_map);
 3055                    let line_start = display_map.prev_line_boundary(position).0;
 3056                    let next_line_start = buffer.clip_point(
 3057                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3058                        Bias::Left,
 3059                    );
 3060
 3061                    if line_start < original_range.start {
 3062                        head = line_start
 3063                    } else {
 3064                        head = next_line_start
 3065                    }
 3066
 3067                    if head <= original_range.start {
 3068                        tail = original_range.end;
 3069                    } else {
 3070                        tail = original_range.start;
 3071                    }
 3072                }
 3073                SelectMode::All => {
 3074                    return;
 3075                }
 3076            };
 3077
 3078            if head < tail {
 3079                pending.start = buffer.anchor_before(head);
 3080                pending.end = buffer.anchor_before(tail);
 3081                pending.reversed = true;
 3082            } else {
 3083                pending.start = buffer.anchor_before(tail);
 3084                pending.end = buffer.anchor_before(head);
 3085                pending.reversed = false;
 3086            }
 3087
 3088            self.change_selections(None, cx, |s| {
 3089                s.set_pending(pending, mode);
 3090            });
 3091        } else {
 3092            log::error!("update_selection dispatched with no pending selection");
 3093            return;
 3094        }
 3095
 3096        self.apply_scroll_delta(scroll_delta, cx);
 3097        cx.notify();
 3098    }
 3099
 3100    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3101        self.columnar_selection_tail.take();
 3102        if self.selections.pending_anchor().is_some() {
 3103            let selections = self.selections.all::<usize>(cx);
 3104            self.change_selections(None, cx, |s| {
 3105                s.select(selections);
 3106                s.clear_pending();
 3107            });
 3108        }
 3109    }
 3110
 3111    fn select_columns(
 3112        &mut self,
 3113        tail: DisplayPoint,
 3114        head: DisplayPoint,
 3115        goal_column: u32,
 3116        display_map: &DisplaySnapshot,
 3117        cx: &mut ViewContext<Self>,
 3118    ) {
 3119        let start_row = cmp::min(tail.row(), head.row());
 3120        let end_row = cmp::max(tail.row(), head.row());
 3121        let start_column = cmp::min(tail.column(), goal_column);
 3122        let end_column = cmp::max(tail.column(), goal_column);
 3123        let reversed = start_column < tail.column();
 3124
 3125        let selection_ranges = (start_row.0..=end_row.0)
 3126            .map(DisplayRow)
 3127            .filter_map(|row| {
 3128                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3129                    let start = display_map
 3130                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3131                        .to_point(display_map);
 3132                    let end = display_map
 3133                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3134                        .to_point(display_map);
 3135                    if reversed {
 3136                        Some(end..start)
 3137                    } else {
 3138                        Some(start..end)
 3139                    }
 3140                } else {
 3141                    None
 3142                }
 3143            })
 3144            .collect::<Vec<_>>();
 3145
 3146        self.change_selections(None, cx, |s| {
 3147            s.select_ranges(selection_ranges);
 3148        });
 3149        cx.notify();
 3150    }
 3151
 3152    pub fn has_pending_nonempty_selection(&self) -> bool {
 3153        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3154            Some(Selection { start, end, .. }) => start != end,
 3155            None => false,
 3156        };
 3157
 3158        pending_nonempty_selection
 3159            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3160    }
 3161
 3162    pub fn has_pending_selection(&self) -> bool {
 3163        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3164    }
 3165
 3166    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3167        if self.clear_expanded_diff_hunks(cx) {
 3168            cx.notify();
 3169            return;
 3170        }
 3171        if self.dismiss_menus_and_popups(true, cx) {
 3172            return;
 3173        }
 3174
 3175        if self.mode == EditorMode::Full
 3176            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3177        {
 3178            return;
 3179        }
 3180
 3181        cx.propagate();
 3182    }
 3183
 3184    pub fn dismiss_menus_and_popups(
 3185        &mut self,
 3186        should_report_inline_completion_event: bool,
 3187        cx: &mut ViewContext<Self>,
 3188    ) -> bool {
 3189        if self.take_rename(false, cx).is_some() {
 3190            return true;
 3191        }
 3192
 3193        if hide_hover(self, cx) {
 3194            return true;
 3195        }
 3196
 3197        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3198            return true;
 3199        }
 3200
 3201        if self.hide_context_menu(cx).is_some() {
 3202            return true;
 3203        }
 3204
 3205        if self.mouse_context_menu.take().is_some() {
 3206            return true;
 3207        }
 3208
 3209        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3210            return true;
 3211        }
 3212
 3213        if self.snippet_stack.pop().is_some() {
 3214            return true;
 3215        }
 3216
 3217        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3218            self.dismiss_diagnostics(cx);
 3219            return true;
 3220        }
 3221
 3222        false
 3223    }
 3224
 3225    fn linked_editing_ranges_for(
 3226        &self,
 3227        selection: Range<text::Anchor>,
 3228        cx: &AppContext,
 3229    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3230        if self.linked_edit_ranges.is_empty() {
 3231            return None;
 3232        }
 3233        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3234            selection.end.buffer_id.and_then(|end_buffer_id| {
 3235                if selection.start.buffer_id != Some(end_buffer_id) {
 3236                    return None;
 3237                }
 3238                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3239                let snapshot = buffer.read(cx).snapshot();
 3240                self.linked_edit_ranges
 3241                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3242                    .map(|ranges| (ranges, snapshot, buffer))
 3243            })?;
 3244        use text::ToOffset as TO;
 3245        // find offset from the start of current range to current cursor position
 3246        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3247
 3248        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3249        let start_difference = start_offset - start_byte_offset;
 3250        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3251        let end_difference = end_offset - start_byte_offset;
 3252        // Current range has associated linked ranges.
 3253        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3254        for range in linked_ranges.iter() {
 3255            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3256            let end_offset = start_offset + end_difference;
 3257            let start_offset = start_offset + start_difference;
 3258            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3259                continue;
 3260            }
 3261            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3262                if s.start.buffer_id != selection.start.buffer_id
 3263                    || s.end.buffer_id != selection.end.buffer_id
 3264                {
 3265                    return false;
 3266                }
 3267                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3268                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3269            }) {
 3270                continue;
 3271            }
 3272            let start = buffer_snapshot.anchor_after(start_offset);
 3273            let end = buffer_snapshot.anchor_after(end_offset);
 3274            linked_edits
 3275                .entry(buffer.clone())
 3276                .or_default()
 3277                .push(start..end);
 3278        }
 3279        Some(linked_edits)
 3280    }
 3281
 3282    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3283        let text: Arc<str> = text.into();
 3284
 3285        if self.read_only(cx) {
 3286            return;
 3287        }
 3288
 3289        let selections = self.selections.all_adjusted(cx);
 3290        let mut bracket_inserted = false;
 3291        let mut edits = Vec::new();
 3292        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3293        let mut new_selections = Vec::with_capacity(selections.len());
 3294        let mut new_autoclose_regions = Vec::new();
 3295        let snapshot = self.buffer.read(cx).read(cx);
 3296
 3297        for (selection, autoclose_region) in
 3298            self.selections_with_autoclose_regions(selections, &snapshot)
 3299        {
 3300            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3301                // Determine if the inserted text matches the opening or closing
 3302                // bracket of any of this language's bracket pairs.
 3303                let mut bracket_pair = None;
 3304                let mut is_bracket_pair_start = false;
 3305                let mut is_bracket_pair_end = false;
 3306                if !text.is_empty() {
 3307                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3308                    //  and they are removing the character that triggered IME popup.
 3309                    for (pair, enabled) in scope.brackets() {
 3310                        if !pair.close && !pair.surround {
 3311                            continue;
 3312                        }
 3313
 3314                        if enabled && pair.start.ends_with(text.as_ref()) {
 3315                            let prefix_len = pair.start.len() - text.len();
 3316                            let preceding_text_matches_prefix = prefix_len == 0
 3317                                || (selection.start.column >= (prefix_len as u32)
 3318                                    && snapshot.contains_str_at(
 3319                                        Point::new(
 3320                                            selection.start.row,
 3321                                            selection.start.column - (prefix_len as u32),
 3322                                        ),
 3323                                        &pair.start[..prefix_len],
 3324                                    ));
 3325                            if preceding_text_matches_prefix {
 3326                                bracket_pair = Some(pair.clone());
 3327                                is_bracket_pair_start = true;
 3328                                break;
 3329                            }
 3330                        }
 3331                        if pair.end.as_str() == text.as_ref() {
 3332                            bracket_pair = Some(pair.clone());
 3333                            is_bracket_pair_end = true;
 3334                            break;
 3335                        }
 3336                    }
 3337                }
 3338
 3339                if let Some(bracket_pair) = bracket_pair {
 3340                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3341                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3342                    let auto_surround =
 3343                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3344                    if selection.is_empty() {
 3345                        if is_bracket_pair_start {
 3346                            // If the inserted text is a suffix of an opening bracket and the
 3347                            // selection is preceded by the rest of the opening bracket, then
 3348                            // insert the closing bracket.
 3349                            let following_text_allows_autoclose = snapshot
 3350                                .chars_at(selection.start)
 3351                                .next()
 3352                                .map_or(true, |c| scope.should_autoclose_before(c));
 3353
 3354                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3355                                && bracket_pair.start.len() == 1
 3356                            {
 3357                                let target = bracket_pair.start.chars().next().unwrap();
 3358                                let current_line_count = snapshot
 3359                                    .reversed_chars_at(selection.start)
 3360                                    .take_while(|&c| c != '\n')
 3361                                    .filter(|&c| c == target)
 3362                                    .count();
 3363                                current_line_count % 2 == 1
 3364                            } else {
 3365                                false
 3366                            };
 3367
 3368                            if autoclose
 3369                                && bracket_pair.close
 3370                                && following_text_allows_autoclose
 3371                                && !is_closing_quote
 3372                            {
 3373                                let anchor = snapshot.anchor_before(selection.end);
 3374                                new_selections.push((selection.map(|_| anchor), text.len()));
 3375                                new_autoclose_regions.push((
 3376                                    anchor,
 3377                                    text.len(),
 3378                                    selection.id,
 3379                                    bracket_pair.clone(),
 3380                                ));
 3381                                edits.push((
 3382                                    selection.range(),
 3383                                    format!("{}{}", text, bracket_pair.end).into(),
 3384                                ));
 3385                                bracket_inserted = true;
 3386                                continue;
 3387                            }
 3388                        }
 3389
 3390                        if let Some(region) = autoclose_region {
 3391                            // If the selection is followed by an auto-inserted closing bracket,
 3392                            // then don't insert that closing bracket again; just move the selection
 3393                            // past the closing bracket.
 3394                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3395                                && text.as_ref() == region.pair.end.as_str();
 3396                            if should_skip {
 3397                                let anchor = snapshot.anchor_after(selection.end);
 3398                                new_selections
 3399                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3400                                continue;
 3401                            }
 3402                        }
 3403
 3404                        let always_treat_brackets_as_autoclosed = snapshot
 3405                            .settings_at(selection.start, cx)
 3406                            .always_treat_brackets_as_autoclosed;
 3407                        if always_treat_brackets_as_autoclosed
 3408                            && is_bracket_pair_end
 3409                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3410                        {
 3411                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3412                            // and the inserted text is a closing bracket and the selection is followed
 3413                            // by the closing bracket then move the selection past the closing bracket.
 3414                            let anchor = snapshot.anchor_after(selection.end);
 3415                            new_selections.push((selection.map(|_| anchor), text.len()));
 3416                            continue;
 3417                        }
 3418                    }
 3419                    // If an opening bracket is 1 character long and is typed while
 3420                    // text is selected, then surround that text with the bracket pair.
 3421                    else if auto_surround
 3422                        && bracket_pair.surround
 3423                        && is_bracket_pair_start
 3424                        && bracket_pair.start.chars().count() == 1
 3425                    {
 3426                        edits.push((selection.start..selection.start, text.clone()));
 3427                        edits.push((
 3428                            selection.end..selection.end,
 3429                            bracket_pair.end.as_str().into(),
 3430                        ));
 3431                        bracket_inserted = true;
 3432                        new_selections.push((
 3433                            Selection {
 3434                                id: selection.id,
 3435                                start: snapshot.anchor_after(selection.start),
 3436                                end: snapshot.anchor_before(selection.end),
 3437                                reversed: selection.reversed,
 3438                                goal: selection.goal,
 3439                            },
 3440                            0,
 3441                        ));
 3442                        continue;
 3443                    }
 3444                }
 3445            }
 3446
 3447            if self.auto_replace_emoji_shortcode
 3448                && selection.is_empty()
 3449                && text.as_ref().ends_with(':')
 3450            {
 3451                if let Some(possible_emoji_short_code) =
 3452                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3453                {
 3454                    if !possible_emoji_short_code.is_empty() {
 3455                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3456                            let emoji_shortcode_start = Point::new(
 3457                                selection.start.row,
 3458                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3459                            );
 3460
 3461                            // Remove shortcode from buffer
 3462                            edits.push((
 3463                                emoji_shortcode_start..selection.start,
 3464                                "".to_string().into(),
 3465                            ));
 3466                            new_selections.push((
 3467                                Selection {
 3468                                    id: selection.id,
 3469                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3470                                    end: snapshot.anchor_before(selection.start),
 3471                                    reversed: selection.reversed,
 3472                                    goal: selection.goal,
 3473                                },
 3474                                0,
 3475                            ));
 3476
 3477                            // Insert emoji
 3478                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3479                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3480                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3481
 3482                            continue;
 3483                        }
 3484                    }
 3485                }
 3486            }
 3487
 3488            // If not handling any auto-close operation, then just replace the selected
 3489            // text with the given input and move the selection to the end of the
 3490            // newly inserted text.
 3491            let anchor = snapshot.anchor_after(selection.end);
 3492            if !self.linked_edit_ranges.is_empty() {
 3493                let start_anchor = snapshot.anchor_before(selection.start);
 3494
 3495                let is_word_char = text.chars().next().map_or(true, |char| {
 3496                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3497                    classifier.is_word(char)
 3498                });
 3499
 3500                if is_word_char {
 3501                    if let Some(ranges) = self
 3502                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3503                    {
 3504                        for (buffer, edits) in ranges {
 3505                            linked_edits
 3506                                .entry(buffer.clone())
 3507                                .or_default()
 3508                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3509                        }
 3510                    }
 3511                }
 3512            }
 3513
 3514            new_selections.push((selection.map(|_| anchor), 0));
 3515            edits.push((selection.start..selection.end, text.clone()));
 3516        }
 3517
 3518        drop(snapshot);
 3519
 3520        self.transact(cx, |this, cx| {
 3521            this.buffer.update(cx, |buffer, cx| {
 3522                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3523            });
 3524            for (buffer, edits) in linked_edits {
 3525                buffer.update(cx, |buffer, cx| {
 3526                    let snapshot = buffer.snapshot();
 3527                    let edits = edits
 3528                        .into_iter()
 3529                        .map(|(range, text)| {
 3530                            use text::ToPoint as TP;
 3531                            let end_point = TP::to_point(&range.end, &snapshot);
 3532                            let start_point = TP::to_point(&range.start, &snapshot);
 3533                            (start_point..end_point, text)
 3534                        })
 3535                        .sorted_by_key(|(range, _)| range.start)
 3536                        .collect::<Vec<_>>();
 3537                    buffer.edit(edits, None, cx);
 3538                })
 3539            }
 3540            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3541            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3542            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3543            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3544                .zip(new_selection_deltas)
 3545                .map(|(selection, delta)| Selection {
 3546                    id: selection.id,
 3547                    start: selection.start + delta,
 3548                    end: selection.end + delta,
 3549                    reversed: selection.reversed,
 3550                    goal: SelectionGoal::None,
 3551                })
 3552                .collect::<Vec<_>>();
 3553
 3554            let mut i = 0;
 3555            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3556                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3557                let start = map.buffer_snapshot.anchor_before(position);
 3558                let end = map.buffer_snapshot.anchor_after(position);
 3559                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3560                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3561                        Ordering::Less => i += 1,
 3562                        Ordering::Greater => break,
 3563                        Ordering::Equal => {
 3564                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3565                                Ordering::Less => i += 1,
 3566                                Ordering::Equal => break,
 3567                                Ordering::Greater => break,
 3568                            }
 3569                        }
 3570                    }
 3571                }
 3572                this.autoclose_regions.insert(
 3573                    i,
 3574                    AutocloseRegion {
 3575                        selection_id,
 3576                        range: start..end,
 3577                        pair,
 3578                    },
 3579                );
 3580            }
 3581
 3582            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3583            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3584                s.select(new_selections)
 3585            });
 3586
 3587            if !bracket_inserted {
 3588                if let Some(on_type_format_task) =
 3589                    this.trigger_on_type_formatting(text.to_string(), cx)
 3590                {
 3591                    on_type_format_task.detach_and_log_err(cx);
 3592                }
 3593            }
 3594
 3595            let editor_settings = EditorSettings::get_global(cx);
 3596            if bracket_inserted
 3597                && (editor_settings.auto_signature_help
 3598                    || editor_settings.show_signature_help_after_edits)
 3599            {
 3600                this.show_signature_help(&ShowSignatureHelp, cx);
 3601            }
 3602
 3603            let trigger_in_words = !had_active_inline_completion;
 3604            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3605            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3606            this.refresh_inline_completion(true, false, cx);
 3607        });
 3608    }
 3609
 3610    fn find_possible_emoji_shortcode_at_position(
 3611        snapshot: &MultiBufferSnapshot,
 3612        position: Point,
 3613    ) -> Option<String> {
 3614        let mut chars = Vec::new();
 3615        let mut found_colon = false;
 3616        for char in snapshot.reversed_chars_at(position).take(100) {
 3617            // Found a possible emoji shortcode in the middle of the buffer
 3618            if found_colon {
 3619                if char.is_whitespace() {
 3620                    chars.reverse();
 3621                    return Some(chars.iter().collect());
 3622                }
 3623                // If the previous character is not a whitespace, we are in the middle of a word
 3624                // and we only want to complete the shortcode if the word is made up of other emojis
 3625                let mut containing_word = String::new();
 3626                for ch in snapshot
 3627                    .reversed_chars_at(position)
 3628                    .skip(chars.len() + 1)
 3629                    .take(100)
 3630                {
 3631                    if ch.is_whitespace() {
 3632                        break;
 3633                    }
 3634                    containing_word.push(ch);
 3635                }
 3636                let containing_word = containing_word.chars().rev().collect::<String>();
 3637                if util::word_consists_of_emojis(containing_word.as_str()) {
 3638                    chars.reverse();
 3639                    return Some(chars.iter().collect());
 3640                }
 3641            }
 3642
 3643            if char.is_whitespace() || !char.is_ascii() {
 3644                return None;
 3645            }
 3646            if char == ':' {
 3647                found_colon = true;
 3648            } else {
 3649                chars.push(char);
 3650            }
 3651        }
 3652        // Found a possible emoji shortcode at the beginning of the buffer
 3653        chars.reverse();
 3654        Some(chars.iter().collect())
 3655    }
 3656
 3657    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3658        self.transact(cx, |this, cx| {
 3659            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3660                let selections = this.selections.all::<usize>(cx);
 3661                let multi_buffer = this.buffer.read(cx);
 3662                let buffer = multi_buffer.snapshot(cx);
 3663                selections
 3664                    .iter()
 3665                    .map(|selection| {
 3666                        let start_point = selection.start.to_point(&buffer);
 3667                        let mut indent =
 3668                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3669                        indent.len = cmp::min(indent.len, start_point.column);
 3670                        let start = selection.start;
 3671                        let end = selection.end;
 3672                        let selection_is_empty = start == end;
 3673                        let language_scope = buffer.language_scope_at(start);
 3674                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3675                            &language_scope
 3676                        {
 3677                            let leading_whitespace_len = buffer
 3678                                .reversed_chars_at(start)
 3679                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3680                                .map(|c| c.len_utf8())
 3681                                .sum::<usize>();
 3682
 3683                            let trailing_whitespace_len = buffer
 3684                                .chars_at(end)
 3685                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3686                                .map(|c| c.len_utf8())
 3687                                .sum::<usize>();
 3688
 3689                            let insert_extra_newline =
 3690                                language.brackets().any(|(pair, enabled)| {
 3691                                    let pair_start = pair.start.trim_end();
 3692                                    let pair_end = pair.end.trim_start();
 3693
 3694                                    enabled
 3695                                        && pair.newline
 3696                                        && buffer.contains_str_at(
 3697                                            end + trailing_whitespace_len,
 3698                                            pair_end,
 3699                                        )
 3700                                        && buffer.contains_str_at(
 3701                                            (start - leading_whitespace_len)
 3702                                                .saturating_sub(pair_start.len()),
 3703                                            pair_start,
 3704                                        )
 3705                                });
 3706
 3707                            // Comment extension on newline is allowed only for cursor selections
 3708                            let comment_delimiter = maybe!({
 3709                                if !selection_is_empty {
 3710                                    return None;
 3711                                }
 3712
 3713                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3714                                    return None;
 3715                                }
 3716
 3717                                let delimiters = language.line_comment_prefixes();
 3718                                let max_len_of_delimiter =
 3719                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3720                                let (snapshot, range) =
 3721                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3722
 3723                                let mut index_of_first_non_whitespace = 0;
 3724                                let comment_candidate = snapshot
 3725                                    .chars_for_range(range)
 3726                                    .skip_while(|c| {
 3727                                        let should_skip = c.is_whitespace();
 3728                                        if should_skip {
 3729                                            index_of_first_non_whitespace += 1;
 3730                                        }
 3731                                        should_skip
 3732                                    })
 3733                                    .take(max_len_of_delimiter)
 3734                                    .collect::<String>();
 3735                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3736                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3737                                })?;
 3738                                let cursor_is_placed_after_comment_marker =
 3739                                    index_of_first_non_whitespace + comment_prefix.len()
 3740                                        <= start_point.column as usize;
 3741                                if cursor_is_placed_after_comment_marker {
 3742                                    Some(comment_prefix.clone())
 3743                                } else {
 3744                                    None
 3745                                }
 3746                            });
 3747                            (comment_delimiter, insert_extra_newline)
 3748                        } else {
 3749                            (None, false)
 3750                        };
 3751
 3752                        let capacity_for_delimiter = comment_delimiter
 3753                            .as_deref()
 3754                            .map(str::len)
 3755                            .unwrap_or_default();
 3756                        let mut new_text =
 3757                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3758                        new_text.push('\n');
 3759                        new_text.extend(indent.chars());
 3760                        if let Some(delimiter) = &comment_delimiter {
 3761                            new_text.push_str(delimiter);
 3762                        }
 3763                        if insert_extra_newline {
 3764                            new_text = new_text.repeat(2);
 3765                        }
 3766
 3767                        let anchor = buffer.anchor_after(end);
 3768                        let new_selection = selection.map(|_| anchor);
 3769                        (
 3770                            (start..end, new_text),
 3771                            (insert_extra_newline, new_selection),
 3772                        )
 3773                    })
 3774                    .unzip()
 3775            };
 3776
 3777            this.edit_with_autoindent(edits, cx);
 3778            let buffer = this.buffer.read(cx).snapshot(cx);
 3779            let new_selections = selection_fixup_info
 3780                .into_iter()
 3781                .map(|(extra_newline_inserted, new_selection)| {
 3782                    let mut cursor = new_selection.end.to_point(&buffer);
 3783                    if extra_newline_inserted {
 3784                        cursor.row -= 1;
 3785                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3786                    }
 3787                    new_selection.map(|_| cursor)
 3788                })
 3789                .collect();
 3790
 3791            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3792            this.refresh_inline_completion(true, false, cx);
 3793        });
 3794    }
 3795
 3796    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3797        let buffer = self.buffer.read(cx);
 3798        let snapshot = buffer.snapshot(cx);
 3799
 3800        let mut edits = Vec::new();
 3801        let mut rows = Vec::new();
 3802
 3803        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3804            let cursor = selection.head();
 3805            let row = cursor.row;
 3806
 3807            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3808
 3809            let newline = "\n".to_string();
 3810            edits.push((start_of_line..start_of_line, newline));
 3811
 3812            rows.push(row + rows_inserted as u32);
 3813        }
 3814
 3815        self.transact(cx, |editor, cx| {
 3816            editor.edit(edits, cx);
 3817
 3818            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3819                let mut index = 0;
 3820                s.move_cursors_with(|map, _, _| {
 3821                    let row = rows[index];
 3822                    index += 1;
 3823
 3824                    let point = Point::new(row, 0);
 3825                    let boundary = map.next_line_boundary(point).1;
 3826                    let clipped = map.clip_point(boundary, Bias::Left);
 3827
 3828                    (clipped, SelectionGoal::None)
 3829                });
 3830            });
 3831
 3832            let mut indent_edits = Vec::new();
 3833            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3834            for row in rows {
 3835                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3836                for (row, indent) in indents {
 3837                    if indent.len == 0 {
 3838                        continue;
 3839                    }
 3840
 3841                    let text = match indent.kind {
 3842                        IndentKind::Space => " ".repeat(indent.len as usize),
 3843                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3844                    };
 3845                    let point = Point::new(row.0, 0);
 3846                    indent_edits.push((point..point, text));
 3847                }
 3848            }
 3849            editor.edit(indent_edits, cx);
 3850        });
 3851    }
 3852
 3853    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3854        let buffer = self.buffer.read(cx);
 3855        let snapshot = buffer.snapshot(cx);
 3856
 3857        let mut edits = Vec::new();
 3858        let mut rows = Vec::new();
 3859        let mut rows_inserted = 0;
 3860
 3861        for selection in self.selections.all_adjusted(cx) {
 3862            let cursor = selection.head();
 3863            let row = cursor.row;
 3864
 3865            let point = Point::new(row + 1, 0);
 3866            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3867
 3868            let newline = "\n".to_string();
 3869            edits.push((start_of_line..start_of_line, newline));
 3870
 3871            rows_inserted += 1;
 3872            rows.push(row + rows_inserted);
 3873        }
 3874
 3875        self.transact(cx, |editor, cx| {
 3876            editor.edit(edits, cx);
 3877
 3878            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3879                let mut index = 0;
 3880                s.move_cursors_with(|map, _, _| {
 3881                    let row = rows[index];
 3882                    index += 1;
 3883
 3884                    let point = Point::new(row, 0);
 3885                    let boundary = map.next_line_boundary(point).1;
 3886                    let clipped = map.clip_point(boundary, Bias::Left);
 3887
 3888                    (clipped, SelectionGoal::None)
 3889                });
 3890            });
 3891
 3892            let mut indent_edits = Vec::new();
 3893            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3894            for row in rows {
 3895                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3896                for (row, indent) in indents {
 3897                    if indent.len == 0 {
 3898                        continue;
 3899                    }
 3900
 3901                    let text = match indent.kind {
 3902                        IndentKind::Space => " ".repeat(indent.len as usize),
 3903                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3904                    };
 3905                    let point = Point::new(row.0, 0);
 3906                    indent_edits.push((point..point, text));
 3907                }
 3908            }
 3909            editor.edit(indent_edits, cx);
 3910        });
 3911    }
 3912
 3913    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3914        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3915            original_indent_columns: Vec::new(),
 3916        });
 3917        self.insert_with_autoindent_mode(text, autoindent, cx);
 3918    }
 3919
 3920    fn insert_with_autoindent_mode(
 3921        &mut self,
 3922        text: &str,
 3923        autoindent_mode: Option<AutoindentMode>,
 3924        cx: &mut ViewContext<Self>,
 3925    ) {
 3926        if self.read_only(cx) {
 3927            return;
 3928        }
 3929
 3930        let text: Arc<str> = text.into();
 3931        self.transact(cx, |this, cx| {
 3932            let old_selections = this.selections.all_adjusted(cx);
 3933            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3934                let anchors = {
 3935                    let snapshot = buffer.read(cx);
 3936                    old_selections
 3937                        .iter()
 3938                        .map(|s| {
 3939                            let anchor = snapshot.anchor_after(s.head());
 3940                            s.map(|_| anchor)
 3941                        })
 3942                        .collect::<Vec<_>>()
 3943                };
 3944                buffer.edit(
 3945                    old_selections
 3946                        .iter()
 3947                        .map(|s| (s.start..s.end, text.clone())),
 3948                    autoindent_mode,
 3949                    cx,
 3950                );
 3951                anchors
 3952            });
 3953
 3954            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3955                s.select_anchors(selection_anchors);
 3956            })
 3957        });
 3958    }
 3959
 3960    fn trigger_completion_on_input(
 3961        &mut self,
 3962        text: &str,
 3963        trigger_in_words: bool,
 3964        cx: &mut ViewContext<Self>,
 3965    ) {
 3966        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3967            self.show_completions(
 3968                &ShowCompletions {
 3969                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3970                },
 3971                cx,
 3972            );
 3973        } else {
 3974            self.hide_context_menu(cx);
 3975        }
 3976    }
 3977
 3978    fn is_completion_trigger(
 3979        &self,
 3980        text: &str,
 3981        trigger_in_words: bool,
 3982        cx: &mut ViewContext<Self>,
 3983    ) -> bool {
 3984        let position = self.selections.newest_anchor().head();
 3985        let multibuffer = self.buffer.read(cx);
 3986        let Some(buffer) = position
 3987            .buffer_id
 3988            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3989        else {
 3990            return false;
 3991        };
 3992
 3993        if let Some(completion_provider) = &self.completion_provider {
 3994            completion_provider.is_completion_trigger(
 3995                &buffer,
 3996                position.text_anchor,
 3997                text,
 3998                trigger_in_words,
 3999                cx,
 4000            )
 4001        } else {
 4002            false
 4003        }
 4004    }
 4005
 4006    /// If any empty selections is touching the start of its innermost containing autoclose
 4007    /// region, expand it to select the brackets.
 4008    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4009        let selections = self.selections.all::<usize>(cx);
 4010        let buffer = self.buffer.read(cx).read(cx);
 4011        let new_selections = self
 4012            .selections_with_autoclose_regions(selections, &buffer)
 4013            .map(|(mut selection, region)| {
 4014                if !selection.is_empty() {
 4015                    return selection;
 4016                }
 4017
 4018                if let Some(region) = region {
 4019                    let mut range = region.range.to_offset(&buffer);
 4020                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4021                        range.start -= region.pair.start.len();
 4022                        if buffer.contains_str_at(range.start, &region.pair.start)
 4023                            && buffer.contains_str_at(range.end, &region.pair.end)
 4024                        {
 4025                            range.end += region.pair.end.len();
 4026                            selection.start = range.start;
 4027                            selection.end = range.end;
 4028
 4029                            return selection;
 4030                        }
 4031                    }
 4032                }
 4033
 4034                let always_treat_brackets_as_autoclosed = buffer
 4035                    .settings_at(selection.start, cx)
 4036                    .always_treat_brackets_as_autoclosed;
 4037
 4038                if !always_treat_brackets_as_autoclosed {
 4039                    return selection;
 4040                }
 4041
 4042                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4043                    for (pair, enabled) in scope.brackets() {
 4044                        if !enabled || !pair.close {
 4045                            continue;
 4046                        }
 4047
 4048                        if buffer.contains_str_at(selection.start, &pair.end) {
 4049                            let pair_start_len = pair.start.len();
 4050                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 4051                            {
 4052                                selection.start -= pair_start_len;
 4053                                selection.end += pair.end.len();
 4054
 4055                                return selection;
 4056                            }
 4057                        }
 4058                    }
 4059                }
 4060
 4061                selection
 4062            })
 4063            .collect();
 4064
 4065        drop(buffer);
 4066        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4067    }
 4068
 4069    /// Iterate the given selections, and for each one, find the smallest surrounding
 4070    /// autoclose region. This uses the ordering of the selections and the autoclose
 4071    /// regions to avoid repeated comparisons.
 4072    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4073        &'a self,
 4074        selections: impl IntoIterator<Item = Selection<D>>,
 4075        buffer: &'a MultiBufferSnapshot,
 4076    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4077        let mut i = 0;
 4078        let mut regions = self.autoclose_regions.as_slice();
 4079        selections.into_iter().map(move |selection| {
 4080            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4081
 4082            let mut enclosing = None;
 4083            while let Some(pair_state) = regions.get(i) {
 4084                if pair_state.range.end.to_offset(buffer) < range.start {
 4085                    regions = &regions[i + 1..];
 4086                    i = 0;
 4087                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4088                    break;
 4089                } else {
 4090                    if pair_state.selection_id == selection.id {
 4091                        enclosing = Some(pair_state);
 4092                    }
 4093                    i += 1;
 4094                }
 4095            }
 4096
 4097            (selection, enclosing)
 4098        })
 4099    }
 4100
 4101    /// Remove any autoclose regions that no longer contain their selection.
 4102    fn invalidate_autoclose_regions(
 4103        &mut self,
 4104        mut selections: &[Selection<Anchor>],
 4105        buffer: &MultiBufferSnapshot,
 4106    ) {
 4107        self.autoclose_regions.retain(|state| {
 4108            let mut i = 0;
 4109            while let Some(selection) = selections.get(i) {
 4110                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4111                    selections = &selections[1..];
 4112                    continue;
 4113                }
 4114                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4115                    break;
 4116                }
 4117                if selection.id == state.selection_id {
 4118                    return true;
 4119                } else {
 4120                    i += 1;
 4121                }
 4122            }
 4123            false
 4124        });
 4125    }
 4126
 4127    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4128        let offset = position.to_offset(buffer);
 4129        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4130        if offset > word_range.start && kind == Some(CharKind::Word) {
 4131            Some(
 4132                buffer
 4133                    .text_for_range(word_range.start..offset)
 4134                    .collect::<String>(),
 4135            )
 4136        } else {
 4137            None
 4138        }
 4139    }
 4140
 4141    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4142        self.refresh_inlay_hints(
 4143            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4144            cx,
 4145        );
 4146    }
 4147
 4148    pub fn inlay_hints_enabled(&self) -> bool {
 4149        self.inlay_hint_cache.enabled
 4150    }
 4151
 4152    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4153        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4154            return;
 4155        }
 4156
 4157        let reason_description = reason.description();
 4158        let ignore_debounce = matches!(
 4159            reason,
 4160            InlayHintRefreshReason::SettingsChange(_)
 4161                | InlayHintRefreshReason::Toggle(_)
 4162                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4163        );
 4164        let (invalidate_cache, required_languages) = match reason {
 4165            InlayHintRefreshReason::Toggle(enabled) => {
 4166                self.inlay_hint_cache.enabled = enabled;
 4167                if enabled {
 4168                    (InvalidationStrategy::RefreshRequested, None)
 4169                } else {
 4170                    self.inlay_hint_cache.clear();
 4171                    self.splice_inlays(
 4172                        self.visible_inlay_hints(cx)
 4173                            .iter()
 4174                            .map(|inlay| inlay.id)
 4175                            .collect(),
 4176                        Vec::new(),
 4177                        cx,
 4178                    );
 4179                    return;
 4180                }
 4181            }
 4182            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4183                match self.inlay_hint_cache.update_settings(
 4184                    &self.buffer,
 4185                    new_settings,
 4186                    self.visible_inlay_hints(cx),
 4187                    cx,
 4188                ) {
 4189                    ControlFlow::Break(Some(InlaySplice {
 4190                        to_remove,
 4191                        to_insert,
 4192                    })) => {
 4193                        self.splice_inlays(to_remove, to_insert, cx);
 4194                        return;
 4195                    }
 4196                    ControlFlow::Break(None) => return,
 4197                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4198                }
 4199            }
 4200            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4201                if let Some(InlaySplice {
 4202                    to_remove,
 4203                    to_insert,
 4204                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4205                {
 4206                    self.splice_inlays(to_remove, to_insert, cx);
 4207                }
 4208                return;
 4209            }
 4210            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4211            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4212                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4213            }
 4214            InlayHintRefreshReason::RefreshRequested => {
 4215                (InvalidationStrategy::RefreshRequested, None)
 4216            }
 4217        };
 4218
 4219        if let Some(InlaySplice {
 4220            to_remove,
 4221            to_insert,
 4222        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4223            reason_description,
 4224            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4225            invalidate_cache,
 4226            ignore_debounce,
 4227            cx,
 4228        ) {
 4229            self.splice_inlays(to_remove, to_insert, cx);
 4230        }
 4231    }
 4232
 4233    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4234        self.display_map
 4235            .read(cx)
 4236            .current_inlays()
 4237            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4238            .cloned()
 4239            .collect()
 4240    }
 4241
 4242    pub fn excerpts_for_inlay_hints_query(
 4243        &self,
 4244        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4245        cx: &mut ViewContext<Editor>,
 4246    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4247        let Some(project) = self.project.as_ref() else {
 4248            return HashMap::default();
 4249        };
 4250        let project = project.read(cx);
 4251        let multi_buffer = self.buffer().read(cx);
 4252        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4253        let multi_buffer_visible_start = self
 4254            .scroll_manager
 4255            .anchor()
 4256            .anchor
 4257            .to_point(&multi_buffer_snapshot);
 4258        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4259            multi_buffer_visible_start
 4260                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4261            Bias::Left,
 4262        );
 4263        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4264        multi_buffer
 4265            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4266            .into_iter()
 4267            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4268            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4269                let buffer = buffer_handle.read(cx);
 4270                let buffer_file = project::File::from_dyn(buffer.file())?;
 4271                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4272                let worktree_entry = buffer_worktree
 4273                    .read(cx)
 4274                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4275                if worktree_entry.is_ignored {
 4276                    return None;
 4277                }
 4278
 4279                let language = buffer.language()?;
 4280                if let Some(restrict_to_languages) = restrict_to_languages {
 4281                    if !restrict_to_languages.contains(language) {
 4282                        return None;
 4283                    }
 4284                }
 4285                Some((
 4286                    excerpt_id,
 4287                    (
 4288                        buffer_handle,
 4289                        buffer.version().clone(),
 4290                        excerpt_visible_range,
 4291                    ),
 4292                ))
 4293            })
 4294            .collect()
 4295    }
 4296
 4297    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4298        TextLayoutDetails {
 4299            text_system: cx.text_system().clone(),
 4300            editor_style: self.style.clone().unwrap(),
 4301            rem_size: cx.rem_size(),
 4302            scroll_anchor: self.scroll_manager.anchor(),
 4303            visible_rows: self.visible_line_count(),
 4304            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4305        }
 4306    }
 4307
 4308    fn splice_inlays(
 4309        &self,
 4310        to_remove: Vec<InlayId>,
 4311        to_insert: Vec<Inlay>,
 4312        cx: &mut ViewContext<Self>,
 4313    ) {
 4314        self.display_map.update(cx, |display_map, cx| {
 4315            display_map.splice_inlays(to_remove, to_insert, cx);
 4316        });
 4317        cx.notify();
 4318    }
 4319
 4320    fn trigger_on_type_formatting(
 4321        &self,
 4322        input: String,
 4323        cx: &mut ViewContext<Self>,
 4324    ) -> Option<Task<Result<()>>> {
 4325        if input.len() != 1 {
 4326            return None;
 4327        }
 4328
 4329        let project = self.project.as_ref()?;
 4330        let position = self.selections.newest_anchor().head();
 4331        let (buffer, buffer_position) = self
 4332            .buffer
 4333            .read(cx)
 4334            .text_anchor_for_position(position, cx)?;
 4335
 4336        let settings = language_settings::language_settings(
 4337            buffer
 4338                .read(cx)
 4339                .language_at(buffer_position)
 4340                .map(|l| l.name()),
 4341            buffer.read(cx).file(),
 4342            cx,
 4343        );
 4344        if !settings.use_on_type_format {
 4345            return None;
 4346        }
 4347
 4348        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4349        // hence we do LSP request & edit on host side only — add formats to host's history.
 4350        let push_to_lsp_host_history = true;
 4351        // If this is not the host, append its history with new edits.
 4352        let push_to_client_history = project.read(cx).is_via_collab();
 4353
 4354        let on_type_formatting = project.update(cx, |project, cx| {
 4355            project.on_type_format(
 4356                buffer.clone(),
 4357                buffer_position,
 4358                input,
 4359                push_to_lsp_host_history,
 4360                cx,
 4361            )
 4362        });
 4363        Some(cx.spawn(|editor, mut cx| async move {
 4364            if let Some(transaction) = on_type_formatting.await? {
 4365                if push_to_client_history {
 4366                    buffer
 4367                        .update(&mut cx, |buffer, _| {
 4368                            buffer.push_transaction(transaction, Instant::now());
 4369                        })
 4370                        .ok();
 4371                }
 4372                editor.update(&mut cx, |editor, cx| {
 4373                    editor.refresh_document_highlights(cx);
 4374                })?;
 4375            }
 4376            Ok(())
 4377        }))
 4378    }
 4379
 4380    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4381        if self.pending_rename.is_some() {
 4382            return;
 4383        }
 4384
 4385        let Some(provider) = self.completion_provider.as_ref() else {
 4386            return;
 4387        };
 4388
 4389        let position = self.selections.newest_anchor().head();
 4390        let (buffer, buffer_position) =
 4391            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4392                output
 4393            } else {
 4394                return;
 4395            };
 4396
 4397        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4398        let is_followup_invoke = {
 4399            let context_menu_state = self.context_menu.read();
 4400            matches!(
 4401                context_menu_state.deref(),
 4402                Some(ContextMenu::Completions(_))
 4403            )
 4404        };
 4405        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4406            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4407            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4408                CompletionTriggerKind::TRIGGER_CHARACTER
 4409            }
 4410
 4411            _ => CompletionTriggerKind::INVOKED,
 4412        };
 4413        let completion_context = CompletionContext {
 4414            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4415                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4416                    Some(String::from(trigger))
 4417                } else {
 4418                    None
 4419                }
 4420            }),
 4421            trigger_kind,
 4422        };
 4423        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4424        let sort_completions = provider.sort_completions();
 4425
 4426        let id = post_inc(&mut self.next_completion_id);
 4427        let task = cx.spawn(|this, mut cx| {
 4428            async move {
 4429                this.update(&mut cx, |this, _| {
 4430                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4431                })?;
 4432                let completions = completions.await.log_err();
 4433                let menu = if let Some(completions) = completions {
 4434                    let mut menu = CompletionsMenu {
 4435                        id,
 4436                        sort_completions,
 4437                        initial_position: position,
 4438                        match_candidates: completions
 4439                            .iter()
 4440                            .enumerate()
 4441                            .map(|(id, completion)| {
 4442                                StringMatchCandidate::new(
 4443                                    id,
 4444                                    completion.label.text[completion.label.filter_range.clone()]
 4445                                        .into(),
 4446                                )
 4447                            })
 4448                            .collect(),
 4449                        buffer: buffer.clone(),
 4450                        completions: Arc::new(RwLock::new(completions.into())),
 4451                        matches: Vec::new().into(),
 4452                        selected_item: 0,
 4453                        scroll_handle: UniformListScrollHandle::new(),
 4454                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4455                            DebouncedDelay::new(),
 4456                        )),
 4457                    };
 4458                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4459                        .await;
 4460
 4461                    if menu.matches.is_empty() {
 4462                        None
 4463                    } else {
 4464                        this.update(&mut cx, |editor, cx| {
 4465                            let completions = menu.completions.clone();
 4466                            let matches = menu.matches.clone();
 4467
 4468                            let delay_ms = EditorSettings::get_global(cx)
 4469                                .completion_documentation_secondary_query_debounce;
 4470                            let delay = Duration::from_millis(delay_ms);
 4471                            editor
 4472                                .completion_documentation_pre_resolve_debounce
 4473                                .fire_new(delay, cx, |editor, cx| {
 4474                                    CompletionsMenu::pre_resolve_completion_documentation(
 4475                                        buffer,
 4476                                        completions,
 4477                                        matches,
 4478                                        editor,
 4479                                        cx,
 4480                                    )
 4481                                });
 4482                        })
 4483                        .ok();
 4484                        Some(menu)
 4485                    }
 4486                } else {
 4487                    None
 4488                };
 4489
 4490                this.update(&mut cx, |this, cx| {
 4491                    let mut context_menu = this.context_menu.write();
 4492                    match context_menu.as_ref() {
 4493                        None => {}
 4494
 4495                        Some(ContextMenu::Completions(prev_menu)) => {
 4496                            if prev_menu.id > id {
 4497                                return;
 4498                            }
 4499                        }
 4500
 4501                        _ => return,
 4502                    }
 4503
 4504                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4505                        let menu = menu.unwrap();
 4506                        *context_menu = Some(ContextMenu::Completions(menu));
 4507                        drop(context_menu);
 4508                        this.discard_inline_completion(false, cx);
 4509                        cx.notify();
 4510                    } else if this.completion_tasks.len() <= 1 {
 4511                        // If there are no more completion tasks and the last menu was
 4512                        // empty, we should hide it. If it was already hidden, we should
 4513                        // also show the copilot completion when available.
 4514                        drop(context_menu);
 4515                        if this.hide_context_menu(cx).is_none() {
 4516                            this.update_visible_inline_completion(cx);
 4517                        }
 4518                    }
 4519                })?;
 4520
 4521                Ok::<_, anyhow::Error>(())
 4522            }
 4523            .log_err()
 4524        });
 4525
 4526        self.completion_tasks.push((id, task));
 4527    }
 4528
 4529    pub fn confirm_completion(
 4530        &mut self,
 4531        action: &ConfirmCompletion,
 4532        cx: &mut ViewContext<Self>,
 4533    ) -> Option<Task<Result<()>>> {
 4534        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4535    }
 4536
 4537    pub fn compose_completion(
 4538        &mut self,
 4539        action: &ComposeCompletion,
 4540        cx: &mut ViewContext<Self>,
 4541    ) -> Option<Task<Result<()>>> {
 4542        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4543    }
 4544
 4545    fn do_completion(
 4546        &mut self,
 4547        item_ix: Option<usize>,
 4548        intent: CompletionIntent,
 4549        cx: &mut ViewContext<Editor>,
 4550    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4551        use language::ToOffset as _;
 4552
 4553        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4554            menu
 4555        } else {
 4556            return None;
 4557        };
 4558
 4559        let mat = completions_menu
 4560            .matches
 4561            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4562        let buffer_handle = completions_menu.buffer;
 4563        let completions = completions_menu.completions.read();
 4564        let completion = completions.get(mat.candidate_id)?;
 4565        cx.stop_propagation();
 4566
 4567        let snippet;
 4568        let text;
 4569
 4570        if completion.is_snippet() {
 4571            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4572            text = snippet.as_ref().unwrap().text.clone();
 4573        } else {
 4574            snippet = None;
 4575            text = completion.new_text.clone();
 4576        };
 4577        let selections = self.selections.all::<usize>(cx);
 4578        let buffer = buffer_handle.read(cx);
 4579        let old_range = completion.old_range.to_offset(buffer);
 4580        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4581
 4582        let newest_selection = self.selections.newest_anchor();
 4583        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4584            return None;
 4585        }
 4586
 4587        let lookbehind = newest_selection
 4588            .start
 4589            .text_anchor
 4590            .to_offset(buffer)
 4591            .saturating_sub(old_range.start);
 4592        let lookahead = old_range
 4593            .end
 4594            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4595        let mut common_prefix_len = old_text
 4596            .bytes()
 4597            .zip(text.bytes())
 4598            .take_while(|(a, b)| a == b)
 4599            .count();
 4600
 4601        let snapshot = self.buffer.read(cx).snapshot(cx);
 4602        let mut range_to_replace: Option<Range<isize>> = None;
 4603        let mut ranges = Vec::new();
 4604        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4605        for selection in &selections {
 4606            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4607                let start = selection.start.saturating_sub(lookbehind);
 4608                let end = selection.end + lookahead;
 4609                if selection.id == newest_selection.id {
 4610                    range_to_replace = Some(
 4611                        ((start + common_prefix_len) as isize - selection.start as isize)
 4612                            ..(end as isize - selection.start as isize),
 4613                    );
 4614                }
 4615                ranges.push(start + common_prefix_len..end);
 4616            } else {
 4617                common_prefix_len = 0;
 4618                ranges.clear();
 4619                ranges.extend(selections.iter().map(|s| {
 4620                    if s.id == newest_selection.id {
 4621                        range_to_replace = Some(
 4622                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4623                                - selection.start as isize
 4624                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4625                                    - selection.start as isize,
 4626                        );
 4627                        old_range.clone()
 4628                    } else {
 4629                        s.start..s.end
 4630                    }
 4631                }));
 4632                break;
 4633            }
 4634            if !self.linked_edit_ranges.is_empty() {
 4635                let start_anchor = snapshot.anchor_before(selection.head());
 4636                let end_anchor = snapshot.anchor_after(selection.tail());
 4637                if let Some(ranges) = self
 4638                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4639                {
 4640                    for (buffer, edits) in ranges {
 4641                        linked_edits.entry(buffer.clone()).or_default().extend(
 4642                            edits
 4643                                .into_iter()
 4644                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4645                        );
 4646                    }
 4647                }
 4648            }
 4649        }
 4650        let text = &text[common_prefix_len..];
 4651
 4652        cx.emit(EditorEvent::InputHandled {
 4653            utf16_range_to_replace: range_to_replace,
 4654            text: text.into(),
 4655        });
 4656
 4657        self.transact(cx, |this, cx| {
 4658            if let Some(mut snippet) = snippet {
 4659                snippet.text = text.to_string();
 4660                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4661                    tabstop.start -= common_prefix_len as isize;
 4662                    tabstop.end -= common_prefix_len as isize;
 4663                }
 4664
 4665                this.insert_snippet(&ranges, snippet, cx).log_err();
 4666            } else {
 4667                this.buffer.update(cx, |buffer, cx| {
 4668                    buffer.edit(
 4669                        ranges.iter().map(|range| (range.clone(), text)),
 4670                        this.autoindent_mode.clone(),
 4671                        cx,
 4672                    );
 4673                });
 4674            }
 4675            for (buffer, edits) in linked_edits {
 4676                buffer.update(cx, |buffer, cx| {
 4677                    let snapshot = buffer.snapshot();
 4678                    let edits = edits
 4679                        .into_iter()
 4680                        .map(|(range, text)| {
 4681                            use text::ToPoint as TP;
 4682                            let end_point = TP::to_point(&range.end, &snapshot);
 4683                            let start_point = TP::to_point(&range.start, &snapshot);
 4684                            (start_point..end_point, text)
 4685                        })
 4686                        .sorted_by_key(|(range, _)| range.start)
 4687                        .collect::<Vec<_>>();
 4688                    buffer.edit(edits, None, cx);
 4689                })
 4690            }
 4691
 4692            this.refresh_inline_completion(true, false, cx);
 4693        });
 4694
 4695        let show_new_completions_on_confirm = completion
 4696            .confirm
 4697            .as_ref()
 4698            .map_or(false, |confirm| confirm(intent, cx));
 4699        if show_new_completions_on_confirm {
 4700            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4701        }
 4702
 4703        let provider = self.completion_provider.as_ref()?;
 4704        let apply_edits = provider.apply_additional_edits_for_completion(
 4705            buffer_handle,
 4706            completion.clone(),
 4707            true,
 4708            cx,
 4709        );
 4710
 4711        let editor_settings = EditorSettings::get_global(cx);
 4712        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4713            // After the code completion is finished, users often want to know what signatures are needed.
 4714            // so we should automatically call signature_help
 4715            self.show_signature_help(&ShowSignatureHelp, cx);
 4716        }
 4717
 4718        Some(cx.foreground_executor().spawn(async move {
 4719            apply_edits.await?;
 4720            Ok(())
 4721        }))
 4722    }
 4723
 4724    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4725        let mut context_menu = self.context_menu.write();
 4726        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4727            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4728                // Toggle if we're selecting the same one
 4729                *context_menu = None;
 4730                cx.notify();
 4731                return;
 4732            } else {
 4733                // Otherwise, clear it and start a new one
 4734                *context_menu = None;
 4735                cx.notify();
 4736            }
 4737        }
 4738        drop(context_menu);
 4739        let snapshot = self.snapshot(cx);
 4740        let deployed_from_indicator = action.deployed_from_indicator;
 4741        let mut task = self.code_actions_task.take();
 4742        let action = action.clone();
 4743        cx.spawn(|editor, mut cx| async move {
 4744            while let Some(prev_task) = task {
 4745                prev_task.await.log_err();
 4746                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4747            }
 4748
 4749            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4750                if editor.focus_handle.is_focused(cx) {
 4751                    let multibuffer_point = action
 4752                        .deployed_from_indicator
 4753                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4754                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4755                    let (buffer, buffer_row) = snapshot
 4756                        .buffer_snapshot
 4757                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4758                        .and_then(|(buffer_snapshot, range)| {
 4759                            editor
 4760                                .buffer
 4761                                .read(cx)
 4762                                .buffer(buffer_snapshot.remote_id())
 4763                                .map(|buffer| (buffer, range.start.row))
 4764                        })?;
 4765                    let (_, code_actions) = editor
 4766                        .available_code_actions
 4767                        .clone()
 4768                        .and_then(|(location, code_actions)| {
 4769                            let snapshot = location.buffer.read(cx).snapshot();
 4770                            let point_range = location.range.to_point(&snapshot);
 4771                            let point_range = point_range.start.row..=point_range.end.row;
 4772                            if point_range.contains(&buffer_row) {
 4773                                Some((location, code_actions))
 4774                            } else {
 4775                                None
 4776                            }
 4777                        })
 4778                        .unzip();
 4779                    let buffer_id = buffer.read(cx).remote_id();
 4780                    let tasks = editor
 4781                        .tasks
 4782                        .get(&(buffer_id, buffer_row))
 4783                        .map(|t| Arc::new(t.to_owned()));
 4784                    if tasks.is_none() && code_actions.is_none() {
 4785                        return None;
 4786                    }
 4787
 4788                    editor.completion_tasks.clear();
 4789                    editor.discard_inline_completion(false, cx);
 4790                    let task_context =
 4791                        tasks
 4792                            .as_ref()
 4793                            .zip(editor.project.clone())
 4794                            .map(|(tasks, project)| {
 4795                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4796                            });
 4797
 4798                    Some(cx.spawn(|editor, mut cx| async move {
 4799                        let task_context = match task_context {
 4800                            Some(task_context) => task_context.await,
 4801                            None => None,
 4802                        };
 4803                        let resolved_tasks =
 4804                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4805                                Arc::new(ResolvedTasks {
 4806                                    templates: tasks.resolve(&task_context).collect(),
 4807                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4808                                        multibuffer_point.row,
 4809                                        tasks.column,
 4810                                    )),
 4811                                })
 4812                            });
 4813                        let spawn_straight_away = resolved_tasks
 4814                            .as_ref()
 4815                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4816                            && code_actions
 4817                                .as_ref()
 4818                                .map_or(true, |actions| actions.is_empty());
 4819                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4820                            *editor.context_menu.write() =
 4821                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4822                                    buffer,
 4823                                    actions: CodeActionContents {
 4824                                        tasks: resolved_tasks,
 4825                                        actions: code_actions,
 4826                                    },
 4827                                    selected_item: Default::default(),
 4828                                    scroll_handle: UniformListScrollHandle::default(),
 4829                                    deployed_from_indicator,
 4830                                }));
 4831                            if spawn_straight_away {
 4832                                if let Some(task) = editor.confirm_code_action(
 4833                                    &ConfirmCodeAction { item_ix: Some(0) },
 4834                                    cx,
 4835                                ) {
 4836                                    cx.notify();
 4837                                    return task;
 4838                                }
 4839                            }
 4840                            cx.notify();
 4841                            Task::ready(Ok(()))
 4842                        }) {
 4843                            task.await
 4844                        } else {
 4845                            Ok(())
 4846                        }
 4847                    }))
 4848                } else {
 4849                    Some(Task::ready(Ok(())))
 4850                }
 4851            })?;
 4852            if let Some(task) = spawned_test_task {
 4853                task.await?;
 4854            }
 4855
 4856            Ok::<_, anyhow::Error>(())
 4857        })
 4858        .detach_and_log_err(cx);
 4859    }
 4860
 4861    pub fn confirm_code_action(
 4862        &mut self,
 4863        action: &ConfirmCodeAction,
 4864        cx: &mut ViewContext<Self>,
 4865    ) -> Option<Task<Result<()>>> {
 4866        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4867            menu
 4868        } else {
 4869            return None;
 4870        };
 4871        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4872        let action = actions_menu.actions.get(action_ix)?;
 4873        let title = action.label();
 4874        let buffer = actions_menu.buffer;
 4875        let workspace = self.workspace()?;
 4876
 4877        match action {
 4878            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4879                workspace.update(cx, |workspace, cx| {
 4880                    workspace::tasks::schedule_resolved_task(
 4881                        workspace,
 4882                        task_source_kind,
 4883                        resolved_task,
 4884                        false,
 4885                        cx,
 4886                    );
 4887
 4888                    Some(Task::ready(Ok(())))
 4889                })
 4890            }
 4891            CodeActionsItem::CodeAction {
 4892                excerpt_id,
 4893                action,
 4894                provider,
 4895            } => {
 4896                let apply_code_action =
 4897                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4898                let workspace = workspace.downgrade();
 4899                Some(cx.spawn(|editor, cx| async move {
 4900                    let project_transaction = apply_code_action.await?;
 4901                    Self::open_project_transaction(
 4902                        &editor,
 4903                        workspace,
 4904                        project_transaction,
 4905                        title,
 4906                        cx,
 4907                    )
 4908                    .await
 4909                }))
 4910            }
 4911        }
 4912    }
 4913
 4914    pub async fn open_project_transaction(
 4915        this: &WeakView<Editor>,
 4916        workspace: WeakView<Workspace>,
 4917        transaction: ProjectTransaction,
 4918        title: String,
 4919        mut cx: AsyncWindowContext,
 4920    ) -> Result<()> {
 4921        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4922        cx.update(|cx| {
 4923            entries.sort_unstable_by_key(|(buffer, _)| {
 4924                buffer.read(cx).file().map(|f| f.path().clone())
 4925            });
 4926        })?;
 4927
 4928        // If the project transaction's edits are all contained within this editor, then
 4929        // avoid opening a new editor to display them.
 4930
 4931        if let Some((buffer, transaction)) = entries.first() {
 4932            if entries.len() == 1 {
 4933                let excerpt = this.update(&mut cx, |editor, cx| {
 4934                    editor
 4935                        .buffer()
 4936                        .read(cx)
 4937                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4938                })?;
 4939                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4940                    if excerpted_buffer == *buffer {
 4941                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4942                            let excerpt_range = excerpt_range.to_offset(buffer);
 4943                            buffer
 4944                                .edited_ranges_for_transaction::<usize>(transaction)
 4945                                .all(|range| {
 4946                                    excerpt_range.start <= range.start
 4947                                        && excerpt_range.end >= range.end
 4948                                })
 4949                        })?;
 4950
 4951                        if all_edits_within_excerpt {
 4952                            return Ok(());
 4953                        }
 4954                    }
 4955                }
 4956            }
 4957        } else {
 4958            return Ok(());
 4959        }
 4960
 4961        let mut ranges_to_highlight = Vec::new();
 4962        let excerpt_buffer = cx.new_model(|cx| {
 4963            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4964            for (buffer_handle, transaction) in &entries {
 4965                let buffer = buffer_handle.read(cx);
 4966                ranges_to_highlight.extend(
 4967                    multibuffer.push_excerpts_with_context_lines(
 4968                        buffer_handle.clone(),
 4969                        buffer
 4970                            .edited_ranges_for_transaction::<usize>(transaction)
 4971                            .collect(),
 4972                        DEFAULT_MULTIBUFFER_CONTEXT,
 4973                        cx,
 4974                    ),
 4975                );
 4976            }
 4977            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4978            multibuffer
 4979        })?;
 4980
 4981        workspace.update(&mut cx, |workspace, cx| {
 4982            let project = workspace.project().clone();
 4983            let editor =
 4984                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4985            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4986            editor.update(cx, |editor, cx| {
 4987                editor.highlight_background::<Self>(
 4988                    &ranges_to_highlight,
 4989                    |theme| theme.editor_highlighted_line_background,
 4990                    cx,
 4991                );
 4992            });
 4993        })?;
 4994
 4995        Ok(())
 4996    }
 4997
 4998    pub fn clear_code_action_providers(&mut self) {
 4999        self.code_action_providers.clear();
 5000        self.available_code_actions.take();
 5001    }
 5002
 5003    pub fn push_code_action_provider(
 5004        &mut self,
 5005        provider: Arc<dyn CodeActionProvider>,
 5006        cx: &mut ViewContext<Self>,
 5007    ) {
 5008        self.code_action_providers.push(provider);
 5009        self.refresh_code_actions(cx);
 5010    }
 5011
 5012    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5013        let buffer = self.buffer.read(cx);
 5014        let newest_selection = self.selections.newest_anchor().clone();
 5015        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5016        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5017        if start_buffer != end_buffer {
 5018            return None;
 5019        }
 5020
 5021        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5022            cx.background_executor()
 5023                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5024                .await;
 5025
 5026            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5027                let providers = this.code_action_providers.clone();
 5028                let tasks = this
 5029                    .code_action_providers
 5030                    .iter()
 5031                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5032                    .collect::<Vec<_>>();
 5033                (providers, tasks)
 5034            })?;
 5035
 5036            let mut actions = Vec::new();
 5037            for (provider, provider_actions) in
 5038                providers.into_iter().zip(future::join_all(tasks).await)
 5039            {
 5040                if let Some(provider_actions) = provider_actions.log_err() {
 5041                    actions.extend(provider_actions.into_iter().map(|action| {
 5042                        AvailableCodeAction {
 5043                            excerpt_id: newest_selection.start.excerpt_id,
 5044                            action,
 5045                            provider: provider.clone(),
 5046                        }
 5047                    }));
 5048                }
 5049            }
 5050
 5051            this.update(&mut cx, |this, cx| {
 5052                this.available_code_actions = if actions.is_empty() {
 5053                    None
 5054                } else {
 5055                    Some((
 5056                        Location {
 5057                            buffer: start_buffer,
 5058                            range: start..end,
 5059                        },
 5060                        actions.into(),
 5061                    ))
 5062                };
 5063                cx.notify();
 5064            })
 5065        }));
 5066        None
 5067    }
 5068
 5069    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5070        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5071            self.show_git_blame_inline = false;
 5072
 5073            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5074                cx.background_executor().timer(delay).await;
 5075
 5076                this.update(&mut cx, |this, cx| {
 5077                    this.show_git_blame_inline = true;
 5078                    cx.notify();
 5079                })
 5080                .log_err();
 5081            }));
 5082        }
 5083    }
 5084
 5085    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5086        if self.pending_rename.is_some() {
 5087            return None;
 5088        }
 5089
 5090        let provider = self.semantics_provider.clone()?;
 5091        let buffer = self.buffer.read(cx);
 5092        let newest_selection = self.selections.newest_anchor().clone();
 5093        let cursor_position = newest_selection.head();
 5094        let (cursor_buffer, cursor_buffer_position) =
 5095            buffer.text_anchor_for_position(cursor_position, cx)?;
 5096        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5097        if cursor_buffer != tail_buffer {
 5098            return None;
 5099        }
 5100
 5101        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5102            cx.background_executor()
 5103                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5104                .await;
 5105
 5106            let highlights = if let Some(highlights) = cx
 5107                .update(|cx| {
 5108                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5109                })
 5110                .ok()
 5111                .flatten()
 5112            {
 5113                highlights.await.log_err()
 5114            } else {
 5115                None
 5116            };
 5117
 5118            if let Some(highlights) = highlights {
 5119                this.update(&mut cx, |this, cx| {
 5120                    if this.pending_rename.is_some() {
 5121                        return;
 5122                    }
 5123
 5124                    let buffer_id = cursor_position.buffer_id;
 5125                    let buffer = this.buffer.read(cx);
 5126                    if !buffer
 5127                        .text_anchor_for_position(cursor_position, cx)
 5128                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5129                    {
 5130                        return;
 5131                    }
 5132
 5133                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5134                    let mut write_ranges = Vec::new();
 5135                    let mut read_ranges = Vec::new();
 5136                    for highlight in highlights {
 5137                        for (excerpt_id, excerpt_range) in
 5138                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5139                        {
 5140                            let start = highlight
 5141                                .range
 5142                                .start
 5143                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5144                            let end = highlight
 5145                                .range
 5146                                .end
 5147                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5148                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5149                                continue;
 5150                            }
 5151
 5152                            let range = Anchor {
 5153                                buffer_id,
 5154                                excerpt_id,
 5155                                text_anchor: start,
 5156                            }..Anchor {
 5157                                buffer_id,
 5158                                excerpt_id,
 5159                                text_anchor: end,
 5160                            };
 5161                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5162                                write_ranges.push(range);
 5163                            } else {
 5164                                read_ranges.push(range);
 5165                            }
 5166                        }
 5167                    }
 5168
 5169                    this.highlight_background::<DocumentHighlightRead>(
 5170                        &read_ranges,
 5171                        |theme| theme.editor_document_highlight_read_background,
 5172                        cx,
 5173                    );
 5174                    this.highlight_background::<DocumentHighlightWrite>(
 5175                        &write_ranges,
 5176                        |theme| theme.editor_document_highlight_write_background,
 5177                        cx,
 5178                    );
 5179                    cx.notify();
 5180                })
 5181                .log_err();
 5182            }
 5183        }));
 5184        None
 5185    }
 5186
 5187    pub fn refresh_inline_completion(
 5188        &mut self,
 5189        debounce: bool,
 5190        user_requested: bool,
 5191        cx: &mut ViewContext<Self>,
 5192    ) -> Option<()> {
 5193        let provider = self.inline_completion_provider()?;
 5194        let cursor = self.selections.newest_anchor().head();
 5195        let (buffer, cursor_buffer_position) =
 5196            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5197
 5198        if !user_requested
 5199            && (!self.enable_inline_completions
 5200                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5201        {
 5202            self.discard_inline_completion(false, cx);
 5203            return None;
 5204        }
 5205
 5206        self.update_visible_inline_completion(cx);
 5207        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5208        Some(())
 5209    }
 5210
 5211    fn cycle_inline_completion(
 5212        &mut self,
 5213        direction: Direction,
 5214        cx: &mut ViewContext<Self>,
 5215    ) -> Option<()> {
 5216        let provider = self.inline_completion_provider()?;
 5217        let cursor = self.selections.newest_anchor().head();
 5218        let (buffer, cursor_buffer_position) =
 5219            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5220        if !self.enable_inline_completions
 5221            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5222        {
 5223            return None;
 5224        }
 5225
 5226        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5227        self.update_visible_inline_completion(cx);
 5228
 5229        Some(())
 5230    }
 5231
 5232    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5233        if !self.has_active_inline_completion(cx) {
 5234            self.refresh_inline_completion(false, true, cx);
 5235            return;
 5236        }
 5237
 5238        self.update_visible_inline_completion(cx);
 5239    }
 5240
 5241    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5242        self.show_cursor_names(cx);
 5243    }
 5244
 5245    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5246        self.show_cursor_names = true;
 5247        cx.notify();
 5248        cx.spawn(|this, mut cx| async move {
 5249            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5250            this.update(&mut cx, |this, cx| {
 5251                this.show_cursor_names = false;
 5252                cx.notify()
 5253            })
 5254            .ok()
 5255        })
 5256        .detach();
 5257    }
 5258
 5259    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5260        if self.has_active_inline_completion(cx) {
 5261            self.cycle_inline_completion(Direction::Next, cx);
 5262        } else {
 5263            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5264            if is_copilot_disabled {
 5265                cx.propagate();
 5266            }
 5267        }
 5268    }
 5269
 5270    pub fn previous_inline_completion(
 5271        &mut self,
 5272        _: &PreviousInlineCompletion,
 5273        cx: &mut ViewContext<Self>,
 5274    ) {
 5275        if self.has_active_inline_completion(cx) {
 5276            self.cycle_inline_completion(Direction::Prev, cx);
 5277        } else {
 5278            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5279            if is_copilot_disabled {
 5280                cx.propagate();
 5281            }
 5282        }
 5283    }
 5284
 5285    pub fn accept_inline_completion(
 5286        &mut self,
 5287        _: &AcceptInlineCompletion,
 5288        cx: &mut ViewContext<Self>,
 5289    ) {
 5290        let Some(completion) = self.take_active_inline_completion(cx) else {
 5291            return;
 5292        };
 5293        if let Some(provider) = self.inline_completion_provider() {
 5294            provider.accept(cx);
 5295        }
 5296
 5297        cx.emit(EditorEvent::InputHandled {
 5298            utf16_range_to_replace: None,
 5299            text: completion.text.to_string().into(),
 5300        });
 5301
 5302        if let Some(range) = completion.delete_range {
 5303            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5304        }
 5305        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5306        self.refresh_inline_completion(true, true, cx);
 5307        cx.notify();
 5308    }
 5309
 5310    pub fn accept_partial_inline_completion(
 5311        &mut self,
 5312        _: &AcceptPartialInlineCompletion,
 5313        cx: &mut ViewContext<Self>,
 5314    ) {
 5315        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5316            if let Some(completion) = self.take_active_inline_completion(cx) {
 5317                let mut partial_completion = completion
 5318                    .text
 5319                    .chars()
 5320                    .by_ref()
 5321                    .take_while(|c| c.is_alphabetic())
 5322                    .collect::<String>();
 5323                if partial_completion.is_empty() {
 5324                    partial_completion = completion
 5325                        .text
 5326                        .chars()
 5327                        .by_ref()
 5328                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5329                        .collect::<String>();
 5330                }
 5331
 5332                cx.emit(EditorEvent::InputHandled {
 5333                    utf16_range_to_replace: None,
 5334                    text: partial_completion.clone().into(),
 5335                });
 5336
 5337                if let Some(range) = completion.delete_range {
 5338                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5339                }
 5340                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5341
 5342                self.refresh_inline_completion(true, true, cx);
 5343                cx.notify();
 5344            }
 5345        }
 5346    }
 5347
 5348    fn discard_inline_completion(
 5349        &mut self,
 5350        should_report_inline_completion_event: bool,
 5351        cx: &mut ViewContext<Self>,
 5352    ) -> bool {
 5353        if let Some(provider) = self.inline_completion_provider() {
 5354            provider.discard(should_report_inline_completion_event, cx);
 5355        }
 5356
 5357        self.take_active_inline_completion(cx).is_some()
 5358    }
 5359
 5360    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5361        if let Some(completion) = self.active_inline_completion.as_ref() {
 5362            let buffer = self.buffer.read(cx).read(cx);
 5363            completion.position.is_valid(&buffer)
 5364        } else {
 5365            false
 5366        }
 5367    }
 5368
 5369    fn take_active_inline_completion(
 5370        &mut self,
 5371        cx: &mut ViewContext<Self>,
 5372    ) -> Option<CompletionState> {
 5373        let completion = self.active_inline_completion.take()?;
 5374        let render_inlay_ids = completion.render_inlay_ids.clone();
 5375        self.display_map.update(cx, |map, cx| {
 5376            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5377        });
 5378        let buffer = self.buffer.read(cx).read(cx);
 5379
 5380        if completion.position.is_valid(&buffer) {
 5381            Some(completion)
 5382        } else {
 5383            None
 5384        }
 5385    }
 5386
 5387    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5388        let selection = self.selections.newest_anchor();
 5389        let cursor = selection.head();
 5390
 5391        let excerpt_id = cursor.excerpt_id;
 5392
 5393        if self.context_menu.read().is_none()
 5394            && self.completion_tasks.is_empty()
 5395            && selection.start == selection.end
 5396        {
 5397            if let Some(provider) = self.inline_completion_provider() {
 5398                if let Some((buffer, cursor_buffer_position)) =
 5399                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5400                {
 5401                    if let Some(proposal) =
 5402                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5403                    {
 5404                        let mut to_remove = Vec::new();
 5405                        if let Some(completion) = self.active_inline_completion.take() {
 5406                            to_remove.extend(completion.render_inlay_ids.iter());
 5407                        }
 5408
 5409                        let to_add = proposal
 5410                            .inlays
 5411                            .iter()
 5412                            .filter_map(|inlay| {
 5413                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5414                                let id = post_inc(&mut self.next_inlay_id);
 5415                                match inlay {
 5416                                    InlayProposal::Hint(position, hint) => {
 5417                                        let position =
 5418                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5419                                        Some(Inlay::hint(id, position, hint))
 5420                                    }
 5421                                    InlayProposal::Suggestion(position, text) => {
 5422                                        let position =
 5423                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5424                                        Some(Inlay::suggestion(id, position, text.clone()))
 5425                                    }
 5426                                }
 5427                            })
 5428                            .collect_vec();
 5429
 5430                        self.active_inline_completion = Some(CompletionState {
 5431                            position: cursor,
 5432                            text: proposal.text,
 5433                            delete_range: proposal.delete_range.and_then(|range| {
 5434                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5435                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5436                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5437                                Some(start?..end?)
 5438                            }),
 5439                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5440                        });
 5441
 5442                        self.display_map
 5443                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5444
 5445                        cx.notify();
 5446                        return;
 5447                    }
 5448                }
 5449            }
 5450        }
 5451
 5452        self.discard_inline_completion(false, cx);
 5453    }
 5454
 5455    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5456        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5457    }
 5458
 5459    fn render_code_actions_indicator(
 5460        &self,
 5461        _style: &EditorStyle,
 5462        row: DisplayRow,
 5463        is_active: bool,
 5464        cx: &mut ViewContext<Self>,
 5465    ) -> Option<IconButton> {
 5466        if self.available_code_actions.is_some() {
 5467            Some(
 5468                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5469                    .shape(ui::IconButtonShape::Square)
 5470                    .icon_size(IconSize::XSmall)
 5471                    .icon_color(Color::Muted)
 5472                    .selected(is_active)
 5473                    .tooltip({
 5474                        let focus_handle = self.focus_handle.clone();
 5475                        move |cx| {
 5476                            Tooltip::for_action_in(
 5477                                "Toggle Code Actions",
 5478                                &ToggleCodeActions {
 5479                                    deployed_from_indicator: None,
 5480                                },
 5481                                &focus_handle,
 5482                                cx,
 5483                            )
 5484                        }
 5485                    })
 5486                    .on_click(cx.listener(move |editor, _e, cx| {
 5487                        editor.focus(cx);
 5488                        editor.toggle_code_actions(
 5489                            &ToggleCodeActions {
 5490                                deployed_from_indicator: Some(row),
 5491                            },
 5492                            cx,
 5493                        );
 5494                    })),
 5495            )
 5496        } else {
 5497            None
 5498        }
 5499    }
 5500
 5501    fn clear_tasks(&mut self) {
 5502        self.tasks.clear()
 5503    }
 5504
 5505    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5506        if self.tasks.insert(key, value).is_some() {
 5507            // This case should hopefully be rare, but just in case...
 5508            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5509        }
 5510    }
 5511
 5512    fn build_tasks_context(
 5513        project: &Model<Project>,
 5514        buffer: &Model<Buffer>,
 5515        buffer_row: u32,
 5516        tasks: &Arc<RunnableTasks>,
 5517        cx: &mut ViewContext<Self>,
 5518    ) -> Task<Option<task::TaskContext>> {
 5519        let position = Point::new(buffer_row, tasks.column);
 5520        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5521        let location = Location {
 5522            buffer: buffer.clone(),
 5523            range: range_start..range_start,
 5524        };
 5525        // Fill in the environmental variables from the tree-sitter captures
 5526        let mut captured_task_variables = TaskVariables::default();
 5527        for (capture_name, value) in tasks.extra_variables.clone() {
 5528            captured_task_variables.insert(
 5529                task::VariableName::Custom(capture_name.into()),
 5530                value.clone(),
 5531            );
 5532        }
 5533        project.update(cx, |project, cx| {
 5534            project.task_store().update(cx, |task_store, cx| {
 5535                task_store.task_context_for_location(captured_task_variables, location, cx)
 5536            })
 5537        })
 5538    }
 5539
 5540    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5541        let Some((workspace, _)) = self.workspace.clone() else {
 5542            return;
 5543        };
 5544        let Some(project) = self.project.clone() else {
 5545            return;
 5546        };
 5547
 5548        // Try to find a closest, enclosing node using tree-sitter that has a
 5549        // task
 5550        let Some((buffer, buffer_row, tasks)) = self
 5551            .find_enclosing_node_task(cx)
 5552            // Or find the task that's closest in row-distance.
 5553            .or_else(|| self.find_closest_task(cx))
 5554        else {
 5555            return;
 5556        };
 5557
 5558        let reveal_strategy = action.reveal;
 5559        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5560        cx.spawn(|_, mut cx| async move {
 5561            let context = task_context.await?;
 5562            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5563
 5564            let resolved = resolved_task.resolved.as_mut()?;
 5565            resolved.reveal = reveal_strategy;
 5566
 5567            workspace
 5568                .update(&mut cx, |workspace, cx| {
 5569                    workspace::tasks::schedule_resolved_task(
 5570                        workspace,
 5571                        task_source_kind,
 5572                        resolved_task,
 5573                        false,
 5574                        cx,
 5575                    );
 5576                })
 5577                .ok()
 5578        })
 5579        .detach();
 5580    }
 5581
 5582    fn find_closest_task(
 5583        &mut self,
 5584        cx: &mut ViewContext<Self>,
 5585    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5586        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5587
 5588        let ((buffer_id, row), tasks) = self
 5589            .tasks
 5590            .iter()
 5591            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5592
 5593        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5594        let tasks = Arc::new(tasks.to_owned());
 5595        Some((buffer, *row, tasks))
 5596    }
 5597
 5598    fn find_enclosing_node_task(
 5599        &mut self,
 5600        cx: &mut ViewContext<Self>,
 5601    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5602        let snapshot = self.buffer.read(cx).snapshot(cx);
 5603        let offset = self.selections.newest::<usize>(cx).head();
 5604        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5605        let buffer_id = excerpt.buffer().remote_id();
 5606
 5607        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5608        let mut cursor = layer.node().walk();
 5609
 5610        while cursor.goto_first_child_for_byte(offset).is_some() {
 5611            if cursor.node().end_byte() == offset {
 5612                cursor.goto_next_sibling();
 5613            }
 5614        }
 5615
 5616        // Ascend to the smallest ancestor that contains the range and has a task.
 5617        loop {
 5618            let node = cursor.node();
 5619            let node_range = node.byte_range();
 5620            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5621
 5622            // Check if this node contains our offset
 5623            if node_range.start <= offset && node_range.end >= offset {
 5624                // If it contains offset, check for task
 5625                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5626                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5627                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5628                }
 5629            }
 5630
 5631            if !cursor.goto_parent() {
 5632                break;
 5633            }
 5634        }
 5635        None
 5636    }
 5637
 5638    fn render_run_indicator(
 5639        &self,
 5640        _style: &EditorStyle,
 5641        is_active: bool,
 5642        row: DisplayRow,
 5643        cx: &mut ViewContext<Self>,
 5644    ) -> IconButton {
 5645        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5646            .shape(ui::IconButtonShape::Square)
 5647            .icon_size(IconSize::XSmall)
 5648            .icon_color(Color::Muted)
 5649            .selected(is_active)
 5650            .on_click(cx.listener(move |editor, _e, cx| {
 5651                editor.focus(cx);
 5652                editor.toggle_code_actions(
 5653                    &ToggleCodeActions {
 5654                        deployed_from_indicator: Some(row),
 5655                    },
 5656                    cx,
 5657                );
 5658            }))
 5659    }
 5660
 5661    pub fn context_menu_visible(&self) -> bool {
 5662        self.context_menu
 5663            .read()
 5664            .as_ref()
 5665            .map_or(false, |menu| menu.visible())
 5666    }
 5667
 5668    fn render_context_menu(
 5669        &self,
 5670        cursor_position: DisplayPoint,
 5671        style: &EditorStyle,
 5672        max_height: Pixels,
 5673        cx: &mut ViewContext<Editor>,
 5674    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5675        self.context_menu.read().as_ref().map(|menu| {
 5676            menu.render(
 5677                cursor_position,
 5678                style,
 5679                max_height,
 5680                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5681                cx,
 5682            )
 5683        })
 5684    }
 5685
 5686    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5687        cx.notify();
 5688        self.completion_tasks.clear();
 5689        let context_menu = self.context_menu.write().take();
 5690        if context_menu.is_some() {
 5691            self.update_visible_inline_completion(cx);
 5692        }
 5693        context_menu
 5694    }
 5695
 5696    pub fn insert_snippet(
 5697        &mut self,
 5698        insertion_ranges: &[Range<usize>],
 5699        snippet: Snippet,
 5700        cx: &mut ViewContext<Self>,
 5701    ) -> Result<()> {
 5702        struct Tabstop<T> {
 5703            is_end_tabstop: bool,
 5704            ranges: Vec<Range<T>>,
 5705        }
 5706
 5707        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5708            let snippet_text: Arc<str> = snippet.text.clone().into();
 5709            buffer.edit(
 5710                insertion_ranges
 5711                    .iter()
 5712                    .cloned()
 5713                    .map(|range| (range, snippet_text.clone())),
 5714                Some(AutoindentMode::EachLine),
 5715                cx,
 5716            );
 5717
 5718            let snapshot = &*buffer.read(cx);
 5719            let snippet = &snippet;
 5720            snippet
 5721                .tabstops
 5722                .iter()
 5723                .map(|tabstop| {
 5724                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5725                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5726                    });
 5727                    let mut tabstop_ranges = tabstop
 5728                        .iter()
 5729                        .flat_map(|tabstop_range| {
 5730                            let mut delta = 0_isize;
 5731                            insertion_ranges.iter().map(move |insertion_range| {
 5732                                let insertion_start = insertion_range.start as isize + delta;
 5733                                delta +=
 5734                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5735
 5736                                let start = ((insertion_start + tabstop_range.start) as usize)
 5737                                    .min(snapshot.len());
 5738                                let end = ((insertion_start + tabstop_range.end) as usize)
 5739                                    .min(snapshot.len());
 5740                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5741                            })
 5742                        })
 5743                        .collect::<Vec<_>>();
 5744                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5745
 5746                    Tabstop {
 5747                        is_end_tabstop,
 5748                        ranges: tabstop_ranges,
 5749                    }
 5750                })
 5751                .collect::<Vec<_>>()
 5752        });
 5753        if let Some(tabstop) = tabstops.first() {
 5754            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5755                s.select_ranges(tabstop.ranges.iter().cloned());
 5756            });
 5757
 5758            // If we're already at the last tabstop and it's at the end of the snippet,
 5759            // we're done, we don't need to keep the state around.
 5760            if !tabstop.is_end_tabstop {
 5761                let ranges = tabstops
 5762                    .into_iter()
 5763                    .map(|tabstop| tabstop.ranges)
 5764                    .collect::<Vec<_>>();
 5765                self.snippet_stack.push(SnippetState {
 5766                    active_index: 0,
 5767                    ranges,
 5768                });
 5769            }
 5770
 5771            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5772            if self.autoclose_regions.is_empty() {
 5773                let snapshot = self.buffer.read(cx).snapshot(cx);
 5774                for selection in &mut self.selections.all::<Point>(cx) {
 5775                    let selection_head = selection.head();
 5776                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5777                        continue;
 5778                    };
 5779
 5780                    let mut bracket_pair = None;
 5781                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5782                    let prev_chars = snapshot
 5783                        .reversed_chars_at(selection_head)
 5784                        .collect::<String>();
 5785                    for (pair, enabled) in scope.brackets() {
 5786                        if enabled
 5787                            && pair.close
 5788                            && prev_chars.starts_with(pair.start.as_str())
 5789                            && next_chars.starts_with(pair.end.as_str())
 5790                        {
 5791                            bracket_pair = Some(pair.clone());
 5792                            break;
 5793                        }
 5794                    }
 5795                    if let Some(pair) = bracket_pair {
 5796                        let start = snapshot.anchor_after(selection_head);
 5797                        let end = snapshot.anchor_after(selection_head);
 5798                        self.autoclose_regions.push(AutocloseRegion {
 5799                            selection_id: selection.id,
 5800                            range: start..end,
 5801                            pair,
 5802                        });
 5803                    }
 5804                }
 5805            }
 5806        }
 5807        Ok(())
 5808    }
 5809
 5810    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5811        self.move_to_snippet_tabstop(Bias::Right, cx)
 5812    }
 5813
 5814    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5815        self.move_to_snippet_tabstop(Bias::Left, cx)
 5816    }
 5817
 5818    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5819        if let Some(mut snippet) = self.snippet_stack.pop() {
 5820            match bias {
 5821                Bias::Left => {
 5822                    if snippet.active_index > 0 {
 5823                        snippet.active_index -= 1;
 5824                    } else {
 5825                        self.snippet_stack.push(snippet);
 5826                        return false;
 5827                    }
 5828                }
 5829                Bias::Right => {
 5830                    if snippet.active_index + 1 < snippet.ranges.len() {
 5831                        snippet.active_index += 1;
 5832                    } else {
 5833                        self.snippet_stack.push(snippet);
 5834                        return false;
 5835                    }
 5836                }
 5837            }
 5838            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5839                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5840                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5841                });
 5842                // If snippet state is not at the last tabstop, push it back on the stack
 5843                if snippet.active_index + 1 < snippet.ranges.len() {
 5844                    self.snippet_stack.push(snippet);
 5845                }
 5846                return true;
 5847            }
 5848        }
 5849
 5850        false
 5851    }
 5852
 5853    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5854        self.transact(cx, |this, cx| {
 5855            this.select_all(&SelectAll, cx);
 5856            this.insert("", cx);
 5857        });
 5858    }
 5859
 5860    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5861        self.transact(cx, |this, cx| {
 5862            this.select_autoclose_pair(cx);
 5863            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5864            if !this.linked_edit_ranges.is_empty() {
 5865                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5866                let snapshot = this.buffer.read(cx).snapshot(cx);
 5867
 5868                for selection in selections.iter() {
 5869                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5870                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5871                    if selection_start.buffer_id != selection_end.buffer_id {
 5872                        continue;
 5873                    }
 5874                    if let Some(ranges) =
 5875                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5876                    {
 5877                        for (buffer, entries) in ranges {
 5878                            linked_ranges.entry(buffer).or_default().extend(entries);
 5879                        }
 5880                    }
 5881                }
 5882            }
 5883
 5884            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5885            if !this.selections.line_mode {
 5886                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5887                for selection in &mut selections {
 5888                    if selection.is_empty() {
 5889                        let old_head = selection.head();
 5890                        let mut new_head =
 5891                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5892                                .to_point(&display_map);
 5893                        if let Some((buffer, line_buffer_range)) = display_map
 5894                            .buffer_snapshot
 5895                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5896                        {
 5897                            let indent_size =
 5898                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5899                            let indent_len = match indent_size.kind {
 5900                                IndentKind::Space => {
 5901                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5902                                }
 5903                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5904                            };
 5905                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5906                                let indent_len = indent_len.get();
 5907                                new_head = cmp::min(
 5908                                    new_head,
 5909                                    MultiBufferPoint::new(
 5910                                        old_head.row,
 5911                                        ((old_head.column - 1) / indent_len) * indent_len,
 5912                                    ),
 5913                                );
 5914                            }
 5915                        }
 5916
 5917                        selection.set_head(new_head, SelectionGoal::None);
 5918                    }
 5919                }
 5920            }
 5921
 5922            this.signature_help_state.set_backspace_pressed(true);
 5923            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5924            this.insert("", cx);
 5925            let empty_str: Arc<str> = Arc::from("");
 5926            for (buffer, edits) in linked_ranges {
 5927                let snapshot = buffer.read(cx).snapshot();
 5928                use text::ToPoint as TP;
 5929
 5930                let edits = edits
 5931                    .into_iter()
 5932                    .map(|range| {
 5933                        let end_point = TP::to_point(&range.end, &snapshot);
 5934                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5935
 5936                        if end_point == start_point {
 5937                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5938                                .saturating_sub(1);
 5939                            start_point = TP::to_point(&offset, &snapshot);
 5940                        };
 5941
 5942                        (start_point..end_point, empty_str.clone())
 5943                    })
 5944                    .sorted_by_key(|(range, _)| range.start)
 5945                    .collect::<Vec<_>>();
 5946                buffer.update(cx, |this, cx| {
 5947                    this.edit(edits, None, cx);
 5948                })
 5949            }
 5950            this.refresh_inline_completion(true, false, cx);
 5951            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5952        });
 5953    }
 5954
 5955    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5956        self.transact(cx, |this, cx| {
 5957            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5958                let line_mode = s.line_mode;
 5959                s.move_with(|map, selection| {
 5960                    if selection.is_empty() && !line_mode {
 5961                        let cursor = movement::right(map, selection.head());
 5962                        selection.end = cursor;
 5963                        selection.reversed = true;
 5964                        selection.goal = SelectionGoal::None;
 5965                    }
 5966                })
 5967            });
 5968            this.insert("", cx);
 5969            this.refresh_inline_completion(true, false, cx);
 5970        });
 5971    }
 5972
 5973    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5974        if self.move_to_prev_snippet_tabstop(cx) {
 5975            return;
 5976        }
 5977
 5978        self.outdent(&Outdent, cx);
 5979    }
 5980
 5981    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5982        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5983            return;
 5984        }
 5985
 5986        let mut selections = self.selections.all_adjusted(cx);
 5987        let buffer = self.buffer.read(cx);
 5988        let snapshot = buffer.snapshot(cx);
 5989        let rows_iter = selections.iter().map(|s| s.head().row);
 5990        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5991
 5992        let mut edits = Vec::new();
 5993        let mut prev_edited_row = 0;
 5994        let mut row_delta = 0;
 5995        for selection in &mut selections {
 5996            if selection.start.row != prev_edited_row {
 5997                row_delta = 0;
 5998            }
 5999            prev_edited_row = selection.end.row;
 6000
 6001            // If the selection is non-empty, then increase the indentation of the selected lines.
 6002            if !selection.is_empty() {
 6003                row_delta =
 6004                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6005                continue;
 6006            }
 6007
 6008            // If the selection is empty and the cursor is in the leading whitespace before the
 6009            // suggested indentation, then auto-indent the line.
 6010            let cursor = selection.head();
 6011            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6012            if let Some(suggested_indent) =
 6013                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6014            {
 6015                if cursor.column < suggested_indent.len
 6016                    && cursor.column <= current_indent.len
 6017                    && current_indent.len <= suggested_indent.len
 6018                {
 6019                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6020                    selection.end = selection.start;
 6021                    if row_delta == 0 {
 6022                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6023                            cursor.row,
 6024                            current_indent,
 6025                            suggested_indent,
 6026                        ));
 6027                        row_delta = suggested_indent.len - current_indent.len;
 6028                    }
 6029                    continue;
 6030                }
 6031            }
 6032
 6033            // Otherwise, insert a hard or soft tab.
 6034            let settings = buffer.settings_at(cursor, cx);
 6035            let tab_size = if settings.hard_tabs {
 6036                IndentSize::tab()
 6037            } else {
 6038                let tab_size = settings.tab_size.get();
 6039                let char_column = snapshot
 6040                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6041                    .flat_map(str::chars)
 6042                    .count()
 6043                    + row_delta as usize;
 6044                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6045                IndentSize::spaces(chars_to_next_tab_stop)
 6046            };
 6047            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6048            selection.end = selection.start;
 6049            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6050            row_delta += tab_size.len;
 6051        }
 6052
 6053        self.transact(cx, |this, cx| {
 6054            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6055            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6056            this.refresh_inline_completion(true, false, cx);
 6057        });
 6058    }
 6059
 6060    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6061        if self.read_only(cx) {
 6062            return;
 6063        }
 6064        let mut selections = self.selections.all::<Point>(cx);
 6065        let mut prev_edited_row = 0;
 6066        let mut row_delta = 0;
 6067        let mut edits = Vec::new();
 6068        let buffer = self.buffer.read(cx);
 6069        let snapshot = buffer.snapshot(cx);
 6070        for selection in &mut selections {
 6071            if selection.start.row != prev_edited_row {
 6072                row_delta = 0;
 6073            }
 6074            prev_edited_row = selection.end.row;
 6075
 6076            row_delta =
 6077                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6078        }
 6079
 6080        self.transact(cx, |this, cx| {
 6081            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6082            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6083        });
 6084    }
 6085
 6086    fn indent_selection(
 6087        buffer: &MultiBuffer,
 6088        snapshot: &MultiBufferSnapshot,
 6089        selection: &mut Selection<Point>,
 6090        edits: &mut Vec<(Range<Point>, String)>,
 6091        delta_for_start_row: u32,
 6092        cx: &AppContext,
 6093    ) -> u32 {
 6094        let settings = buffer.settings_at(selection.start, cx);
 6095        let tab_size = settings.tab_size.get();
 6096        let indent_kind = if settings.hard_tabs {
 6097            IndentKind::Tab
 6098        } else {
 6099            IndentKind::Space
 6100        };
 6101        let mut start_row = selection.start.row;
 6102        let mut end_row = selection.end.row + 1;
 6103
 6104        // If a selection ends at the beginning of a line, don't indent
 6105        // that last line.
 6106        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6107            end_row -= 1;
 6108        }
 6109
 6110        // Avoid re-indenting a row that has already been indented by a
 6111        // previous selection, but still update this selection's column
 6112        // to reflect that indentation.
 6113        if delta_for_start_row > 0 {
 6114            start_row += 1;
 6115            selection.start.column += delta_for_start_row;
 6116            if selection.end.row == selection.start.row {
 6117                selection.end.column += delta_for_start_row;
 6118            }
 6119        }
 6120
 6121        let mut delta_for_end_row = 0;
 6122        let has_multiple_rows = start_row + 1 != end_row;
 6123        for row in start_row..end_row {
 6124            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6125            let indent_delta = match (current_indent.kind, indent_kind) {
 6126                (IndentKind::Space, IndentKind::Space) => {
 6127                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6128                    IndentSize::spaces(columns_to_next_tab_stop)
 6129                }
 6130                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6131                (_, IndentKind::Tab) => IndentSize::tab(),
 6132            };
 6133
 6134            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6135                0
 6136            } else {
 6137                selection.start.column
 6138            };
 6139            let row_start = Point::new(row, start);
 6140            edits.push((
 6141                row_start..row_start,
 6142                indent_delta.chars().collect::<String>(),
 6143            ));
 6144
 6145            // Update this selection's endpoints to reflect the indentation.
 6146            if row == selection.start.row {
 6147                selection.start.column += indent_delta.len;
 6148            }
 6149            if row == selection.end.row {
 6150                selection.end.column += indent_delta.len;
 6151                delta_for_end_row = indent_delta.len;
 6152            }
 6153        }
 6154
 6155        if selection.start.row == selection.end.row {
 6156            delta_for_start_row + delta_for_end_row
 6157        } else {
 6158            delta_for_end_row
 6159        }
 6160    }
 6161
 6162    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6163        if self.read_only(cx) {
 6164            return;
 6165        }
 6166        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6167        let selections = self.selections.all::<Point>(cx);
 6168        let mut deletion_ranges = Vec::new();
 6169        let mut last_outdent = None;
 6170        {
 6171            let buffer = self.buffer.read(cx);
 6172            let snapshot = buffer.snapshot(cx);
 6173            for selection in &selections {
 6174                let settings = buffer.settings_at(selection.start, cx);
 6175                let tab_size = settings.tab_size.get();
 6176                let mut rows = selection.spanned_rows(false, &display_map);
 6177
 6178                // Avoid re-outdenting a row that has already been outdented by a
 6179                // previous selection.
 6180                if let Some(last_row) = last_outdent {
 6181                    if last_row == rows.start {
 6182                        rows.start = rows.start.next_row();
 6183                    }
 6184                }
 6185                let has_multiple_rows = rows.len() > 1;
 6186                for row in rows.iter_rows() {
 6187                    let indent_size = snapshot.indent_size_for_line(row);
 6188                    if indent_size.len > 0 {
 6189                        let deletion_len = match indent_size.kind {
 6190                            IndentKind::Space => {
 6191                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6192                                if columns_to_prev_tab_stop == 0 {
 6193                                    tab_size
 6194                                } else {
 6195                                    columns_to_prev_tab_stop
 6196                                }
 6197                            }
 6198                            IndentKind::Tab => 1,
 6199                        };
 6200                        let start = if has_multiple_rows
 6201                            || deletion_len > selection.start.column
 6202                            || indent_size.len < selection.start.column
 6203                        {
 6204                            0
 6205                        } else {
 6206                            selection.start.column - deletion_len
 6207                        };
 6208                        deletion_ranges.push(
 6209                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6210                        );
 6211                        last_outdent = Some(row);
 6212                    }
 6213                }
 6214            }
 6215        }
 6216
 6217        self.transact(cx, |this, cx| {
 6218            this.buffer.update(cx, |buffer, cx| {
 6219                let empty_str: Arc<str> = Arc::default();
 6220                buffer.edit(
 6221                    deletion_ranges
 6222                        .into_iter()
 6223                        .map(|range| (range, empty_str.clone())),
 6224                    None,
 6225                    cx,
 6226                );
 6227            });
 6228            let selections = this.selections.all::<usize>(cx);
 6229            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6230        });
 6231    }
 6232
 6233    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6234        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6235        let selections = self.selections.all::<Point>(cx);
 6236
 6237        let mut new_cursors = Vec::new();
 6238        let mut edit_ranges = Vec::new();
 6239        let mut selections = selections.iter().peekable();
 6240        while let Some(selection) = selections.next() {
 6241            let mut rows = selection.spanned_rows(false, &display_map);
 6242            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6243
 6244            // Accumulate contiguous regions of rows that we want to delete.
 6245            while let Some(next_selection) = selections.peek() {
 6246                let next_rows = next_selection.spanned_rows(false, &display_map);
 6247                if next_rows.start <= rows.end {
 6248                    rows.end = next_rows.end;
 6249                    selections.next().unwrap();
 6250                } else {
 6251                    break;
 6252                }
 6253            }
 6254
 6255            let buffer = &display_map.buffer_snapshot;
 6256            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6257            let edit_end;
 6258            let cursor_buffer_row;
 6259            if buffer.max_point().row >= rows.end.0 {
 6260                // If there's a line after the range, delete the \n from the end of the row range
 6261                // and position the cursor on the next line.
 6262                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6263                cursor_buffer_row = rows.end;
 6264            } else {
 6265                // If there isn't a line after the range, delete the \n from the line before the
 6266                // start of the row range and position the cursor there.
 6267                edit_start = edit_start.saturating_sub(1);
 6268                edit_end = buffer.len();
 6269                cursor_buffer_row = rows.start.previous_row();
 6270            }
 6271
 6272            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6273            *cursor.column_mut() =
 6274                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6275
 6276            new_cursors.push((
 6277                selection.id,
 6278                buffer.anchor_after(cursor.to_point(&display_map)),
 6279            ));
 6280            edit_ranges.push(edit_start..edit_end);
 6281        }
 6282
 6283        self.transact(cx, |this, cx| {
 6284            let buffer = this.buffer.update(cx, |buffer, cx| {
 6285                let empty_str: Arc<str> = Arc::default();
 6286                buffer.edit(
 6287                    edit_ranges
 6288                        .into_iter()
 6289                        .map(|range| (range, empty_str.clone())),
 6290                    None,
 6291                    cx,
 6292                );
 6293                buffer.snapshot(cx)
 6294            });
 6295            let new_selections = new_cursors
 6296                .into_iter()
 6297                .map(|(id, cursor)| {
 6298                    let cursor = cursor.to_point(&buffer);
 6299                    Selection {
 6300                        id,
 6301                        start: cursor,
 6302                        end: cursor,
 6303                        reversed: false,
 6304                        goal: SelectionGoal::None,
 6305                    }
 6306                })
 6307                .collect();
 6308
 6309            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6310                s.select(new_selections);
 6311            });
 6312        });
 6313    }
 6314
 6315    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6316        if self.read_only(cx) {
 6317            return;
 6318        }
 6319        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6320        for selection in self.selections.all::<Point>(cx) {
 6321            let start = MultiBufferRow(selection.start.row);
 6322            // Treat single line selections as if they include the next line. Otherwise this action
 6323            // would do nothing for single line selections individual cursors.
 6324            let end = if selection.start.row == selection.end.row {
 6325                MultiBufferRow(selection.start.row + 1)
 6326            } else {
 6327                MultiBufferRow(selection.end.row)
 6328            };
 6329
 6330            if let Some(last_row_range) = row_ranges.last_mut() {
 6331                if start <= last_row_range.end {
 6332                    last_row_range.end = end;
 6333                    continue;
 6334                }
 6335            }
 6336            row_ranges.push(start..end);
 6337        }
 6338
 6339        let snapshot = self.buffer.read(cx).snapshot(cx);
 6340        let mut cursor_positions = Vec::new();
 6341        for row_range in &row_ranges {
 6342            let anchor = snapshot.anchor_before(Point::new(
 6343                row_range.end.previous_row().0,
 6344                snapshot.line_len(row_range.end.previous_row()),
 6345            ));
 6346            cursor_positions.push(anchor..anchor);
 6347        }
 6348
 6349        self.transact(cx, |this, cx| {
 6350            for row_range in row_ranges.into_iter().rev() {
 6351                for row in row_range.iter_rows().rev() {
 6352                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6353                    let next_line_row = row.next_row();
 6354                    let indent = snapshot.indent_size_for_line(next_line_row);
 6355                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6356
 6357                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6358                        " "
 6359                    } else {
 6360                        ""
 6361                    };
 6362
 6363                    this.buffer.update(cx, |buffer, cx| {
 6364                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6365                    });
 6366                }
 6367            }
 6368
 6369            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6370                s.select_anchor_ranges(cursor_positions)
 6371            });
 6372        });
 6373    }
 6374
 6375    pub fn sort_lines_case_sensitive(
 6376        &mut self,
 6377        _: &SortLinesCaseSensitive,
 6378        cx: &mut ViewContext<Self>,
 6379    ) {
 6380        self.manipulate_lines(cx, |lines| lines.sort())
 6381    }
 6382
 6383    pub fn sort_lines_case_insensitive(
 6384        &mut self,
 6385        _: &SortLinesCaseInsensitive,
 6386        cx: &mut ViewContext<Self>,
 6387    ) {
 6388        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6389    }
 6390
 6391    pub fn unique_lines_case_insensitive(
 6392        &mut self,
 6393        _: &UniqueLinesCaseInsensitive,
 6394        cx: &mut ViewContext<Self>,
 6395    ) {
 6396        self.manipulate_lines(cx, |lines| {
 6397            let mut seen = HashSet::default();
 6398            lines.retain(|line| seen.insert(line.to_lowercase()));
 6399        })
 6400    }
 6401
 6402    pub fn unique_lines_case_sensitive(
 6403        &mut self,
 6404        _: &UniqueLinesCaseSensitive,
 6405        cx: &mut ViewContext<Self>,
 6406    ) {
 6407        self.manipulate_lines(cx, |lines| {
 6408            let mut seen = HashSet::default();
 6409            lines.retain(|line| seen.insert(*line));
 6410        })
 6411    }
 6412
 6413    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6414        let mut revert_changes = HashMap::default();
 6415        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6416        for hunk in hunks_for_rows(
 6417            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6418            &multi_buffer_snapshot,
 6419        ) {
 6420            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6421        }
 6422        if !revert_changes.is_empty() {
 6423            self.transact(cx, |editor, cx| {
 6424                editor.revert(revert_changes, cx);
 6425            });
 6426        }
 6427    }
 6428
 6429    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6430        let Some(project) = self.project.clone() else {
 6431            return;
 6432        };
 6433        self.reload(project, cx).detach_and_notify_err(cx);
 6434    }
 6435
 6436    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6437        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6438        if !revert_changes.is_empty() {
 6439            self.transact(cx, |editor, cx| {
 6440                editor.revert(revert_changes, cx);
 6441            });
 6442        }
 6443    }
 6444
 6445    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6446        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6447            let project_path = buffer.read(cx).project_path(cx)?;
 6448            let project = self.project.as_ref()?.read(cx);
 6449            let entry = project.entry_for_path(&project_path, cx)?;
 6450            let parent = match &entry.canonical_path {
 6451                Some(canonical_path) => canonical_path.to_path_buf(),
 6452                None => project.absolute_path(&project_path, cx)?,
 6453            }
 6454            .parent()?
 6455            .to_path_buf();
 6456            Some(parent)
 6457        }) {
 6458            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6459        }
 6460    }
 6461
 6462    fn gather_revert_changes(
 6463        &mut self,
 6464        selections: &[Selection<Anchor>],
 6465        cx: &mut ViewContext<'_, Editor>,
 6466    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6467        let mut revert_changes = HashMap::default();
 6468        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6469        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6470            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6471        }
 6472        revert_changes
 6473    }
 6474
 6475    pub fn prepare_revert_change(
 6476        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6477        multi_buffer: &Model<MultiBuffer>,
 6478        hunk: &MultiBufferDiffHunk,
 6479        cx: &AppContext,
 6480    ) -> Option<()> {
 6481        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6482        let buffer = buffer.read(cx);
 6483        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6484        let buffer_snapshot = buffer.snapshot();
 6485        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6486        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6487            probe
 6488                .0
 6489                .start
 6490                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6491                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6492        }) {
 6493            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6494            Some(())
 6495        } else {
 6496            None
 6497        }
 6498    }
 6499
 6500    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6501        self.manipulate_lines(cx, |lines| lines.reverse())
 6502    }
 6503
 6504    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6505        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6506    }
 6507
 6508    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6509    where
 6510        Fn: FnMut(&mut Vec<&str>),
 6511    {
 6512        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6513        let buffer = self.buffer.read(cx).snapshot(cx);
 6514
 6515        let mut edits = Vec::new();
 6516
 6517        let selections = self.selections.all::<Point>(cx);
 6518        let mut selections = selections.iter().peekable();
 6519        let mut contiguous_row_selections = Vec::new();
 6520        let mut new_selections = Vec::new();
 6521        let mut added_lines = 0;
 6522        let mut removed_lines = 0;
 6523
 6524        while let Some(selection) = selections.next() {
 6525            let (start_row, end_row) = consume_contiguous_rows(
 6526                &mut contiguous_row_selections,
 6527                selection,
 6528                &display_map,
 6529                &mut selections,
 6530            );
 6531
 6532            let start_point = Point::new(start_row.0, 0);
 6533            let end_point = Point::new(
 6534                end_row.previous_row().0,
 6535                buffer.line_len(end_row.previous_row()),
 6536            );
 6537            let text = buffer
 6538                .text_for_range(start_point..end_point)
 6539                .collect::<String>();
 6540
 6541            let mut lines = text.split('\n').collect_vec();
 6542
 6543            let lines_before = lines.len();
 6544            callback(&mut lines);
 6545            let lines_after = lines.len();
 6546
 6547            edits.push((start_point..end_point, lines.join("\n")));
 6548
 6549            // Selections must change based on added and removed line count
 6550            let start_row =
 6551                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6552            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6553            new_selections.push(Selection {
 6554                id: selection.id,
 6555                start: start_row,
 6556                end: end_row,
 6557                goal: SelectionGoal::None,
 6558                reversed: selection.reversed,
 6559            });
 6560
 6561            if lines_after > lines_before {
 6562                added_lines += lines_after - lines_before;
 6563            } else if lines_before > lines_after {
 6564                removed_lines += lines_before - lines_after;
 6565            }
 6566        }
 6567
 6568        self.transact(cx, |this, cx| {
 6569            let buffer = this.buffer.update(cx, |buffer, cx| {
 6570                buffer.edit(edits, None, cx);
 6571                buffer.snapshot(cx)
 6572            });
 6573
 6574            // Recalculate offsets on newly edited buffer
 6575            let new_selections = new_selections
 6576                .iter()
 6577                .map(|s| {
 6578                    let start_point = Point::new(s.start.0, 0);
 6579                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6580                    Selection {
 6581                        id: s.id,
 6582                        start: buffer.point_to_offset(start_point),
 6583                        end: buffer.point_to_offset(end_point),
 6584                        goal: s.goal,
 6585                        reversed: s.reversed,
 6586                    }
 6587                })
 6588                .collect();
 6589
 6590            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6591                s.select(new_selections);
 6592            });
 6593
 6594            this.request_autoscroll(Autoscroll::fit(), cx);
 6595        });
 6596    }
 6597
 6598    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6599        self.manipulate_text(cx, |text| text.to_uppercase())
 6600    }
 6601
 6602    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6603        self.manipulate_text(cx, |text| text.to_lowercase())
 6604    }
 6605
 6606    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6607        self.manipulate_text(cx, |text| {
 6608            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6609            // https://github.com/rutrum/convert-case/issues/16
 6610            text.split('\n')
 6611                .map(|line| line.to_case(Case::Title))
 6612                .join("\n")
 6613        })
 6614    }
 6615
 6616    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6617        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6618    }
 6619
 6620    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6621        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6622    }
 6623
 6624    pub fn convert_to_upper_camel_case(
 6625        &mut self,
 6626        _: &ConvertToUpperCamelCase,
 6627        cx: &mut ViewContext<Self>,
 6628    ) {
 6629        self.manipulate_text(cx, |text| {
 6630            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6631            // https://github.com/rutrum/convert-case/issues/16
 6632            text.split('\n')
 6633                .map(|line| line.to_case(Case::UpperCamel))
 6634                .join("\n")
 6635        })
 6636    }
 6637
 6638    pub fn convert_to_lower_camel_case(
 6639        &mut self,
 6640        _: &ConvertToLowerCamelCase,
 6641        cx: &mut ViewContext<Self>,
 6642    ) {
 6643        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6644    }
 6645
 6646    pub fn convert_to_opposite_case(
 6647        &mut self,
 6648        _: &ConvertToOppositeCase,
 6649        cx: &mut ViewContext<Self>,
 6650    ) {
 6651        self.manipulate_text(cx, |text| {
 6652            text.chars()
 6653                .fold(String::with_capacity(text.len()), |mut t, c| {
 6654                    if c.is_uppercase() {
 6655                        t.extend(c.to_lowercase());
 6656                    } else {
 6657                        t.extend(c.to_uppercase());
 6658                    }
 6659                    t
 6660                })
 6661        })
 6662    }
 6663
 6664    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6665    where
 6666        Fn: FnMut(&str) -> String,
 6667    {
 6668        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6669        let buffer = self.buffer.read(cx).snapshot(cx);
 6670
 6671        let mut new_selections = Vec::new();
 6672        let mut edits = Vec::new();
 6673        let mut selection_adjustment = 0i32;
 6674
 6675        for selection in self.selections.all::<usize>(cx) {
 6676            let selection_is_empty = selection.is_empty();
 6677
 6678            let (start, end) = if selection_is_empty {
 6679                let word_range = movement::surrounding_word(
 6680                    &display_map,
 6681                    selection.start.to_display_point(&display_map),
 6682                );
 6683                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6684                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6685                (start, end)
 6686            } else {
 6687                (selection.start, selection.end)
 6688            };
 6689
 6690            let text = buffer.text_for_range(start..end).collect::<String>();
 6691            let old_length = text.len() as i32;
 6692            let text = callback(&text);
 6693
 6694            new_selections.push(Selection {
 6695                start: (start as i32 - selection_adjustment) as usize,
 6696                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6697                goal: SelectionGoal::None,
 6698                ..selection
 6699            });
 6700
 6701            selection_adjustment += old_length - text.len() as i32;
 6702
 6703            edits.push((start..end, text));
 6704        }
 6705
 6706        self.transact(cx, |this, cx| {
 6707            this.buffer.update(cx, |buffer, cx| {
 6708                buffer.edit(edits, None, cx);
 6709            });
 6710
 6711            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6712                s.select(new_selections);
 6713            });
 6714
 6715            this.request_autoscroll(Autoscroll::fit(), cx);
 6716        });
 6717    }
 6718
 6719    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6720        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6721        let buffer = &display_map.buffer_snapshot;
 6722        let selections = self.selections.all::<Point>(cx);
 6723
 6724        let mut edits = Vec::new();
 6725        let mut selections_iter = selections.iter().peekable();
 6726        while let Some(selection) = selections_iter.next() {
 6727            // Avoid duplicating the same lines twice.
 6728            let mut rows = selection.spanned_rows(false, &display_map);
 6729
 6730            while let Some(next_selection) = selections_iter.peek() {
 6731                let next_rows = next_selection.spanned_rows(false, &display_map);
 6732                if next_rows.start < rows.end {
 6733                    rows.end = next_rows.end;
 6734                    selections_iter.next().unwrap();
 6735                } else {
 6736                    break;
 6737                }
 6738            }
 6739
 6740            // Copy the text from the selected row region and splice it either at the start
 6741            // or end of the region.
 6742            let start = Point::new(rows.start.0, 0);
 6743            let end = Point::new(
 6744                rows.end.previous_row().0,
 6745                buffer.line_len(rows.end.previous_row()),
 6746            );
 6747            let text = buffer
 6748                .text_for_range(start..end)
 6749                .chain(Some("\n"))
 6750                .collect::<String>();
 6751            let insert_location = if upwards {
 6752                Point::new(rows.end.0, 0)
 6753            } else {
 6754                start
 6755            };
 6756            edits.push((insert_location..insert_location, text));
 6757        }
 6758
 6759        self.transact(cx, |this, cx| {
 6760            this.buffer.update(cx, |buffer, cx| {
 6761                buffer.edit(edits, None, cx);
 6762            });
 6763
 6764            this.request_autoscroll(Autoscroll::fit(), cx);
 6765        });
 6766    }
 6767
 6768    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6769        self.duplicate_line(true, cx);
 6770    }
 6771
 6772    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6773        self.duplicate_line(false, cx);
 6774    }
 6775
 6776    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6777        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6778        let buffer = self.buffer.read(cx).snapshot(cx);
 6779
 6780        let mut edits = Vec::new();
 6781        let mut unfold_ranges = Vec::new();
 6782        let mut refold_creases = Vec::new();
 6783
 6784        let selections = self.selections.all::<Point>(cx);
 6785        let mut selections = selections.iter().peekable();
 6786        let mut contiguous_row_selections = Vec::new();
 6787        let mut new_selections = Vec::new();
 6788
 6789        while let Some(selection) = selections.next() {
 6790            // Find all the selections that span a contiguous row range
 6791            let (start_row, end_row) = consume_contiguous_rows(
 6792                &mut contiguous_row_selections,
 6793                selection,
 6794                &display_map,
 6795                &mut selections,
 6796            );
 6797
 6798            // Move the text spanned by the row range to be before the line preceding the row range
 6799            if start_row.0 > 0 {
 6800                let range_to_move = Point::new(
 6801                    start_row.previous_row().0,
 6802                    buffer.line_len(start_row.previous_row()),
 6803                )
 6804                    ..Point::new(
 6805                        end_row.previous_row().0,
 6806                        buffer.line_len(end_row.previous_row()),
 6807                    );
 6808                let insertion_point = display_map
 6809                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6810                    .0;
 6811
 6812                // Don't move lines across excerpts
 6813                if buffer
 6814                    .excerpt_boundaries_in_range((
 6815                        Bound::Excluded(insertion_point),
 6816                        Bound::Included(range_to_move.end),
 6817                    ))
 6818                    .next()
 6819                    .is_none()
 6820                {
 6821                    let text = buffer
 6822                        .text_for_range(range_to_move.clone())
 6823                        .flat_map(|s| s.chars())
 6824                        .skip(1)
 6825                        .chain(['\n'])
 6826                        .collect::<String>();
 6827
 6828                    edits.push((
 6829                        buffer.anchor_after(range_to_move.start)
 6830                            ..buffer.anchor_before(range_to_move.end),
 6831                        String::new(),
 6832                    ));
 6833                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6834                    edits.push((insertion_anchor..insertion_anchor, text));
 6835
 6836                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6837
 6838                    // Move selections up
 6839                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6840                        |mut selection| {
 6841                            selection.start.row -= row_delta;
 6842                            selection.end.row -= row_delta;
 6843                            selection
 6844                        },
 6845                    ));
 6846
 6847                    // Move folds up
 6848                    unfold_ranges.push(range_to_move.clone());
 6849                    for fold in display_map.folds_in_range(
 6850                        buffer.anchor_before(range_to_move.start)
 6851                            ..buffer.anchor_after(range_to_move.end),
 6852                    ) {
 6853                        let mut start = fold.range.start.to_point(&buffer);
 6854                        let mut end = fold.range.end.to_point(&buffer);
 6855                        start.row -= row_delta;
 6856                        end.row -= row_delta;
 6857                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6858                    }
 6859                }
 6860            }
 6861
 6862            // If we didn't move line(s), preserve the existing selections
 6863            new_selections.append(&mut contiguous_row_selections);
 6864        }
 6865
 6866        self.transact(cx, |this, cx| {
 6867            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6868            this.buffer.update(cx, |buffer, cx| {
 6869                for (range, text) in edits {
 6870                    buffer.edit([(range, text)], None, cx);
 6871                }
 6872            });
 6873            this.fold_creases(refold_creases, true, cx);
 6874            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6875                s.select(new_selections);
 6876            })
 6877        });
 6878    }
 6879
 6880    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6881        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6882        let buffer = self.buffer.read(cx).snapshot(cx);
 6883
 6884        let mut edits = Vec::new();
 6885        let mut unfold_ranges = Vec::new();
 6886        let mut refold_creases = Vec::new();
 6887
 6888        let selections = self.selections.all::<Point>(cx);
 6889        let mut selections = selections.iter().peekable();
 6890        let mut contiguous_row_selections = Vec::new();
 6891        let mut new_selections = Vec::new();
 6892
 6893        while let Some(selection) = selections.next() {
 6894            // Find all the selections that span a contiguous row range
 6895            let (start_row, end_row) = consume_contiguous_rows(
 6896                &mut contiguous_row_selections,
 6897                selection,
 6898                &display_map,
 6899                &mut selections,
 6900            );
 6901
 6902            // Move the text spanned by the row range to be after the last line of the row range
 6903            if end_row.0 <= buffer.max_point().row {
 6904                let range_to_move =
 6905                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6906                let insertion_point = display_map
 6907                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6908                    .0;
 6909
 6910                // Don't move lines across excerpt boundaries
 6911                if buffer
 6912                    .excerpt_boundaries_in_range((
 6913                        Bound::Excluded(range_to_move.start),
 6914                        Bound::Included(insertion_point),
 6915                    ))
 6916                    .next()
 6917                    .is_none()
 6918                {
 6919                    let mut text = String::from("\n");
 6920                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6921                    text.pop(); // Drop trailing newline
 6922                    edits.push((
 6923                        buffer.anchor_after(range_to_move.start)
 6924                            ..buffer.anchor_before(range_to_move.end),
 6925                        String::new(),
 6926                    ));
 6927                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6928                    edits.push((insertion_anchor..insertion_anchor, text));
 6929
 6930                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6931
 6932                    // Move selections down
 6933                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6934                        |mut selection| {
 6935                            selection.start.row += row_delta;
 6936                            selection.end.row += row_delta;
 6937                            selection
 6938                        },
 6939                    ));
 6940
 6941                    // Move folds down
 6942                    unfold_ranges.push(range_to_move.clone());
 6943                    for fold in display_map.folds_in_range(
 6944                        buffer.anchor_before(range_to_move.start)
 6945                            ..buffer.anchor_after(range_to_move.end),
 6946                    ) {
 6947                        let mut start = fold.range.start.to_point(&buffer);
 6948                        let mut end = fold.range.end.to_point(&buffer);
 6949                        start.row += row_delta;
 6950                        end.row += row_delta;
 6951                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6952                    }
 6953                }
 6954            }
 6955
 6956            // If we didn't move line(s), preserve the existing selections
 6957            new_selections.append(&mut contiguous_row_selections);
 6958        }
 6959
 6960        self.transact(cx, |this, cx| {
 6961            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6962            this.buffer.update(cx, |buffer, cx| {
 6963                for (range, text) in edits {
 6964                    buffer.edit([(range, text)], None, cx);
 6965                }
 6966            });
 6967            this.fold_creases(refold_creases, true, cx);
 6968            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6969        });
 6970    }
 6971
 6972    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6973        let text_layout_details = &self.text_layout_details(cx);
 6974        self.transact(cx, |this, cx| {
 6975            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6976                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6977                let line_mode = s.line_mode;
 6978                s.move_with(|display_map, selection| {
 6979                    if !selection.is_empty() || line_mode {
 6980                        return;
 6981                    }
 6982
 6983                    let mut head = selection.head();
 6984                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6985                    if head.column() == display_map.line_len(head.row()) {
 6986                        transpose_offset = display_map
 6987                            .buffer_snapshot
 6988                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6989                    }
 6990
 6991                    if transpose_offset == 0 {
 6992                        return;
 6993                    }
 6994
 6995                    *head.column_mut() += 1;
 6996                    head = display_map.clip_point(head, Bias::Right);
 6997                    let goal = SelectionGoal::HorizontalPosition(
 6998                        display_map
 6999                            .x_for_display_point(head, text_layout_details)
 7000                            .into(),
 7001                    );
 7002                    selection.collapse_to(head, goal);
 7003
 7004                    let transpose_start = display_map
 7005                        .buffer_snapshot
 7006                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7007                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7008                        let transpose_end = display_map
 7009                            .buffer_snapshot
 7010                            .clip_offset(transpose_offset + 1, Bias::Right);
 7011                        if let Some(ch) =
 7012                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7013                        {
 7014                            edits.push((transpose_start..transpose_offset, String::new()));
 7015                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7016                        }
 7017                    }
 7018                });
 7019                edits
 7020            });
 7021            this.buffer
 7022                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7023            let selections = this.selections.all::<usize>(cx);
 7024            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7025                s.select(selections);
 7026            });
 7027        });
 7028    }
 7029
 7030    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7031        self.rewrap_impl(IsVimMode::No, cx)
 7032    }
 7033
 7034    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7035        let buffer = self.buffer.read(cx).snapshot(cx);
 7036        let selections = self.selections.all::<Point>(cx);
 7037        let mut selections = selections.iter().peekable();
 7038
 7039        let mut edits = Vec::new();
 7040        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7041
 7042        while let Some(selection) = selections.next() {
 7043            let mut start_row = selection.start.row;
 7044            let mut end_row = selection.end.row;
 7045
 7046            // Skip selections that overlap with a range that has already been rewrapped.
 7047            let selection_range = start_row..end_row;
 7048            if rewrapped_row_ranges
 7049                .iter()
 7050                .any(|range| range.overlaps(&selection_range))
 7051            {
 7052                continue;
 7053            }
 7054
 7055            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7056
 7057            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7058                match language_scope.language_name().0.as_ref() {
 7059                    "Markdown" | "Plain Text" => {
 7060                        should_rewrap = true;
 7061                    }
 7062                    _ => {}
 7063                }
 7064            }
 7065
 7066            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7067
 7068            // Since not all lines in the selection may be at the same indent
 7069            // level, choose the indent size that is the most common between all
 7070            // of the lines.
 7071            //
 7072            // If there is a tie, we use the deepest indent.
 7073            let (indent_size, indent_end) = {
 7074                let mut indent_size_occurrences = HashMap::default();
 7075                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7076
 7077                for row in start_row..=end_row {
 7078                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7079                    rows_by_indent_size.entry(indent).or_default().push(row);
 7080                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7081                }
 7082
 7083                let indent_size = indent_size_occurrences
 7084                    .into_iter()
 7085                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7086                    .map(|(indent, _)| indent)
 7087                    .unwrap_or_default();
 7088                let row = rows_by_indent_size[&indent_size][0];
 7089                let indent_end = Point::new(row, indent_size.len);
 7090
 7091                (indent_size, indent_end)
 7092            };
 7093
 7094            let mut line_prefix = indent_size.chars().collect::<String>();
 7095
 7096            if let Some(comment_prefix) =
 7097                buffer
 7098                    .language_scope_at(selection.head())
 7099                    .and_then(|language| {
 7100                        language
 7101                            .line_comment_prefixes()
 7102                            .iter()
 7103                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7104                            .cloned()
 7105                    })
 7106            {
 7107                line_prefix.push_str(&comment_prefix);
 7108                should_rewrap = true;
 7109            }
 7110
 7111            if !should_rewrap {
 7112                continue;
 7113            }
 7114
 7115            if selection.is_empty() {
 7116                'expand_upwards: while start_row > 0 {
 7117                    let prev_row = start_row - 1;
 7118                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7119                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7120                    {
 7121                        start_row = prev_row;
 7122                    } else {
 7123                        break 'expand_upwards;
 7124                    }
 7125                }
 7126
 7127                'expand_downwards: while end_row < buffer.max_point().row {
 7128                    let next_row = end_row + 1;
 7129                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7130                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7131                    {
 7132                        end_row = next_row;
 7133                    } else {
 7134                        break 'expand_downwards;
 7135                    }
 7136                }
 7137            }
 7138
 7139            let start = Point::new(start_row, 0);
 7140            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7141            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7142            let Some(lines_without_prefixes) = selection_text
 7143                .lines()
 7144                .map(|line| {
 7145                    line.strip_prefix(&line_prefix)
 7146                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7147                        .ok_or_else(|| {
 7148                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7149                        })
 7150                })
 7151                .collect::<Result<Vec<_>, _>>()
 7152                .log_err()
 7153            else {
 7154                continue;
 7155            };
 7156
 7157            let wrap_column = buffer
 7158                .settings_at(Point::new(start_row, 0), cx)
 7159                .preferred_line_length as usize;
 7160            let wrapped_text = wrap_with_prefix(
 7161                line_prefix,
 7162                lines_without_prefixes.join(" "),
 7163                wrap_column,
 7164                tab_size,
 7165            );
 7166
 7167            // TODO: should always use char-based diff while still supporting cursor behavior that
 7168            // matches vim.
 7169            let diff = match is_vim_mode {
 7170                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7171                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7172            };
 7173            let mut offset = start.to_offset(&buffer);
 7174            let mut moved_since_edit = true;
 7175
 7176            for change in diff.iter_all_changes() {
 7177                let value = change.value();
 7178                match change.tag() {
 7179                    ChangeTag::Equal => {
 7180                        offset += value.len();
 7181                        moved_since_edit = true;
 7182                    }
 7183                    ChangeTag::Delete => {
 7184                        let start = buffer.anchor_after(offset);
 7185                        let end = buffer.anchor_before(offset + value.len());
 7186
 7187                        if moved_since_edit {
 7188                            edits.push((start..end, String::new()));
 7189                        } else {
 7190                            edits.last_mut().unwrap().0.end = end;
 7191                        }
 7192
 7193                        offset += value.len();
 7194                        moved_since_edit = false;
 7195                    }
 7196                    ChangeTag::Insert => {
 7197                        if moved_since_edit {
 7198                            let anchor = buffer.anchor_after(offset);
 7199                            edits.push((anchor..anchor, value.to_string()));
 7200                        } else {
 7201                            edits.last_mut().unwrap().1.push_str(value);
 7202                        }
 7203
 7204                        moved_since_edit = false;
 7205                    }
 7206                }
 7207            }
 7208
 7209            rewrapped_row_ranges.push(start_row..=end_row);
 7210        }
 7211
 7212        self.buffer
 7213            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7214    }
 7215
 7216    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7217        let mut text = String::new();
 7218        let buffer = self.buffer.read(cx).snapshot(cx);
 7219        let mut selections = self.selections.all::<Point>(cx);
 7220        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7221        {
 7222            let max_point = buffer.max_point();
 7223            let mut is_first = true;
 7224            for selection in &mut selections {
 7225                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7226                if is_entire_line {
 7227                    selection.start = Point::new(selection.start.row, 0);
 7228                    if !selection.is_empty() && selection.end.column == 0 {
 7229                        selection.end = cmp::min(max_point, selection.end);
 7230                    } else {
 7231                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7232                    }
 7233                    selection.goal = SelectionGoal::None;
 7234                }
 7235                if is_first {
 7236                    is_first = false;
 7237                } else {
 7238                    text += "\n";
 7239                }
 7240                let mut len = 0;
 7241                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7242                    text.push_str(chunk);
 7243                    len += chunk.len();
 7244                }
 7245                clipboard_selections.push(ClipboardSelection {
 7246                    len,
 7247                    is_entire_line,
 7248                    first_line_indent: buffer
 7249                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7250                        .len,
 7251                });
 7252            }
 7253        }
 7254
 7255        self.transact(cx, |this, cx| {
 7256            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7257                s.select(selections);
 7258            });
 7259            this.insert("", cx);
 7260            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7261                text,
 7262                clipboard_selections,
 7263            ));
 7264        });
 7265    }
 7266
 7267    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7268        let selections = self.selections.all::<Point>(cx);
 7269        let buffer = self.buffer.read(cx).read(cx);
 7270        let mut text = String::new();
 7271
 7272        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7273        {
 7274            let max_point = buffer.max_point();
 7275            let mut is_first = true;
 7276            for selection in selections.iter() {
 7277                let mut start = selection.start;
 7278                let mut end = selection.end;
 7279                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7280                if is_entire_line {
 7281                    start = Point::new(start.row, 0);
 7282                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7283                }
 7284                if is_first {
 7285                    is_first = false;
 7286                } else {
 7287                    text += "\n";
 7288                }
 7289                let mut len = 0;
 7290                for chunk in buffer.text_for_range(start..end) {
 7291                    text.push_str(chunk);
 7292                    len += chunk.len();
 7293                }
 7294                clipboard_selections.push(ClipboardSelection {
 7295                    len,
 7296                    is_entire_line,
 7297                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7298                });
 7299            }
 7300        }
 7301
 7302        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7303            text,
 7304            clipboard_selections,
 7305        ));
 7306    }
 7307
 7308    pub fn do_paste(
 7309        &mut self,
 7310        text: &String,
 7311        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7312        handle_entire_lines: bool,
 7313        cx: &mut ViewContext<Self>,
 7314    ) {
 7315        if self.read_only(cx) {
 7316            return;
 7317        }
 7318
 7319        let clipboard_text = Cow::Borrowed(text);
 7320
 7321        self.transact(cx, |this, cx| {
 7322            if let Some(mut clipboard_selections) = clipboard_selections {
 7323                let old_selections = this.selections.all::<usize>(cx);
 7324                let all_selections_were_entire_line =
 7325                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7326                let first_selection_indent_column =
 7327                    clipboard_selections.first().map(|s| s.first_line_indent);
 7328                if clipboard_selections.len() != old_selections.len() {
 7329                    clipboard_selections.drain(..);
 7330                }
 7331                let cursor_offset = this.selections.last::<usize>(cx).head();
 7332                let mut auto_indent_on_paste = true;
 7333
 7334                this.buffer.update(cx, |buffer, cx| {
 7335                    let snapshot = buffer.read(cx);
 7336                    auto_indent_on_paste =
 7337                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7338
 7339                    let mut start_offset = 0;
 7340                    let mut edits = Vec::new();
 7341                    let mut original_indent_columns = Vec::new();
 7342                    for (ix, selection) in old_selections.iter().enumerate() {
 7343                        let to_insert;
 7344                        let entire_line;
 7345                        let original_indent_column;
 7346                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7347                            let end_offset = start_offset + clipboard_selection.len;
 7348                            to_insert = &clipboard_text[start_offset..end_offset];
 7349                            entire_line = clipboard_selection.is_entire_line;
 7350                            start_offset = end_offset + 1;
 7351                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7352                        } else {
 7353                            to_insert = clipboard_text.as_str();
 7354                            entire_line = all_selections_were_entire_line;
 7355                            original_indent_column = first_selection_indent_column
 7356                        }
 7357
 7358                        // If the corresponding selection was empty when this slice of the
 7359                        // clipboard text was written, then the entire line containing the
 7360                        // selection was copied. If this selection is also currently empty,
 7361                        // then paste the line before the current line of the buffer.
 7362                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7363                            let column = selection.start.to_point(&snapshot).column as usize;
 7364                            let line_start = selection.start - column;
 7365                            line_start..line_start
 7366                        } else {
 7367                            selection.range()
 7368                        };
 7369
 7370                        edits.push((range, to_insert));
 7371                        original_indent_columns.extend(original_indent_column);
 7372                    }
 7373                    drop(snapshot);
 7374
 7375                    buffer.edit(
 7376                        edits,
 7377                        if auto_indent_on_paste {
 7378                            Some(AutoindentMode::Block {
 7379                                original_indent_columns,
 7380                            })
 7381                        } else {
 7382                            None
 7383                        },
 7384                        cx,
 7385                    );
 7386                });
 7387
 7388                let selections = this.selections.all::<usize>(cx);
 7389                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7390            } else {
 7391                this.insert(&clipboard_text, cx);
 7392            }
 7393        });
 7394    }
 7395
 7396    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7397        if let Some(item) = cx.read_from_clipboard() {
 7398            let entries = item.entries();
 7399
 7400            match entries.first() {
 7401                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7402                // of all the pasted entries.
 7403                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7404                    .do_paste(
 7405                        clipboard_string.text(),
 7406                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7407                        true,
 7408                        cx,
 7409                    ),
 7410                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7411            }
 7412        }
 7413    }
 7414
 7415    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7416        if self.read_only(cx) {
 7417            return;
 7418        }
 7419
 7420        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7421            if let Some((selections, _)) =
 7422                self.selection_history.transaction(transaction_id).cloned()
 7423            {
 7424                self.change_selections(None, cx, |s| {
 7425                    s.select_anchors(selections.to_vec());
 7426                });
 7427            }
 7428            self.request_autoscroll(Autoscroll::fit(), cx);
 7429            self.unmark_text(cx);
 7430            self.refresh_inline_completion(true, false, cx);
 7431            cx.emit(EditorEvent::Edited { transaction_id });
 7432            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7433        }
 7434    }
 7435
 7436    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7437        if self.read_only(cx) {
 7438            return;
 7439        }
 7440
 7441        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7442            if let Some((_, Some(selections))) =
 7443                self.selection_history.transaction(transaction_id).cloned()
 7444            {
 7445                self.change_selections(None, cx, |s| {
 7446                    s.select_anchors(selections.to_vec());
 7447                });
 7448            }
 7449            self.request_autoscroll(Autoscroll::fit(), cx);
 7450            self.unmark_text(cx);
 7451            self.refresh_inline_completion(true, false, cx);
 7452            cx.emit(EditorEvent::Edited { transaction_id });
 7453        }
 7454    }
 7455
 7456    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7457        self.buffer
 7458            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7459    }
 7460
 7461    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7462        self.buffer
 7463            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7464    }
 7465
 7466    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7467        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7468            let line_mode = s.line_mode;
 7469            s.move_with(|map, selection| {
 7470                let cursor = if selection.is_empty() && !line_mode {
 7471                    movement::left(map, selection.start)
 7472                } else {
 7473                    selection.start
 7474                };
 7475                selection.collapse_to(cursor, SelectionGoal::None);
 7476            });
 7477        })
 7478    }
 7479
 7480    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7481        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7482            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7483        })
 7484    }
 7485
 7486    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7487        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7488            let line_mode = s.line_mode;
 7489            s.move_with(|map, selection| {
 7490                let cursor = if selection.is_empty() && !line_mode {
 7491                    movement::right(map, selection.end)
 7492                } else {
 7493                    selection.end
 7494                };
 7495                selection.collapse_to(cursor, SelectionGoal::None)
 7496            });
 7497        })
 7498    }
 7499
 7500    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7501        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7502            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7503        })
 7504    }
 7505
 7506    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7507        if self.take_rename(true, cx).is_some() {
 7508            return;
 7509        }
 7510
 7511        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7512            cx.propagate();
 7513            return;
 7514        }
 7515
 7516        let text_layout_details = &self.text_layout_details(cx);
 7517        let selection_count = self.selections.count();
 7518        let first_selection = self.selections.first_anchor();
 7519
 7520        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7521            let line_mode = s.line_mode;
 7522            s.move_with(|map, selection| {
 7523                if !selection.is_empty() && !line_mode {
 7524                    selection.goal = SelectionGoal::None;
 7525                }
 7526                let (cursor, goal) = movement::up(
 7527                    map,
 7528                    selection.start,
 7529                    selection.goal,
 7530                    false,
 7531                    text_layout_details,
 7532                );
 7533                selection.collapse_to(cursor, goal);
 7534            });
 7535        });
 7536
 7537        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7538        {
 7539            cx.propagate();
 7540        }
 7541    }
 7542
 7543    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7544        if self.take_rename(true, cx).is_some() {
 7545            return;
 7546        }
 7547
 7548        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7549            cx.propagate();
 7550            return;
 7551        }
 7552
 7553        let text_layout_details = &self.text_layout_details(cx);
 7554
 7555        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7556            let line_mode = s.line_mode;
 7557            s.move_with(|map, selection| {
 7558                if !selection.is_empty() && !line_mode {
 7559                    selection.goal = SelectionGoal::None;
 7560                }
 7561                let (cursor, goal) = movement::up_by_rows(
 7562                    map,
 7563                    selection.start,
 7564                    action.lines,
 7565                    selection.goal,
 7566                    false,
 7567                    text_layout_details,
 7568                );
 7569                selection.collapse_to(cursor, goal);
 7570            });
 7571        })
 7572    }
 7573
 7574    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7575        if self.take_rename(true, cx).is_some() {
 7576            return;
 7577        }
 7578
 7579        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7580            cx.propagate();
 7581            return;
 7582        }
 7583
 7584        let text_layout_details = &self.text_layout_details(cx);
 7585
 7586        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7587            let line_mode = s.line_mode;
 7588            s.move_with(|map, selection| {
 7589                if !selection.is_empty() && !line_mode {
 7590                    selection.goal = SelectionGoal::None;
 7591                }
 7592                let (cursor, goal) = movement::down_by_rows(
 7593                    map,
 7594                    selection.start,
 7595                    action.lines,
 7596                    selection.goal,
 7597                    false,
 7598                    text_layout_details,
 7599                );
 7600                selection.collapse_to(cursor, goal);
 7601            });
 7602        })
 7603    }
 7604
 7605    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7606        let text_layout_details = &self.text_layout_details(cx);
 7607        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7608            s.move_heads_with(|map, head, goal| {
 7609                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7610            })
 7611        })
 7612    }
 7613
 7614    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7615        let text_layout_details = &self.text_layout_details(cx);
 7616        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7617            s.move_heads_with(|map, head, goal| {
 7618                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7619            })
 7620        })
 7621    }
 7622
 7623    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7624        let Some(row_count) = self.visible_row_count() else {
 7625            return;
 7626        };
 7627
 7628        let text_layout_details = &self.text_layout_details(cx);
 7629
 7630        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7631            s.move_heads_with(|map, head, goal| {
 7632                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7633            })
 7634        })
 7635    }
 7636
 7637    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7638        if self.take_rename(true, cx).is_some() {
 7639            return;
 7640        }
 7641
 7642        if self
 7643            .context_menu
 7644            .write()
 7645            .as_mut()
 7646            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7647            .unwrap_or(false)
 7648        {
 7649            return;
 7650        }
 7651
 7652        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7653            cx.propagate();
 7654            return;
 7655        }
 7656
 7657        let Some(row_count) = self.visible_row_count() else {
 7658            return;
 7659        };
 7660
 7661        let autoscroll = if action.center_cursor {
 7662            Autoscroll::center()
 7663        } else {
 7664            Autoscroll::fit()
 7665        };
 7666
 7667        let text_layout_details = &self.text_layout_details(cx);
 7668
 7669        self.change_selections(Some(autoscroll), cx, |s| {
 7670            let line_mode = s.line_mode;
 7671            s.move_with(|map, selection| {
 7672                if !selection.is_empty() && !line_mode {
 7673                    selection.goal = SelectionGoal::None;
 7674                }
 7675                let (cursor, goal) = movement::up_by_rows(
 7676                    map,
 7677                    selection.end,
 7678                    row_count,
 7679                    selection.goal,
 7680                    false,
 7681                    text_layout_details,
 7682                );
 7683                selection.collapse_to(cursor, goal);
 7684            });
 7685        });
 7686    }
 7687
 7688    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7689        let text_layout_details = &self.text_layout_details(cx);
 7690        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7691            s.move_heads_with(|map, head, goal| {
 7692                movement::up(map, head, goal, false, text_layout_details)
 7693            })
 7694        })
 7695    }
 7696
 7697    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7698        self.take_rename(true, cx);
 7699
 7700        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7701            cx.propagate();
 7702            return;
 7703        }
 7704
 7705        let text_layout_details = &self.text_layout_details(cx);
 7706        let selection_count = self.selections.count();
 7707        let first_selection = self.selections.first_anchor();
 7708
 7709        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7710            let line_mode = s.line_mode;
 7711            s.move_with(|map, selection| {
 7712                if !selection.is_empty() && !line_mode {
 7713                    selection.goal = SelectionGoal::None;
 7714                }
 7715                let (cursor, goal) = movement::down(
 7716                    map,
 7717                    selection.end,
 7718                    selection.goal,
 7719                    false,
 7720                    text_layout_details,
 7721                );
 7722                selection.collapse_to(cursor, goal);
 7723            });
 7724        });
 7725
 7726        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7727        {
 7728            cx.propagate();
 7729        }
 7730    }
 7731
 7732    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7733        let Some(row_count) = self.visible_row_count() else {
 7734            return;
 7735        };
 7736
 7737        let text_layout_details = &self.text_layout_details(cx);
 7738
 7739        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7740            s.move_heads_with(|map, head, goal| {
 7741                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7742            })
 7743        })
 7744    }
 7745
 7746    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7747        if self.take_rename(true, cx).is_some() {
 7748            return;
 7749        }
 7750
 7751        if self
 7752            .context_menu
 7753            .write()
 7754            .as_mut()
 7755            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7756            .unwrap_or(false)
 7757        {
 7758            return;
 7759        }
 7760
 7761        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7762            cx.propagate();
 7763            return;
 7764        }
 7765
 7766        let Some(row_count) = self.visible_row_count() else {
 7767            return;
 7768        };
 7769
 7770        let autoscroll = if action.center_cursor {
 7771            Autoscroll::center()
 7772        } else {
 7773            Autoscroll::fit()
 7774        };
 7775
 7776        let text_layout_details = &self.text_layout_details(cx);
 7777        self.change_selections(Some(autoscroll), cx, |s| {
 7778            let line_mode = s.line_mode;
 7779            s.move_with(|map, selection| {
 7780                if !selection.is_empty() && !line_mode {
 7781                    selection.goal = SelectionGoal::None;
 7782                }
 7783                let (cursor, goal) = movement::down_by_rows(
 7784                    map,
 7785                    selection.end,
 7786                    row_count,
 7787                    selection.goal,
 7788                    false,
 7789                    text_layout_details,
 7790                );
 7791                selection.collapse_to(cursor, goal);
 7792            });
 7793        });
 7794    }
 7795
 7796    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7797        let text_layout_details = &self.text_layout_details(cx);
 7798        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7799            s.move_heads_with(|map, head, goal| {
 7800                movement::down(map, head, goal, false, text_layout_details)
 7801            })
 7802        });
 7803    }
 7804
 7805    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7806        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7807            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7808        }
 7809    }
 7810
 7811    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7812        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7813            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7814        }
 7815    }
 7816
 7817    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7818        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7819            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7820        }
 7821    }
 7822
 7823    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7824        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7825            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7826        }
 7827    }
 7828
 7829    pub fn move_to_previous_word_start(
 7830        &mut self,
 7831        _: &MoveToPreviousWordStart,
 7832        cx: &mut ViewContext<Self>,
 7833    ) {
 7834        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7835            s.move_cursors_with(|map, head, _| {
 7836                (
 7837                    movement::previous_word_start(map, head),
 7838                    SelectionGoal::None,
 7839                )
 7840            });
 7841        })
 7842    }
 7843
 7844    pub fn move_to_previous_subword_start(
 7845        &mut self,
 7846        _: &MoveToPreviousSubwordStart,
 7847        cx: &mut ViewContext<Self>,
 7848    ) {
 7849        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7850            s.move_cursors_with(|map, head, _| {
 7851                (
 7852                    movement::previous_subword_start(map, head),
 7853                    SelectionGoal::None,
 7854                )
 7855            });
 7856        })
 7857    }
 7858
 7859    pub fn select_to_previous_word_start(
 7860        &mut self,
 7861        _: &SelectToPreviousWordStart,
 7862        cx: &mut ViewContext<Self>,
 7863    ) {
 7864        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7865            s.move_heads_with(|map, head, _| {
 7866                (
 7867                    movement::previous_word_start(map, head),
 7868                    SelectionGoal::None,
 7869                )
 7870            });
 7871        })
 7872    }
 7873
 7874    pub fn select_to_previous_subword_start(
 7875        &mut self,
 7876        _: &SelectToPreviousSubwordStart,
 7877        cx: &mut ViewContext<Self>,
 7878    ) {
 7879        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7880            s.move_heads_with(|map, head, _| {
 7881                (
 7882                    movement::previous_subword_start(map, head),
 7883                    SelectionGoal::None,
 7884                )
 7885            });
 7886        })
 7887    }
 7888
 7889    pub fn delete_to_previous_word_start(
 7890        &mut self,
 7891        action: &DeleteToPreviousWordStart,
 7892        cx: &mut ViewContext<Self>,
 7893    ) {
 7894        self.transact(cx, |this, cx| {
 7895            this.select_autoclose_pair(cx);
 7896            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7897                let line_mode = s.line_mode;
 7898                s.move_with(|map, selection| {
 7899                    if selection.is_empty() && !line_mode {
 7900                        let cursor = if action.ignore_newlines {
 7901                            movement::previous_word_start(map, selection.head())
 7902                        } else {
 7903                            movement::previous_word_start_or_newline(map, selection.head())
 7904                        };
 7905                        selection.set_head(cursor, SelectionGoal::None);
 7906                    }
 7907                });
 7908            });
 7909            this.insert("", cx);
 7910        });
 7911    }
 7912
 7913    pub fn delete_to_previous_subword_start(
 7914        &mut self,
 7915        _: &DeleteToPreviousSubwordStart,
 7916        cx: &mut ViewContext<Self>,
 7917    ) {
 7918        self.transact(cx, |this, cx| {
 7919            this.select_autoclose_pair(cx);
 7920            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7921                let line_mode = s.line_mode;
 7922                s.move_with(|map, selection| {
 7923                    if selection.is_empty() && !line_mode {
 7924                        let cursor = movement::previous_subword_start(map, selection.head());
 7925                        selection.set_head(cursor, SelectionGoal::None);
 7926                    }
 7927                });
 7928            });
 7929            this.insert("", cx);
 7930        });
 7931    }
 7932
 7933    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7934        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7935            s.move_cursors_with(|map, head, _| {
 7936                (movement::next_word_end(map, head), SelectionGoal::None)
 7937            });
 7938        })
 7939    }
 7940
 7941    pub fn move_to_next_subword_end(
 7942        &mut self,
 7943        _: &MoveToNextSubwordEnd,
 7944        cx: &mut ViewContext<Self>,
 7945    ) {
 7946        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7947            s.move_cursors_with(|map, head, _| {
 7948                (movement::next_subword_end(map, head), SelectionGoal::None)
 7949            });
 7950        })
 7951    }
 7952
 7953    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7954        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7955            s.move_heads_with(|map, head, _| {
 7956                (movement::next_word_end(map, head), SelectionGoal::None)
 7957            });
 7958        })
 7959    }
 7960
 7961    pub fn select_to_next_subword_end(
 7962        &mut self,
 7963        _: &SelectToNextSubwordEnd,
 7964        cx: &mut ViewContext<Self>,
 7965    ) {
 7966        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7967            s.move_heads_with(|map, head, _| {
 7968                (movement::next_subword_end(map, head), SelectionGoal::None)
 7969            });
 7970        })
 7971    }
 7972
 7973    pub fn delete_to_next_word_end(
 7974        &mut self,
 7975        action: &DeleteToNextWordEnd,
 7976        cx: &mut ViewContext<Self>,
 7977    ) {
 7978        self.transact(cx, |this, cx| {
 7979            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7980                let line_mode = s.line_mode;
 7981                s.move_with(|map, selection| {
 7982                    if selection.is_empty() && !line_mode {
 7983                        let cursor = if action.ignore_newlines {
 7984                            movement::next_word_end(map, selection.head())
 7985                        } else {
 7986                            movement::next_word_end_or_newline(map, selection.head())
 7987                        };
 7988                        selection.set_head(cursor, SelectionGoal::None);
 7989                    }
 7990                });
 7991            });
 7992            this.insert("", cx);
 7993        });
 7994    }
 7995
 7996    pub fn delete_to_next_subword_end(
 7997        &mut self,
 7998        _: &DeleteToNextSubwordEnd,
 7999        cx: &mut ViewContext<Self>,
 8000    ) {
 8001        self.transact(cx, |this, cx| {
 8002            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8003                s.move_with(|map, selection| {
 8004                    if selection.is_empty() {
 8005                        let cursor = movement::next_subword_end(map, selection.head());
 8006                        selection.set_head(cursor, SelectionGoal::None);
 8007                    }
 8008                });
 8009            });
 8010            this.insert("", cx);
 8011        });
 8012    }
 8013
 8014    pub fn move_to_beginning_of_line(
 8015        &mut self,
 8016        action: &MoveToBeginningOfLine,
 8017        cx: &mut ViewContext<Self>,
 8018    ) {
 8019        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8020            s.move_cursors_with(|map, head, _| {
 8021                (
 8022                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8023                    SelectionGoal::None,
 8024                )
 8025            });
 8026        })
 8027    }
 8028
 8029    pub fn select_to_beginning_of_line(
 8030        &mut self,
 8031        action: &SelectToBeginningOfLine,
 8032        cx: &mut ViewContext<Self>,
 8033    ) {
 8034        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8035            s.move_heads_with(|map, head, _| {
 8036                (
 8037                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8038                    SelectionGoal::None,
 8039                )
 8040            });
 8041        });
 8042    }
 8043
 8044    pub fn delete_to_beginning_of_line(
 8045        &mut self,
 8046        _: &DeleteToBeginningOfLine,
 8047        cx: &mut ViewContext<Self>,
 8048    ) {
 8049        self.transact(cx, |this, cx| {
 8050            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8051                s.move_with(|_, selection| {
 8052                    selection.reversed = true;
 8053                });
 8054            });
 8055
 8056            this.select_to_beginning_of_line(
 8057                &SelectToBeginningOfLine {
 8058                    stop_at_soft_wraps: false,
 8059                },
 8060                cx,
 8061            );
 8062            this.backspace(&Backspace, cx);
 8063        });
 8064    }
 8065
 8066    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8067        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8068            s.move_cursors_with(|map, head, _| {
 8069                (
 8070                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8071                    SelectionGoal::None,
 8072                )
 8073            });
 8074        })
 8075    }
 8076
 8077    pub fn select_to_end_of_line(
 8078        &mut self,
 8079        action: &SelectToEndOfLine,
 8080        cx: &mut ViewContext<Self>,
 8081    ) {
 8082        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8083            s.move_heads_with(|map, head, _| {
 8084                (
 8085                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8086                    SelectionGoal::None,
 8087                )
 8088            });
 8089        })
 8090    }
 8091
 8092    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8093        self.transact(cx, |this, cx| {
 8094            this.select_to_end_of_line(
 8095                &SelectToEndOfLine {
 8096                    stop_at_soft_wraps: false,
 8097                },
 8098                cx,
 8099            );
 8100            this.delete(&Delete, cx);
 8101        });
 8102    }
 8103
 8104    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8105        self.transact(cx, |this, cx| {
 8106            this.select_to_end_of_line(
 8107                &SelectToEndOfLine {
 8108                    stop_at_soft_wraps: false,
 8109                },
 8110                cx,
 8111            );
 8112            this.cut(&Cut, cx);
 8113        });
 8114    }
 8115
 8116    pub fn move_to_start_of_paragraph(
 8117        &mut self,
 8118        _: &MoveToStartOfParagraph,
 8119        cx: &mut ViewContext<Self>,
 8120    ) {
 8121        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8122            cx.propagate();
 8123            return;
 8124        }
 8125
 8126        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8127            s.move_with(|map, selection| {
 8128                selection.collapse_to(
 8129                    movement::start_of_paragraph(map, selection.head(), 1),
 8130                    SelectionGoal::None,
 8131                )
 8132            });
 8133        })
 8134    }
 8135
 8136    pub fn move_to_end_of_paragraph(
 8137        &mut self,
 8138        _: &MoveToEndOfParagraph,
 8139        cx: &mut ViewContext<Self>,
 8140    ) {
 8141        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8142            cx.propagate();
 8143            return;
 8144        }
 8145
 8146        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8147            s.move_with(|map, selection| {
 8148                selection.collapse_to(
 8149                    movement::end_of_paragraph(map, selection.head(), 1),
 8150                    SelectionGoal::None,
 8151                )
 8152            });
 8153        })
 8154    }
 8155
 8156    pub fn select_to_start_of_paragraph(
 8157        &mut self,
 8158        _: &SelectToStartOfParagraph,
 8159        cx: &mut ViewContext<Self>,
 8160    ) {
 8161        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8162            cx.propagate();
 8163            return;
 8164        }
 8165
 8166        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8167            s.move_heads_with(|map, head, _| {
 8168                (
 8169                    movement::start_of_paragraph(map, head, 1),
 8170                    SelectionGoal::None,
 8171                )
 8172            });
 8173        })
 8174    }
 8175
 8176    pub fn select_to_end_of_paragraph(
 8177        &mut self,
 8178        _: &SelectToEndOfParagraph,
 8179        cx: &mut ViewContext<Self>,
 8180    ) {
 8181        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8182            cx.propagate();
 8183            return;
 8184        }
 8185
 8186        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8187            s.move_heads_with(|map, head, _| {
 8188                (
 8189                    movement::end_of_paragraph(map, head, 1),
 8190                    SelectionGoal::None,
 8191                )
 8192            });
 8193        })
 8194    }
 8195
 8196    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8197        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8198            cx.propagate();
 8199            return;
 8200        }
 8201
 8202        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8203            s.select_ranges(vec![0..0]);
 8204        });
 8205    }
 8206
 8207    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8208        let mut selection = self.selections.last::<Point>(cx);
 8209        selection.set_head(Point::zero(), SelectionGoal::None);
 8210
 8211        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8212            s.select(vec![selection]);
 8213        });
 8214    }
 8215
 8216    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8217        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8218            cx.propagate();
 8219            return;
 8220        }
 8221
 8222        let cursor = self.buffer.read(cx).read(cx).len();
 8223        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8224            s.select_ranges(vec![cursor..cursor])
 8225        });
 8226    }
 8227
 8228    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8229        self.nav_history = nav_history;
 8230    }
 8231
 8232    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8233        self.nav_history.as_ref()
 8234    }
 8235
 8236    fn push_to_nav_history(
 8237        &mut self,
 8238        cursor_anchor: Anchor,
 8239        new_position: Option<Point>,
 8240        cx: &mut ViewContext<Self>,
 8241    ) {
 8242        if let Some(nav_history) = self.nav_history.as_mut() {
 8243            let buffer = self.buffer.read(cx).read(cx);
 8244            let cursor_position = cursor_anchor.to_point(&buffer);
 8245            let scroll_state = self.scroll_manager.anchor();
 8246            let scroll_top_row = scroll_state.top_row(&buffer);
 8247            drop(buffer);
 8248
 8249            if let Some(new_position) = new_position {
 8250                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8251                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8252                    return;
 8253                }
 8254            }
 8255
 8256            nav_history.push(
 8257                Some(NavigationData {
 8258                    cursor_anchor,
 8259                    cursor_position,
 8260                    scroll_anchor: scroll_state,
 8261                    scroll_top_row,
 8262                }),
 8263                cx,
 8264            );
 8265        }
 8266    }
 8267
 8268    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8269        let buffer = self.buffer.read(cx).snapshot(cx);
 8270        let mut selection = self.selections.first::<usize>(cx);
 8271        selection.set_head(buffer.len(), SelectionGoal::None);
 8272        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8273            s.select(vec![selection]);
 8274        });
 8275    }
 8276
 8277    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8278        let end = self.buffer.read(cx).read(cx).len();
 8279        self.change_selections(None, cx, |s| {
 8280            s.select_ranges(vec![0..end]);
 8281        });
 8282    }
 8283
 8284    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8285        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8286        let mut selections = self.selections.all::<Point>(cx);
 8287        let max_point = display_map.buffer_snapshot.max_point();
 8288        for selection in &mut selections {
 8289            let rows = selection.spanned_rows(true, &display_map);
 8290            selection.start = Point::new(rows.start.0, 0);
 8291            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8292            selection.reversed = false;
 8293        }
 8294        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8295            s.select(selections);
 8296        });
 8297    }
 8298
 8299    pub fn split_selection_into_lines(
 8300        &mut self,
 8301        _: &SplitSelectionIntoLines,
 8302        cx: &mut ViewContext<Self>,
 8303    ) {
 8304        let mut to_unfold = Vec::new();
 8305        let mut new_selection_ranges = Vec::new();
 8306        {
 8307            let selections = self.selections.all::<Point>(cx);
 8308            let buffer = self.buffer.read(cx).read(cx);
 8309            for selection in selections {
 8310                for row in selection.start.row..selection.end.row {
 8311                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8312                    new_selection_ranges.push(cursor..cursor);
 8313                }
 8314                new_selection_ranges.push(selection.end..selection.end);
 8315                to_unfold.push(selection.start..selection.end);
 8316            }
 8317        }
 8318        self.unfold_ranges(&to_unfold, true, true, cx);
 8319        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8320            s.select_ranges(new_selection_ranges);
 8321        });
 8322    }
 8323
 8324    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8325        self.add_selection(true, cx);
 8326    }
 8327
 8328    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8329        self.add_selection(false, cx);
 8330    }
 8331
 8332    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8333        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8334        let mut selections = self.selections.all::<Point>(cx);
 8335        let text_layout_details = self.text_layout_details(cx);
 8336        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8337            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8338            let range = oldest_selection.display_range(&display_map).sorted();
 8339
 8340            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8341            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8342            let positions = start_x.min(end_x)..start_x.max(end_x);
 8343
 8344            selections.clear();
 8345            let mut stack = Vec::new();
 8346            for row in range.start.row().0..=range.end.row().0 {
 8347                if let Some(selection) = self.selections.build_columnar_selection(
 8348                    &display_map,
 8349                    DisplayRow(row),
 8350                    &positions,
 8351                    oldest_selection.reversed,
 8352                    &text_layout_details,
 8353                ) {
 8354                    stack.push(selection.id);
 8355                    selections.push(selection);
 8356                }
 8357            }
 8358
 8359            if above {
 8360                stack.reverse();
 8361            }
 8362
 8363            AddSelectionsState { above, stack }
 8364        });
 8365
 8366        let last_added_selection = *state.stack.last().unwrap();
 8367        let mut new_selections = Vec::new();
 8368        if above == state.above {
 8369            let end_row = if above {
 8370                DisplayRow(0)
 8371            } else {
 8372                display_map.max_point().row()
 8373            };
 8374
 8375            'outer: for selection in selections {
 8376                if selection.id == last_added_selection {
 8377                    let range = selection.display_range(&display_map).sorted();
 8378                    debug_assert_eq!(range.start.row(), range.end.row());
 8379                    let mut row = range.start.row();
 8380                    let positions =
 8381                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8382                            px(start)..px(end)
 8383                        } else {
 8384                            let start_x =
 8385                                display_map.x_for_display_point(range.start, &text_layout_details);
 8386                            let end_x =
 8387                                display_map.x_for_display_point(range.end, &text_layout_details);
 8388                            start_x.min(end_x)..start_x.max(end_x)
 8389                        };
 8390
 8391                    while row != end_row {
 8392                        if above {
 8393                            row.0 -= 1;
 8394                        } else {
 8395                            row.0 += 1;
 8396                        }
 8397
 8398                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8399                            &display_map,
 8400                            row,
 8401                            &positions,
 8402                            selection.reversed,
 8403                            &text_layout_details,
 8404                        ) {
 8405                            state.stack.push(new_selection.id);
 8406                            if above {
 8407                                new_selections.push(new_selection);
 8408                                new_selections.push(selection);
 8409                            } else {
 8410                                new_selections.push(selection);
 8411                                new_selections.push(new_selection);
 8412                            }
 8413
 8414                            continue 'outer;
 8415                        }
 8416                    }
 8417                }
 8418
 8419                new_selections.push(selection);
 8420            }
 8421        } else {
 8422            new_selections = selections;
 8423            new_selections.retain(|s| s.id != last_added_selection);
 8424            state.stack.pop();
 8425        }
 8426
 8427        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8428            s.select(new_selections);
 8429        });
 8430        if state.stack.len() > 1 {
 8431            self.add_selections_state = Some(state);
 8432        }
 8433    }
 8434
 8435    pub fn select_next_match_internal(
 8436        &mut self,
 8437        display_map: &DisplaySnapshot,
 8438        replace_newest: bool,
 8439        autoscroll: Option<Autoscroll>,
 8440        cx: &mut ViewContext<Self>,
 8441    ) -> Result<()> {
 8442        fn select_next_match_ranges(
 8443            this: &mut Editor,
 8444            range: Range<usize>,
 8445            replace_newest: bool,
 8446            auto_scroll: Option<Autoscroll>,
 8447            cx: &mut ViewContext<Editor>,
 8448        ) {
 8449            this.unfold_ranges(&[range.clone()], false, true, cx);
 8450            this.change_selections(auto_scroll, cx, |s| {
 8451                if replace_newest {
 8452                    s.delete(s.newest_anchor().id);
 8453                }
 8454                s.insert_range(range.clone());
 8455            });
 8456        }
 8457
 8458        let buffer = &display_map.buffer_snapshot;
 8459        let mut selections = self.selections.all::<usize>(cx);
 8460        if let Some(mut select_next_state) = self.select_next_state.take() {
 8461            let query = &select_next_state.query;
 8462            if !select_next_state.done {
 8463                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8464                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8465                let mut next_selected_range = None;
 8466
 8467                let bytes_after_last_selection =
 8468                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8469                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8470                let query_matches = query
 8471                    .stream_find_iter(bytes_after_last_selection)
 8472                    .map(|result| (last_selection.end, result))
 8473                    .chain(
 8474                        query
 8475                            .stream_find_iter(bytes_before_first_selection)
 8476                            .map(|result| (0, result)),
 8477                    );
 8478
 8479                for (start_offset, query_match) in query_matches {
 8480                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8481                    let offset_range =
 8482                        start_offset + query_match.start()..start_offset + query_match.end();
 8483                    let display_range = offset_range.start.to_display_point(display_map)
 8484                        ..offset_range.end.to_display_point(display_map);
 8485
 8486                    if !select_next_state.wordwise
 8487                        || (!movement::is_inside_word(display_map, display_range.start)
 8488                            && !movement::is_inside_word(display_map, display_range.end))
 8489                    {
 8490                        // TODO: This is n^2, because we might check all the selections
 8491                        if !selections
 8492                            .iter()
 8493                            .any(|selection| selection.range().overlaps(&offset_range))
 8494                        {
 8495                            next_selected_range = Some(offset_range);
 8496                            break;
 8497                        }
 8498                    }
 8499                }
 8500
 8501                if let Some(next_selected_range) = next_selected_range {
 8502                    select_next_match_ranges(
 8503                        self,
 8504                        next_selected_range,
 8505                        replace_newest,
 8506                        autoscroll,
 8507                        cx,
 8508                    );
 8509                } else {
 8510                    select_next_state.done = true;
 8511                }
 8512            }
 8513
 8514            self.select_next_state = Some(select_next_state);
 8515        } else {
 8516            let mut only_carets = true;
 8517            let mut same_text_selected = true;
 8518            let mut selected_text = None;
 8519
 8520            let mut selections_iter = selections.iter().peekable();
 8521            while let Some(selection) = selections_iter.next() {
 8522                if selection.start != selection.end {
 8523                    only_carets = false;
 8524                }
 8525
 8526                if same_text_selected {
 8527                    if selected_text.is_none() {
 8528                        selected_text =
 8529                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8530                    }
 8531
 8532                    if let Some(next_selection) = selections_iter.peek() {
 8533                        if next_selection.range().len() == selection.range().len() {
 8534                            let next_selected_text = buffer
 8535                                .text_for_range(next_selection.range())
 8536                                .collect::<String>();
 8537                            if Some(next_selected_text) != selected_text {
 8538                                same_text_selected = false;
 8539                                selected_text = None;
 8540                            }
 8541                        } else {
 8542                            same_text_selected = false;
 8543                            selected_text = None;
 8544                        }
 8545                    }
 8546                }
 8547            }
 8548
 8549            if only_carets {
 8550                for selection in &mut selections {
 8551                    let word_range = movement::surrounding_word(
 8552                        display_map,
 8553                        selection.start.to_display_point(display_map),
 8554                    );
 8555                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8556                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8557                    selection.goal = SelectionGoal::None;
 8558                    selection.reversed = false;
 8559                    select_next_match_ranges(
 8560                        self,
 8561                        selection.start..selection.end,
 8562                        replace_newest,
 8563                        autoscroll,
 8564                        cx,
 8565                    );
 8566                }
 8567
 8568                if selections.len() == 1 {
 8569                    let selection = selections
 8570                        .last()
 8571                        .expect("ensured that there's only one selection");
 8572                    let query = buffer
 8573                        .text_for_range(selection.start..selection.end)
 8574                        .collect::<String>();
 8575                    let is_empty = query.is_empty();
 8576                    let select_state = SelectNextState {
 8577                        query: AhoCorasick::new(&[query])?,
 8578                        wordwise: true,
 8579                        done: is_empty,
 8580                    };
 8581                    self.select_next_state = Some(select_state);
 8582                } else {
 8583                    self.select_next_state = None;
 8584                }
 8585            } else if let Some(selected_text) = selected_text {
 8586                self.select_next_state = Some(SelectNextState {
 8587                    query: AhoCorasick::new(&[selected_text])?,
 8588                    wordwise: false,
 8589                    done: false,
 8590                });
 8591                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8592            }
 8593        }
 8594        Ok(())
 8595    }
 8596
 8597    pub fn select_all_matches(
 8598        &mut self,
 8599        _action: &SelectAllMatches,
 8600        cx: &mut ViewContext<Self>,
 8601    ) -> Result<()> {
 8602        self.push_to_selection_history();
 8603        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8604
 8605        self.select_next_match_internal(&display_map, false, None, cx)?;
 8606        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8607            return Ok(());
 8608        };
 8609        if select_next_state.done {
 8610            return Ok(());
 8611        }
 8612
 8613        let mut new_selections = self.selections.all::<usize>(cx);
 8614
 8615        let buffer = &display_map.buffer_snapshot;
 8616        let query_matches = select_next_state
 8617            .query
 8618            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8619
 8620        for query_match in query_matches {
 8621            let query_match = query_match.unwrap(); // can only fail due to I/O
 8622            let offset_range = query_match.start()..query_match.end();
 8623            let display_range = offset_range.start.to_display_point(&display_map)
 8624                ..offset_range.end.to_display_point(&display_map);
 8625
 8626            if !select_next_state.wordwise
 8627                || (!movement::is_inside_word(&display_map, display_range.start)
 8628                    && !movement::is_inside_word(&display_map, display_range.end))
 8629            {
 8630                self.selections.change_with(cx, |selections| {
 8631                    new_selections.push(Selection {
 8632                        id: selections.new_selection_id(),
 8633                        start: offset_range.start,
 8634                        end: offset_range.end,
 8635                        reversed: false,
 8636                        goal: SelectionGoal::None,
 8637                    });
 8638                });
 8639            }
 8640        }
 8641
 8642        new_selections.sort_by_key(|selection| selection.start);
 8643        let mut ix = 0;
 8644        while ix + 1 < new_selections.len() {
 8645            let current_selection = &new_selections[ix];
 8646            let next_selection = &new_selections[ix + 1];
 8647            if current_selection.range().overlaps(&next_selection.range()) {
 8648                if current_selection.id < next_selection.id {
 8649                    new_selections.remove(ix + 1);
 8650                } else {
 8651                    new_selections.remove(ix);
 8652                }
 8653            } else {
 8654                ix += 1;
 8655            }
 8656        }
 8657
 8658        select_next_state.done = true;
 8659        self.unfold_ranges(
 8660            &new_selections
 8661                .iter()
 8662                .map(|selection| selection.range())
 8663                .collect::<Vec<_>>(),
 8664            false,
 8665            false,
 8666            cx,
 8667        );
 8668        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8669            selections.select(new_selections)
 8670        });
 8671
 8672        Ok(())
 8673    }
 8674
 8675    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8676        self.push_to_selection_history();
 8677        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8678        self.select_next_match_internal(
 8679            &display_map,
 8680            action.replace_newest,
 8681            Some(Autoscroll::newest()),
 8682            cx,
 8683        )?;
 8684        Ok(())
 8685    }
 8686
 8687    pub fn select_previous(
 8688        &mut self,
 8689        action: &SelectPrevious,
 8690        cx: &mut ViewContext<Self>,
 8691    ) -> Result<()> {
 8692        self.push_to_selection_history();
 8693        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8694        let buffer = &display_map.buffer_snapshot;
 8695        let mut selections = self.selections.all::<usize>(cx);
 8696        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8697            let query = &select_prev_state.query;
 8698            if !select_prev_state.done {
 8699                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8700                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8701                let mut next_selected_range = None;
 8702                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8703                let bytes_before_last_selection =
 8704                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8705                let bytes_after_first_selection =
 8706                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8707                let query_matches = query
 8708                    .stream_find_iter(bytes_before_last_selection)
 8709                    .map(|result| (last_selection.start, result))
 8710                    .chain(
 8711                        query
 8712                            .stream_find_iter(bytes_after_first_selection)
 8713                            .map(|result| (buffer.len(), result)),
 8714                    );
 8715                for (end_offset, query_match) in query_matches {
 8716                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8717                    let offset_range =
 8718                        end_offset - query_match.end()..end_offset - query_match.start();
 8719                    let display_range = offset_range.start.to_display_point(&display_map)
 8720                        ..offset_range.end.to_display_point(&display_map);
 8721
 8722                    if !select_prev_state.wordwise
 8723                        || (!movement::is_inside_word(&display_map, display_range.start)
 8724                            && !movement::is_inside_word(&display_map, display_range.end))
 8725                    {
 8726                        next_selected_range = Some(offset_range);
 8727                        break;
 8728                    }
 8729                }
 8730
 8731                if let Some(next_selected_range) = next_selected_range {
 8732                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8733                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8734                        if action.replace_newest {
 8735                            s.delete(s.newest_anchor().id);
 8736                        }
 8737                        s.insert_range(next_selected_range);
 8738                    });
 8739                } else {
 8740                    select_prev_state.done = true;
 8741                }
 8742            }
 8743
 8744            self.select_prev_state = Some(select_prev_state);
 8745        } else {
 8746            let mut only_carets = true;
 8747            let mut same_text_selected = true;
 8748            let mut selected_text = None;
 8749
 8750            let mut selections_iter = selections.iter().peekable();
 8751            while let Some(selection) = selections_iter.next() {
 8752                if selection.start != selection.end {
 8753                    only_carets = false;
 8754                }
 8755
 8756                if same_text_selected {
 8757                    if selected_text.is_none() {
 8758                        selected_text =
 8759                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8760                    }
 8761
 8762                    if let Some(next_selection) = selections_iter.peek() {
 8763                        if next_selection.range().len() == selection.range().len() {
 8764                            let next_selected_text = buffer
 8765                                .text_for_range(next_selection.range())
 8766                                .collect::<String>();
 8767                            if Some(next_selected_text) != selected_text {
 8768                                same_text_selected = false;
 8769                                selected_text = None;
 8770                            }
 8771                        } else {
 8772                            same_text_selected = false;
 8773                            selected_text = None;
 8774                        }
 8775                    }
 8776                }
 8777            }
 8778
 8779            if only_carets {
 8780                for selection in &mut selections {
 8781                    let word_range = movement::surrounding_word(
 8782                        &display_map,
 8783                        selection.start.to_display_point(&display_map),
 8784                    );
 8785                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8786                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8787                    selection.goal = SelectionGoal::None;
 8788                    selection.reversed = false;
 8789                }
 8790                if selections.len() == 1 {
 8791                    let selection = selections
 8792                        .last()
 8793                        .expect("ensured that there's only one selection");
 8794                    let query = buffer
 8795                        .text_for_range(selection.start..selection.end)
 8796                        .collect::<String>();
 8797                    let is_empty = query.is_empty();
 8798                    let select_state = SelectNextState {
 8799                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8800                        wordwise: true,
 8801                        done: is_empty,
 8802                    };
 8803                    self.select_prev_state = Some(select_state);
 8804                } else {
 8805                    self.select_prev_state = None;
 8806                }
 8807
 8808                self.unfold_ranges(
 8809                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8810                    false,
 8811                    true,
 8812                    cx,
 8813                );
 8814                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8815                    s.select(selections);
 8816                });
 8817            } else if let Some(selected_text) = selected_text {
 8818                self.select_prev_state = Some(SelectNextState {
 8819                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8820                    wordwise: false,
 8821                    done: false,
 8822                });
 8823                self.select_previous(action, cx)?;
 8824            }
 8825        }
 8826        Ok(())
 8827    }
 8828
 8829    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8830        if self.read_only(cx) {
 8831            return;
 8832        }
 8833        let text_layout_details = &self.text_layout_details(cx);
 8834        self.transact(cx, |this, cx| {
 8835            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8836            let mut edits = Vec::new();
 8837            let mut selection_edit_ranges = Vec::new();
 8838            let mut last_toggled_row = None;
 8839            let snapshot = this.buffer.read(cx).read(cx);
 8840            let empty_str: Arc<str> = Arc::default();
 8841            let mut suffixes_inserted = Vec::new();
 8842            let ignore_indent = action.ignore_indent;
 8843
 8844            fn comment_prefix_range(
 8845                snapshot: &MultiBufferSnapshot,
 8846                row: MultiBufferRow,
 8847                comment_prefix: &str,
 8848                comment_prefix_whitespace: &str,
 8849                ignore_indent: bool,
 8850            ) -> Range<Point> {
 8851                let indent_size = if ignore_indent {
 8852                    0
 8853                } else {
 8854                    snapshot.indent_size_for_line(row).len
 8855                };
 8856
 8857                let start = Point::new(row.0, indent_size);
 8858
 8859                let mut line_bytes = snapshot
 8860                    .bytes_in_range(start..snapshot.max_point())
 8861                    .flatten()
 8862                    .copied();
 8863
 8864                // If this line currently begins with the line comment prefix, then record
 8865                // the range containing the prefix.
 8866                if line_bytes
 8867                    .by_ref()
 8868                    .take(comment_prefix.len())
 8869                    .eq(comment_prefix.bytes())
 8870                {
 8871                    // Include any whitespace that matches the comment prefix.
 8872                    let matching_whitespace_len = line_bytes
 8873                        .zip(comment_prefix_whitespace.bytes())
 8874                        .take_while(|(a, b)| a == b)
 8875                        .count() as u32;
 8876                    let end = Point::new(
 8877                        start.row,
 8878                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8879                    );
 8880                    start..end
 8881                } else {
 8882                    start..start
 8883                }
 8884            }
 8885
 8886            fn comment_suffix_range(
 8887                snapshot: &MultiBufferSnapshot,
 8888                row: MultiBufferRow,
 8889                comment_suffix: &str,
 8890                comment_suffix_has_leading_space: bool,
 8891            ) -> Range<Point> {
 8892                let end = Point::new(row.0, snapshot.line_len(row));
 8893                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8894
 8895                let mut line_end_bytes = snapshot
 8896                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8897                    .flatten()
 8898                    .copied();
 8899
 8900                let leading_space_len = if suffix_start_column > 0
 8901                    && line_end_bytes.next() == Some(b' ')
 8902                    && comment_suffix_has_leading_space
 8903                {
 8904                    1
 8905                } else {
 8906                    0
 8907                };
 8908
 8909                // If this line currently begins with the line comment prefix, then record
 8910                // the range containing the prefix.
 8911                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8912                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8913                    start..end
 8914                } else {
 8915                    end..end
 8916                }
 8917            }
 8918
 8919            // TODO: Handle selections that cross excerpts
 8920            for selection in &mut selections {
 8921                let start_column = snapshot
 8922                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8923                    .len;
 8924                let language = if let Some(language) =
 8925                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8926                {
 8927                    language
 8928                } else {
 8929                    continue;
 8930                };
 8931
 8932                selection_edit_ranges.clear();
 8933
 8934                // If multiple selections contain a given row, avoid processing that
 8935                // row more than once.
 8936                let mut start_row = MultiBufferRow(selection.start.row);
 8937                if last_toggled_row == Some(start_row) {
 8938                    start_row = start_row.next_row();
 8939                }
 8940                let end_row =
 8941                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8942                        MultiBufferRow(selection.end.row - 1)
 8943                    } else {
 8944                        MultiBufferRow(selection.end.row)
 8945                    };
 8946                last_toggled_row = Some(end_row);
 8947
 8948                if start_row > end_row {
 8949                    continue;
 8950                }
 8951
 8952                // If the language has line comments, toggle those.
 8953                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8954
 8955                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8956                if ignore_indent {
 8957                    full_comment_prefixes = full_comment_prefixes
 8958                        .into_iter()
 8959                        .map(|s| Arc::from(s.trim_end()))
 8960                        .collect();
 8961                }
 8962
 8963                if !full_comment_prefixes.is_empty() {
 8964                    let first_prefix = full_comment_prefixes
 8965                        .first()
 8966                        .expect("prefixes is non-empty");
 8967                    let prefix_trimmed_lengths = full_comment_prefixes
 8968                        .iter()
 8969                        .map(|p| p.trim_end_matches(' ').len())
 8970                        .collect::<SmallVec<[usize; 4]>>();
 8971
 8972                    let mut all_selection_lines_are_comments = true;
 8973
 8974                    for row in start_row.0..=end_row.0 {
 8975                        let row = MultiBufferRow(row);
 8976                        if start_row < end_row && snapshot.is_line_blank(row) {
 8977                            continue;
 8978                        }
 8979
 8980                        let prefix_range = full_comment_prefixes
 8981                            .iter()
 8982                            .zip(prefix_trimmed_lengths.iter().copied())
 8983                            .map(|(prefix, trimmed_prefix_len)| {
 8984                                comment_prefix_range(
 8985                                    snapshot.deref(),
 8986                                    row,
 8987                                    &prefix[..trimmed_prefix_len],
 8988                                    &prefix[trimmed_prefix_len..],
 8989                                    ignore_indent,
 8990                                )
 8991                            })
 8992                            .max_by_key(|range| range.end.column - range.start.column)
 8993                            .expect("prefixes is non-empty");
 8994
 8995                        if prefix_range.is_empty() {
 8996                            all_selection_lines_are_comments = false;
 8997                        }
 8998
 8999                        selection_edit_ranges.push(prefix_range);
 9000                    }
 9001
 9002                    if all_selection_lines_are_comments {
 9003                        edits.extend(
 9004                            selection_edit_ranges
 9005                                .iter()
 9006                                .cloned()
 9007                                .map(|range| (range, empty_str.clone())),
 9008                        );
 9009                    } else {
 9010                        let min_column = selection_edit_ranges
 9011                            .iter()
 9012                            .map(|range| range.start.column)
 9013                            .min()
 9014                            .unwrap_or(0);
 9015                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9016                            let position = Point::new(range.start.row, min_column);
 9017                            (position..position, first_prefix.clone())
 9018                        }));
 9019                    }
 9020                } else if let Some((full_comment_prefix, comment_suffix)) =
 9021                    language.block_comment_delimiters()
 9022                {
 9023                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9024                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9025                    let prefix_range = comment_prefix_range(
 9026                        snapshot.deref(),
 9027                        start_row,
 9028                        comment_prefix,
 9029                        comment_prefix_whitespace,
 9030                        ignore_indent,
 9031                    );
 9032                    let suffix_range = comment_suffix_range(
 9033                        snapshot.deref(),
 9034                        end_row,
 9035                        comment_suffix.trim_start_matches(' '),
 9036                        comment_suffix.starts_with(' '),
 9037                    );
 9038
 9039                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9040                        edits.push((
 9041                            prefix_range.start..prefix_range.start,
 9042                            full_comment_prefix.clone(),
 9043                        ));
 9044                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9045                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9046                    } else {
 9047                        edits.push((prefix_range, empty_str.clone()));
 9048                        edits.push((suffix_range, empty_str.clone()));
 9049                    }
 9050                } else {
 9051                    continue;
 9052                }
 9053            }
 9054
 9055            drop(snapshot);
 9056            this.buffer.update(cx, |buffer, cx| {
 9057                buffer.edit(edits, None, cx);
 9058            });
 9059
 9060            // Adjust selections so that they end before any comment suffixes that
 9061            // were inserted.
 9062            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9063            let mut selections = this.selections.all::<Point>(cx);
 9064            let snapshot = this.buffer.read(cx).read(cx);
 9065            for selection in &mut selections {
 9066                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9067                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9068                        Ordering::Less => {
 9069                            suffixes_inserted.next();
 9070                            continue;
 9071                        }
 9072                        Ordering::Greater => break,
 9073                        Ordering::Equal => {
 9074                            if selection.end.column == snapshot.line_len(row) {
 9075                                if selection.is_empty() {
 9076                                    selection.start.column -= suffix_len as u32;
 9077                                }
 9078                                selection.end.column -= suffix_len as u32;
 9079                            }
 9080                            break;
 9081                        }
 9082                    }
 9083                }
 9084            }
 9085
 9086            drop(snapshot);
 9087            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9088
 9089            let selections = this.selections.all::<Point>(cx);
 9090            let selections_on_single_row = selections.windows(2).all(|selections| {
 9091                selections[0].start.row == selections[1].start.row
 9092                    && selections[0].end.row == selections[1].end.row
 9093                    && selections[0].start.row == selections[0].end.row
 9094            });
 9095            let selections_selecting = selections
 9096                .iter()
 9097                .any(|selection| selection.start != selection.end);
 9098            let advance_downwards = action.advance_downwards
 9099                && selections_on_single_row
 9100                && !selections_selecting
 9101                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9102
 9103            if advance_downwards {
 9104                let snapshot = this.buffer.read(cx).snapshot(cx);
 9105
 9106                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9107                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9108                        let mut point = display_point.to_point(display_snapshot);
 9109                        point.row += 1;
 9110                        point = snapshot.clip_point(point, Bias::Left);
 9111                        let display_point = point.to_display_point(display_snapshot);
 9112                        let goal = SelectionGoal::HorizontalPosition(
 9113                            display_snapshot
 9114                                .x_for_display_point(display_point, text_layout_details)
 9115                                .into(),
 9116                        );
 9117                        (display_point, goal)
 9118                    })
 9119                });
 9120            }
 9121        });
 9122    }
 9123
 9124    pub fn select_enclosing_symbol(
 9125        &mut self,
 9126        _: &SelectEnclosingSymbol,
 9127        cx: &mut ViewContext<Self>,
 9128    ) {
 9129        let buffer = self.buffer.read(cx).snapshot(cx);
 9130        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9131
 9132        fn update_selection(
 9133            selection: &Selection<usize>,
 9134            buffer_snap: &MultiBufferSnapshot,
 9135        ) -> Option<Selection<usize>> {
 9136            let cursor = selection.head();
 9137            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9138            for symbol in symbols.iter().rev() {
 9139                let start = symbol.range.start.to_offset(buffer_snap);
 9140                let end = symbol.range.end.to_offset(buffer_snap);
 9141                let new_range = start..end;
 9142                if start < selection.start || end > selection.end {
 9143                    return Some(Selection {
 9144                        id: selection.id,
 9145                        start: new_range.start,
 9146                        end: new_range.end,
 9147                        goal: SelectionGoal::None,
 9148                        reversed: selection.reversed,
 9149                    });
 9150                }
 9151            }
 9152            None
 9153        }
 9154
 9155        let mut selected_larger_symbol = false;
 9156        let new_selections = old_selections
 9157            .iter()
 9158            .map(|selection| match update_selection(selection, &buffer) {
 9159                Some(new_selection) => {
 9160                    if new_selection.range() != selection.range() {
 9161                        selected_larger_symbol = true;
 9162                    }
 9163                    new_selection
 9164                }
 9165                None => selection.clone(),
 9166            })
 9167            .collect::<Vec<_>>();
 9168
 9169        if selected_larger_symbol {
 9170            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9171                s.select(new_selections);
 9172            });
 9173        }
 9174    }
 9175
 9176    pub fn select_larger_syntax_node(
 9177        &mut self,
 9178        _: &SelectLargerSyntaxNode,
 9179        cx: &mut ViewContext<Self>,
 9180    ) {
 9181        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9182        let buffer = self.buffer.read(cx).snapshot(cx);
 9183        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9184
 9185        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9186        let mut selected_larger_node = false;
 9187        let new_selections = old_selections
 9188            .iter()
 9189            .map(|selection| {
 9190                let old_range = selection.start..selection.end;
 9191                let mut new_range = old_range.clone();
 9192                while let Some(containing_range) =
 9193                    buffer.range_for_syntax_ancestor(new_range.clone())
 9194                {
 9195                    new_range = containing_range;
 9196                    if !display_map.intersects_fold(new_range.start)
 9197                        && !display_map.intersects_fold(new_range.end)
 9198                    {
 9199                        break;
 9200                    }
 9201                }
 9202
 9203                selected_larger_node |= new_range != old_range;
 9204                Selection {
 9205                    id: selection.id,
 9206                    start: new_range.start,
 9207                    end: new_range.end,
 9208                    goal: SelectionGoal::None,
 9209                    reversed: selection.reversed,
 9210                }
 9211            })
 9212            .collect::<Vec<_>>();
 9213
 9214        if selected_larger_node {
 9215            stack.push(old_selections);
 9216            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9217                s.select(new_selections);
 9218            });
 9219        }
 9220        self.select_larger_syntax_node_stack = stack;
 9221    }
 9222
 9223    pub fn select_smaller_syntax_node(
 9224        &mut self,
 9225        _: &SelectSmallerSyntaxNode,
 9226        cx: &mut ViewContext<Self>,
 9227    ) {
 9228        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9229        if let Some(selections) = stack.pop() {
 9230            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9231                s.select(selections.to_vec());
 9232            });
 9233        }
 9234        self.select_larger_syntax_node_stack = stack;
 9235    }
 9236
 9237    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9238        if !EditorSettings::get_global(cx).gutter.runnables {
 9239            self.clear_tasks();
 9240            return Task::ready(());
 9241        }
 9242        let project = self.project.as_ref().map(Model::downgrade);
 9243        cx.spawn(|this, mut cx| async move {
 9244            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9245            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9246                return;
 9247            };
 9248            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9249                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9250            }) else {
 9251                return;
 9252            };
 9253
 9254            let hide_runnables = project
 9255                .update(&mut cx, |project, cx| {
 9256                    // Do not display any test indicators in non-dev server remote projects.
 9257                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9258                })
 9259                .unwrap_or(true);
 9260            if hide_runnables {
 9261                return;
 9262            }
 9263            let new_rows =
 9264                cx.background_executor()
 9265                    .spawn({
 9266                        let snapshot = display_snapshot.clone();
 9267                        async move {
 9268                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9269                        }
 9270                    })
 9271                    .await;
 9272            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9273
 9274            this.update(&mut cx, |this, _| {
 9275                this.clear_tasks();
 9276                for (key, value) in rows {
 9277                    this.insert_tasks(key, value);
 9278                }
 9279            })
 9280            .ok();
 9281        })
 9282    }
 9283    fn fetch_runnable_ranges(
 9284        snapshot: &DisplaySnapshot,
 9285        range: Range<Anchor>,
 9286    ) -> Vec<language::RunnableRange> {
 9287        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9288    }
 9289
 9290    fn runnable_rows(
 9291        project: Model<Project>,
 9292        snapshot: DisplaySnapshot,
 9293        runnable_ranges: Vec<RunnableRange>,
 9294        mut cx: AsyncWindowContext,
 9295    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9296        runnable_ranges
 9297            .into_iter()
 9298            .filter_map(|mut runnable| {
 9299                let tasks = cx
 9300                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9301                    .ok()?;
 9302                if tasks.is_empty() {
 9303                    return None;
 9304                }
 9305
 9306                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9307
 9308                let row = snapshot
 9309                    .buffer_snapshot
 9310                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9311                    .1
 9312                    .start
 9313                    .row;
 9314
 9315                let context_range =
 9316                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9317                Some((
 9318                    (runnable.buffer_id, row),
 9319                    RunnableTasks {
 9320                        templates: tasks,
 9321                        offset: MultiBufferOffset(runnable.run_range.start),
 9322                        context_range,
 9323                        column: point.column,
 9324                        extra_variables: runnable.extra_captures,
 9325                    },
 9326                ))
 9327            })
 9328            .collect()
 9329    }
 9330
 9331    fn templates_with_tags(
 9332        project: &Model<Project>,
 9333        runnable: &mut Runnable,
 9334        cx: &WindowContext<'_>,
 9335    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9336        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9337            let (worktree_id, file) = project
 9338                .buffer_for_id(runnable.buffer, cx)
 9339                .and_then(|buffer| buffer.read(cx).file())
 9340                .map(|file| (file.worktree_id(cx), file.clone()))
 9341                .unzip();
 9342
 9343            (
 9344                project.task_store().read(cx).task_inventory().cloned(),
 9345                worktree_id,
 9346                file,
 9347            )
 9348        });
 9349
 9350        let tags = mem::take(&mut runnable.tags);
 9351        let mut tags: Vec<_> = tags
 9352            .into_iter()
 9353            .flat_map(|tag| {
 9354                let tag = tag.0.clone();
 9355                inventory
 9356                    .as_ref()
 9357                    .into_iter()
 9358                    .flat_map(|inventory| {
 9359                        inventory.read(cx).list_tasks(
 9360                            file.clone(),
 9361                            Some(runnable.language.clone()),
 9362                            worktree_id,
 9363                            cx,
 9364                        )
 9365                    })
 9366                    .filter(move |(_, template)| {
 9367                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9368                    })
 9369            })
 9370            .sorted_by_key(|(kind, _)| kind.to_owned())
 9371            .collect();
 9372        if let Some((leading_tag_source, _)) = tags.first() {
 9373            // Strongest source wins; if we have worktree tag binding, prefer that to
 9374            // global and language bindings;
 9375            // if we have a global binding, prefer that to language binding.
 9376            let first_mismatch = tags
 9377                .iter()
 9378                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9379            if let Some(index) = first_mismatch {
 9380                tags.truncate(index);
 9381            }
 9382        }
 9383
 9384        tags
 9385    }
 9386
 9387    pub fn move_to_enclosing_bracket(
 9388        &mut self,
 9389        _: &MoveToEnclosingBracket,
 9390        cx: &mut ViewContext<Self>,
 9391    ) {
 9392        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9393            s.move_offsets_with(|snapshot, selection| {
 9394                let Some(enclosing_bracket_ranges) =
 9395                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9396                else {
 9397                    return;
 9398                };
 9399
 9400                let mut best_length = usize::MAX;
 9401                let mut best_inside = false;
 9402                let mut best_in_bracket_range = false;
 9403                let mut best_destination = None;
 9404                for (open, close) in enclosing_bracket_ranges {
 9405                    let close = close.to_inclusive();
 9406                    let length = close.end() - open.start;
 9407                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9408                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9409                        || close.contains(&selection.head());
 9410
 9411                    // If best is next to a bracket and current isn't, skip
 9412                    if !in_bracket_range && best_in_bracket_range {
 9413                        continue;
 9414                    }
 9415
 9416                    // Prefer smaller lengths unless best is inside and current isn't
 9417                    if length > best_length && (best_inside || !inside) {
 9418                        continue;
 9419                    }
 9420
 9421                    best_length = length;
 9422                    best_inside = inside;
 9423                    best_in_bracket_range = in_bracket_range;
 9424                    best_destination = Some(
 9425                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9426                            if inside {
 9427                                open.end
 9428                            } else {
 9429                                open.start
 9430                            }
 9431                        } else if inside {
 9432                            *close.start()
 9433                        } else {
 9434                            *close.end()
 9435                        },
 9436                    );
 9437                }
 9438
 9439                if let Some(destination) = best_destination {
 9440                    selection.collapse_to(destination, SelectionGoal::None);
 9441                }
 9442            })
 9443        });
 9444    }
 9445
 9446    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9447        self.end_selection(cx);
 9448        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9449        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9450            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9451            self.select_next_state = entry.select_next_state;
 9452            self.select_prev_state = entry.select_prev_state;
 9453            self.add_selections_state = entry.add_selections_state;
 9454            self.request_autoscroll(Autoscroll::newest(), cx);
 9455        }
 9456        self.selection_history.mode = SelectionHistoryMode::Normal;
 9457    }
 9458
 9459    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9460        self.end_selection(cx);
 9461        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9462        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9463            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9464            self.select_next_state = entry.select_next_state;
 9465            self.select_prev_state = entry.select_prev_state;
 9466            self.add_selections_state = entry.add_selections_state;
 9467            self.request_autoscroll(Autoscroll::newest(), cx);
 9468        }
 9469        self.selection_history.mode = SelectionHistoryMode::Normal;
 9470    }
 9471
 9472    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9473        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9474    }
 9475
 9476    pub fn expand_excerpts_down(
 9477        &mut self,
 9478        action: &ExpandExcerptsDown,
 9479        cx: &mut ViewContext<Self>,
 9480    ) {
 9481        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9482    }
 9483
 9484    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9485        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9486    }
 9487
 9488    pub fn expand_excerpts_for_direction(
 9489        &mut self,
 9490        lines: u32,
 9491        direction: ExpandExcerptDirection,
 9492        cx: &mut ViewContext<Self>,
 9493    ) {
 9494        let selections = self.selections.disjoint_anchors();
 9495
 9496        let lines = if lines == 0 {
 9497            EditorSettings::get_global(cx).expand_excerpt_lines
 9498        } else {
 9499            lines
 9500        };
 9501
 9502        self.buffer.update(cx, |buffer, cx| {
 9503            buffer.expand_excerpts(
 9504                selections
 9505                    .iter()
 9506                    .map(|selection| selection.head().excerpt_id)
 9507                    .dedup(),
 9508                lines,
 9509                direction,
 9510                cx,
 9511            )
 9512        })
 9513    }
 9514
 9515    pub fn expand_excerpt(
 9516        &mut self,
 9517        excerpt: ExcerptId,
 9518        direction: ExpandExcerptDirection,
 9519        cx: &mut ViewContext<Self>,
 9520    ) {
 9521        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9522        self.buffer.update(cx, |buffer, cx| {
 9523            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9524        })
 9525    }
 9526
 9527    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9528        self.go_to_diagnostic_impl(Direction::Next, cx)
 9529    }
 9530
 9531    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9532        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9533    }
 9534
 9535    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9536        let buffer = self.buffer.read(cx).snapshot(cx);
 9537        let selection = self.selections.newest::<usize>(cx);
 9538
 9539        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9540        if direction == Direction::Next {
 9541            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9542                let (group_id, jump_to) = popover.activation_info();
 9543                if self.activate_diagnostics(group_id, cx) {
 9544                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9545                        let mut new_selection = s.newest_anchor().clone();
 9546                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9547                        s.select_anchors(vec![new_selection.clone()]);
 9548                    });
 9549                }
 9550                return;
 9551            }
 9552        }
 9553
 9554        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9555            active_diagnostics
 9556                .primary_range
 9557                .to_offset(&buffer)
 9558                .to_inclusive()
 9559        });
 9560        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9561            if active_primary_range.contains(&selection.head()) {
 9562                *active_primary_range.start()
 9563            } else {
 9564                selection.head()
 9565            }
 9566        } else {
 9567            selection.head()
 9568        };
 9569        let snapshot = self.snapshot(cx);
 9570        loop {
 9571            let diagnostics = if direction == Direction::Prev {
 9572                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9573            } else {
 9574                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9575            }
 9576            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9577            let group = diagnostics
 9578                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9579                // be sorted in a stable way
 9580                // skip until we are at current active diagnostic, if it exists
 9581                .skip_while(|entry| {
 9582                    (match direction {
 9583                        Direction::Prev => entry.range.start >= search_start,
 9584                        Direction::Next => entry.range.start <= search_start,
 9585                    }) && self
 9586                        .active_diagnostics
 9587                        .as_ref()
 9588                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9589                })
 9590                .find_map(|entry| {
 9591                    if entry.diagnostic.is_primary
 9592                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9593                        && !entry.range.is_empty()
 9594                        // if we match with the active diagnostic, skip it
 9595                        && Some(entry.diagnostic.group_id)
 9596                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9597                    {
 9598                        Some((entry.range, entry.diagnostic.group_id))
 9599                    } else {
 9600                        None
 9601                    }
 9602                });
 9603
 9604            if let Some((primary_range, group_id)) = group {
 9605                if self.activate_diagnostics(group_id, cx) {
 9606                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9607                        s.select(vec![Selection {
 9608                            id: selection.id,
 9609                            start: primary_range.start,
 9610                            end: primary_range.start,
 9611                            reversed: false,
 9612                            goal: SelectionGoal::None,
 9613                        }]);
 9614                    });
 9615                }
 9616                break;
 9617            } else {
 9618                // Cycle around to the start of the buffer, potentially moving back to the start of
 9619                // the currently active diagnostic.
 9620                active_primary_range.take();
 9621                if direction == Direction::Prev {
 9622                    if search_start == buffer.len() {
 9623                        break;
 9624                    } else {
 9625                        search_start = buffer.len();
 9626                    }
 9627                } else if search_start == 0 {
 9628                    break;
 9629                } else {
 9630                    search_start = 0;
 9631                }
 9632            }
 9633        }
 9634    }
 9635
 9636    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9637        let snapshot = self
 9638            .display_map
 9639            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9640        let selection = self.selections.newest::<Point>(cx);
 9641        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9642    }
 9643
 9644    fn go_to_hunk_after_position(
 9645        &mut self,
 9646        snapshot: &DisplaySnapshot,
 9647        position: Point,
 9648        cx: &mut ViewContext<'_, Editor>,
 9649    ) -> Option<MultiBufferDiffHunk> {
 9650        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9651            snapshot,
 9652            position,
 9653            false,
 9654            snapshot
 9655                .buffer_snapshot
 9656                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9657            cx,
 9658        ) {
 9659            return Some(hunk);
 9660        }
 9661
 9662        let wrapped_point = Point::zero();
 9663        self.go_to_next_hunk_in_direction(
 9664            snapshot,
 9665            wrapped_point,
 9666            true,
 9667            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9668                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9669            ),
 9670            cx,
 9671        )
 9672    }
 9673
 9674    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9675        let snapshot = self
 9676            .display_map
 9677            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9678        let selection = self.selections.newest::<Point>(cx);
 9679
 9680        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9681    }
 9682
 9683    fn go_to_hunk_before_position(
 9684        &mut self,
 9685        snapshot: &DisplaySnapshot,
 9686        position: Point,
 9687        cx: &mut ViewContext<'_, Editor>,
 9688    ) -> Option<MultiBufferDiffHunk> {
 9689        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9690            snapshot,
 9691            position,
 9692            false,
 9693            snapshot
 9694                .buffer_snapshot
 9695                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9696            cx,
 9697        ) {
 9698            return Some(hunk);
 9699        }
 9700
 9701        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9702        self.go_to_next_hunk_in_direction(
 9703            snapshot,
 9704            wrapped_point,
 9705            true,
 9706            snapshot
 9707                .buffer_snapshot
 9708                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9709            cx,
 9710        )
 9711    }
 9712
 9713    fn go_to_next_hunk_in_direction(
 9714        &mut self,
 9715        snapshot: &DisplaySnapshot,
 9716        initial_point: Point,
 9717        is_wrapped: bool,
 9718        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9719        cx: &mut ViewContext<Editor>,
 9720    ) -> Option<MultiBufferDiffHunk> {
 9721        let display_point = initial_point.to_display_point(snapshot);
 9722        let mut hunks = hunks
 9723            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9724            .filter(|(display_hunk, _)| {
 9725                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9726            })
 9727            .dedup();
 9728
 9729        if let Some((display_hunk, hunk)) = hunks.next() {
 9730            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9731                let row = display_hunk.start_display_row();
 9732                let point = DisplayPoint::new(row, 0);
 9733                s.select_display_ranges([point..point]);
 9734            });
 9735
 9736            Some(hunk)
 9737        } else {
 9738            None
 9739        }
 9740    }
 9741
 9742    pub fn go_to_definition(
 9743        &mut self,
 9744        _: &GoToDefinition,
 9745        cx: &mut ViewContext<Self>,
 9746    ) -> Task<Result<Navigated>> {
 9747        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9748        cx.spawn(|editor, mut cx| async move {
 9749            if definition.await? == Navigated::Yes {
 9750                return Ok(Navigated::Yes);
 9751            }
 9752            match editor.update(&mut cx, |editor, cx| {
 9753                editor.find_all_references(&FindAllReferences, cx)
 9754            })? {
 9755                Some(references) => references.await,
 9756                None => Ok(Navigated::No),
 9757            }
 9758        })
 9759    }
 9760
 9761    pub fn go_to_declaration(
 9762        &mut self,
 9763        _: &GoToDeclaration,
 9764        cx: &mut ViewContext<Self>,
 9765    ) -> Task<Result<Navigated>> {
 9766        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9767    }
 9768
 9769    pub fn go_to_declaration_split(
 9770        &mut self,
 9771        _: &GoToDeclaration,
 9772        cx: &mut ViewContext<Self>,
 9773    ) -> Task<Result<Navigated>> {
 9774        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9775    }
 9776
 9777    pub fn go_to_implementation(
 9778        &mut self,
 9779        _: &GoToImplementation,
 9780        cx: &mut ViewContext<Self>,
 9781    ) -> Task<Result<Navigated>> {
 9782        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9783    }
 9784
 9785    pub fn go_to_implementation_split(
 9786        &mut self,
 9787        _: &GoToImplementationSplit,
 9788        cx: &mut ViewContext<Self>,
 9789    ) -> Task<Result<Navigated>> {
 9790        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9791    }
 9792
 9793    pub fn go_to_type_definition(
 9794        &mut self,
 9795        _: &GoToTypeDefinition,
 9796        cx: &mut ViewContext<Self>,
 9797    ) -> Task<Result<Navigated>> {
 9798        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9799    }
 9800
 9801    pub fn go_to_definition_split(
 9802        &mut self,
 9803        _: &GoToDefinitionSplit,
 9804        cx: &mut ViewContext<Self>,
 9805    ) -> Task<Result<Navigated>> {
 9806        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9807    }
 9808
 9809    pub fn go_to_type_definition_split(
 9810        &mut self,
 9811        _: &GoToTypeDefinitionSplit,
 9812        cx: &mut ViewContext<Self>,
 9813    ) -> Task<Result<Navigated>> {
 9814        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9815    }
 9816
 9817    fn go_to_definition_of_kind(
 9818        &mut self,
 9819        kind: GotoDefinitionKind,
 9820        split: bool,
 9821        cx: &mut ViewContext<Self>,
 9822    ) -> Task<Result<Navigated>> {
 9823        let Some(provider) = self.semantics_provider.clone() else {
 9824            return Task::ready(Ok(Navigated::No));
 9825        };
 9826        let head = self.selections.newest::<usize>(cx).head();
 9827        let buffer = self.buffer.read(cx);
 9828        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9829            text_anchor
 9830        } else {
 9831            return Task::ready(Ok(Navigated::No));
 9832        };
 9833
 9834        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9835            return Task::ready(Ok(Navigated::No));
 9836        };
 9837
 9838        cx.spawn(|editor, mut cx| async move {
 9839            let definitions = definitions.await?;
 9840            let navigated = editor
 9841                .update(&mut cx, |editor, cx| {
 9842                    editor.navigate_to_hover_links(
 9843                        Some(kind),
 9844                        definitions
 9845                            .into_iter()
 9846                            .filter(|location| {
 9847                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9848                            })
 9849                            .map(HoverLink::Text)
 9850                            .collect::<Vec<_>>(),
 9851                        split,
 9852                        cx,
 9853                    )
 9854                })?
 9855                .await?;
 9856            anyhow::Ok(navigated)
 9857        })
 9858    }
 9859
 9860    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9861        let position = self.selections.newest_anchor().head();
 9862        let Some((buffer, buffer_position)) =
 9863            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9864        else {
 9865            return;
 9866        };
 9867
 9868        cx.spawn(|editor, mut cx| async move {
 9869            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9870                editor.update(&mut cx, |_, cx| {
 9871                    cx.open_url(&url);
 9872                })
 9873            } else {
 9874                Ok(())
 9875            }
 9876        })
 9877        .detach();
 9878    }
 9879
 9880    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9881        let Some(workspace) = self.workspace() else {
 9882            return;
 9883        };
 9884
 9885        let position = self.selections.newest_anchor().head();
 9886
 9887        let Some((buffer, buffer_position)) =
 9888            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9889        else {
 9890            return;
 9891        };
 9892
 9893        let project = self.project.clone();
 9894
 9895        cx.spawn(|_, mut cx| async move {
 9896            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9897
 9898            if let Some((_, path)) = result {
 9899                workspace
 9900                    .update(&mut cx, |workspace, cx| {
 9901                        workspace.open_resolved_path(path, cx)
 9902                    })?
 9903                    .await?;
 9904            }
 9905            anyhow::Ok(())
 9906        })
 9907        .detach();
 9908    }
 9909
 9910    pub(crate) fn navigate_to_hover_links(
 9911        &mut self,
 9912        kind: Option<GotoDefinitionKind>,
 9913        mut definitions: Vec<HoverLink>,
 9914        split: bool,
 9915        cx: &mut ViewContext<Editor>,
 9916    ) -> Task<Result<Navigated>> {
 9917        // If there is one definition, just open it directly
 9918        if definitions.len() == 1 {
 9919            let definition = definitions.pop().unwrap();
 9920
 9921            enum TargetTaskResult {
 9922                Location(Option<Location>),
 9923                AlreadyNavigated,
 9924            }
 9925
 9926            let target_task = match definition {
 9927                HoverLink::Text(link) => {
 9928                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9929                }
 9930                HoverLink::InlayHint(lsp_location, server_id) => {
 9931                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9932                    cx.background_executor().spawn(async move {
 9933                        let location = computation.await?;
 9934                        Ok(TargetTaskResult::Location(location))
 9935                    })
 9936                }
 9937                HoverLink::Url(url) => {
 9938                    cx.open_url(&url);
 9939                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9940                }
 9941                HoverLink::File(path) => {
 9942                    if let Some(workspace) = self.workspace() {
 9943                        cx.spawn(|_, mut cx| async move {
 9944                            workspace
 9945                                .update(&mut cx, |workspace, cx| {
 9946                                    workspace.open_resolved_path(path, cx)
 9947                                })?
 9948                                .await
 9949                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9950                        })
 9951                    } else {
 9952                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9953                    }
 9954                }
 9955            };
 9956            cx.spawn(|editor, mut cx| async move {
 9957                let target = match target_task.await.context("target resolution task")? {
 9958                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9959                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9960                    TargetTaskResult::Location(Some(target)) => target,
 9961                };
 9962
 9963                editor.update(&mut cx, |editor, cx| {
 9964                    let Some(workspace) = editor.workspace() else {
 9965                        return Navigated::No;
 9966                    };
 9967                    let pane = workspace.read(cx).active_pane().clone();
 9968
 9969                    let range = target.range.to_offset(target.buffer.read(cx));
 9970                    let range = editor.range_for_match(&range);
 9971
 9972                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9973                        let buffer = target.buffer.read(cx);
 9974                        let range = check_multiline_range(buffer, range);
 9975                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9976                            s.select_ranges([range]);
 9977                        });
 9978                    } else {
 9979                        cx.window_context().defer(move |cx| {
 9980                            let target_editor: View<Self> =
 9981                                workspace.update(cx, |workspace, cx| {
 9982                                    let pane = if split {
 9983                                        workspace.adjacent_pane(cx)
 9984                                    } else {
 9985                                        workspace.active_pane().clone()
 9986                                    };
 9987
 9988                                    workspace.open_project_item(
 9989                                        pane,
 9990                                        target.buffer.clone(),
 9991                                        true,
 9992                                        true,
 9993                                        cx,
 9994                                    )
 9995                                });
 9996                            target_editor.update(cx, |target_editor, cx| {
 9997                                // When selecting a definition in a different buffer, disable the nav history
 9998                                // to avoid creating a history entry at the previous cursor location.
 9999                                pane.update(cx, |pane, _| pane.disable_history());
10000                                let buffer = target.buffer.read(cx);
10001                                let range = check_multiline_range(buffer, range);
10002                                target_editor.change_selections(
10003                                    Some(Autoscroll::focused()),
10004                                    cx,
10005                                    |s| {
10006                                        s.select_ranges([range]);
10007                                    },
10008                                );
10009                                pane.update(cx, |pane, _| pane.enable_history());
10010                            });
10011                        });
10012                    }
10013                    Navigated::Yes
10014                })
10015            })
10016        } else if !definitions.is_empty() {
10017            cx.spawn(|editor, mut cx| async move {
10018                let (title, location_tasks, workspace) = editor
10019                    .update(&mut cx, |editor, cx| {
10020                        let tab_kind = match kind {
10021                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10022                            _ => "Definitions",
10023                        };
10024                        let title = definitions
10025                            .iter()
10026                            .find_map(|definition| match definition {
10027                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10028                                    let buffer = origin.buffer.read(cx);
10029                                    format!(
10030                                        "{} for {}",
10031                                        tab_kind,
10032                                        buffer
10033                                            .text_for_range(origin.range.clone())
10034                                            .collect::<String>()
10035                                    )
10036                                }),
10037                                HoverLink::InlayHint(_, _) => None,
10038                                HoverLink::Url(_) => None,
10039                                HoverLink::File(_) => None,
10040                            })
10041                            .unwrap_or(tab_kind.to_string());
10042                        let location_tasks = definitions
10043                            .into_iter()
10044                            .map(|definition| match definition {
10045                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10046                                HoverLink::InlayHint(lsp_location, server_id) => {
10047                                    editor.compute_target_location(lsp_location, server_id, cx)
10048                                }
10049                                HoverLink::Url(_) => Task::ready(Ok(None)),
10050                                HoverLink::File(_) => Task::ready(Ok(None)),
10051                            })
10052                            .collect::<Vec<_>>();
10053                        (title, location_tasks, editor.workspace().clone())
10054                    })
10055                    .context("location tasks preparation")?;
10056
10057                let locations = future::join_all(location_tasks)
10058                    .await
10059                    .into_iter()
10060                    .filter_map(|location| location.transpose())
10061                    .collect::<Result<_>>()
10062                    .context("location tasks")?;
10063
10064                let Some(workspace) = workspace else {
10065                    return Ok(Navigated::No);
10066                };
10067                let opened = workspace
10068                    .update(&mut cx, |workspace, cx| {
10069                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10070                    })
10071                    .ok();
10072
10073                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10074            })
10075        } else {
10076            Task::ready(Ok(Navigated::No))
10077        }
10078    }
10079
10080    fn compute_target_location(
10081        &self,
10082        lsp_location: lsp::Location,
10083        server_id: LanguageServerId,
10084        cx: &mut ViewContext<Self>,
10085    ) -> Task<anyhow::Result<Option<Location>>> {
10086        let Some(project) = self.project.clone() else {
10087            return Task::Ready(Some(Ok(None)));
10088        };
10089
10090        cx.spawn(move |editor, mut cx| async move {
10091            let location_task = editor.update(&mut cx, |_, cx| {
10092                project.update(cx, |project, cx| {
10093                    let language_server_name = project
10094                        .language_server_statuses(cx)
10095                        .find(|(id, _)| server_id == *id)
10096                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10097                    language_server_name.map(|language_server_name| {
10098                        project.open_local_buffer_via_lsp(
10099                            lsp_location.uri.clone(),
10100                            server_id,
10101                            language_server_name,
10102                            cx,
10103                        )
10104                    })
10105                })
10106            })?;
10107            let location = match location_task {
10108                Some(task) => Some({
10109                    let target_buffer_handle = task.await.context("open local buffer")?;
10110                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10111                        let target_start = target_buffer
10112                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10113                        let target_end = target_buffer
10114                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10115                        target_buffer.anchor_after(target_start)
10116                            ..target_buffer.anchor_before(target_end)
10117                    })?;
10118                    Location {
10119                        buffer: target_buffer_handle,
10120                        range,
10121                    }
10122                }),
10123                None => None,
10124            };
10125            Ok(location)
10126        })
10127    }
10128
10129    pub fn find_all_references(
10130        &mut self,
10131        _: &FindAllReferences,
10132        cx: &mut ViewContext<Self>,
10133    ) -> Option<Task<Result<Navigated>>> {
10134        let selection = self.selections.newest::<usize>(cx);
10135        let multi_buffer = self.buffer.read(cx);
10136        let head = selection.head();
10137
10138        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10139        let head_anchor = multi_buffer_snapshot.anchor_at(
10140            head,
10141            if head < selection.tail() {
10142                Bias::Right
10143            } else {
10144                Bias::Left
10145            },
10146        );
10147
10148        match self
10149            .find_all_references_task_sources
10150            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10151        {
10152            Ok(_) => {
10153                log::info!(
10154                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10155                );
10156                return None;
10157            }
10158            Err(i) => {
10159                self.find_all_references_task_sources.insert(i, head_anchor);
10160            }
10161        }
10162
10163        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10164        let workspace = self.workspace()?;
10165        let project = workspace.read(cx).project().clone();
10166        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10167        Some(cx.spawn(|editor, mut cx| async move {
10168            let _cleanup = defer({
10169                let mut cx = cx.clone();
10170                move || {
10171                    let _ = editor.update(&mut cx, |editor, _| {
10172                        if let Ok(i) =
10173                            editor
10174                                .find_all_references_task_sources
10175                                .binary_search_by(|anchor| {
10176                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10177                                })
10178                        {
10179                            editor.find_all_references_task_sources.remove(i);
10180                        }
10181                    });
10182                }
10183            });
10184
10185            let locations = references.await?;
10186            if locations.is_empty() {
10187                return anyhow::Ok(Navigated::No);
10188            }
10189
10190            workspace.update(&mut cx, |workspace, cx| {
10191                let title = locations
10192                    .first()
10193                    .as_ref()
10194                    .map(|location| {
10195                        let buffer = location.buffer.read(cx);
10196                        format!(
10197                            "References to `{}`",
10198                            buffer
10199                                .text_for_range(location.range.clone())
10200                                .collect::<String>()
10201                        )
10202                    })
10203                    .unwrap();
10204                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10205                Navigated::Yes
10206            })
10207        }))
10208    }
10209
10210    /// Opens a multibuffer with the given project locations in it
10211    pub fn open_locations_in_multibuffer(
10212        workspace: &mut Workspace,
10213        mut locations: Vec<Location>,
10214        title: String,
10215        split: bool,
10216        cx: &mut ViewContext<Workspace>,
10217    ) {
10218        // If there are multiple definitions, open them in a multibuffer
10219        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10220        let mut locations = locations.into_iter().peekable();
10221        let mut ranges_to_highlight = Vec::new();
10222        let capability = workspace.project().read(cx).capability();
10223
10224        let excerpt_buffer = cx.new_model(|cx| {
10225            let mut multibuffer = MultiBuffer::new(capability);
10226            while let Some(location) = locations.next() {
10227                let buffer = location.buffer.read(cx);
10228                let mut ranges_for_buffer = Vec::new();
10229                let range = location.range.to_offset(buffer);
10230                ranges_for_buffer.push(range.clone());
10231
10232                while let Some(next_location) = locations.peek() {
10233                    if next_location.buffer == location.buffer {
10234                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10235                        locations.next();
10236                    } else {
10237                        break;
10238                    }
10239                }
10240
10241                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10242                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10243                    location.buffer.clone(),
10244                    ranges_for_buffer,
10245                    DEFAULT_MULTIBUFFER_CONTEXT,
10246                    cx,
10247                ))
10248            }
10249
10250            multibuffer.with_title(title)
10251        });
10252
10253        let editor = cx.new_view(|cx| {
10254            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10255        });
10256        editor.update(cx, |editor, cx| {
10257            if let Some(first_range) = ranges_to_highlight.first() {
10258                editor.change_selections(None, cx, |selections| {
10259                    selections.clear_disjoint();
10260                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10261                });
10262            }
10263            editor.highlight_background::<Self>(
10264                &ranges_to_highlight,
10265                |theme| theme.editor_highlighted_line_background,
10266                cx,
10267            );
10268        });
10269
10270        let item = Box::new(editor);
10271        let item_id = item.item_id();
10272
10273        if split {
10274            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10275        } else {
10276            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10277                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10278                    pane.close_current_preview_item(cx)
10279                } else {
10280                    None
10281                }
10282            });
10283            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10284        }
10285        workspace.active_pane().update(cx, |pane, cx| {
10286            pane.set_preview_item_id(Some(item_id), cx);
10287        });
10288    }
10289
10290    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10291        use language::ToOffset as _;
10292
10293        let provider = self.semantics_provider.clone()?;
10294        let selection = self.selections.newest_anchor().clone();
10295        let (cursor_buffer, cursor_buffer_position) = self
10296            .buffer
10297            .read(cx)
10298            .text_anchor_for_position(selection.head(), cx)?;
10299        let (tail_buffer, cursor_buffer_position_end) = self
10300            .buffer
10301            .read(cx)
10302            .text_anchor_for_position(selection.tail(), cx)?;
10303        if tail_buffer != cursor_buffer {
10304            return None;
10305        }
10306
10307        let snapshot = cursor_buffer.read(cx).snapshot();
10308        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10309        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10310        let prepare_rename = provider
10311            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10312            .unwrap_or_else(|| Task::ready(Ok(None)));
10313        drop(snapshot);
10314
10315        Some(cx.spawn(|this, mut cx| async move {
10316            let rename_range = if let Some(range) = prepare_rename.await? {
10317                Some(range)
10318            } else {
10319                this.update(&mut cx, |this, cx| {
10320                    let buffer = this.buffer.read(cx).snapshot(cx);
10321                    let mut buffer_highlights = this
10322                        .document_highlights_for_position(selection.head(), &buffer)
10323                        .filter(|highlight| {
10324                            highlight.start.excerpt_id == selection.head().excerpt_id
10325                                && highlight.end.excerpt_id == selection.head().excerpt_id
10326                        });
10327                    buffer_highlights
10328                        .next()
10329                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10330                })?
10331            };
10332            if let Some(rename_range) = rename_range {
10333                this.update(&mut cx, |this, cx| {
10334                    let snapshot = cursor_buffer.read(cx).snapshot();
10335                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10336                    let cursor_offset_in_rename_range =
10337                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10338                    let cursor_offset_in_rename_range_end =
10339                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10340
10341                    this.take_rename(false, cx);
10342                    let buffer = this.buffer.read(cx).read(cx);
10343                    let cursor_offset = selection.head().to_offset(&buffer);
10344                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10345                    let rename_end = rename_start + rename_buffer_range.len();
10346                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10347                    let mut old_highlight_id = None;
10348                    let old_name: Arc<str> = buffer
10349                        .chunks(rename_start..rename_end, true)
10350                        .map(|chunk| {
10351                            if old_highlight_id.is_none() {
10352                                old_highlight_id = chunk.syntax_highlight_id;
10353                            }
10354                            chunk.text
10355                        })
10356                        .collect::<String>()
10357                        .into();
10358
10359                    drop(buffer);
10360
10361                    // Position the selection in the rename editor so that it matches the current selection.
10362                    this.show_local_selections = false;
10363                    let rename_editor = cx.new_view(|cx| {
10364                        let mut editor = Editor::single_line(cx);
10365                        editor.buffer.update(cx, |buffer, cx| {
10366                            buffer.edit([(0..0, old_name.clone())], None, cx)
10367                        });
10368                        let rename_selection_range = match cursor_offset_in_rename_range
10369                            .cmp(&cursor_offset_in_rename_range_end)
10370                        {
10371                            Ordering::Equal => {
10372                                editor.select_all(&SelectAll, cx);
10373                                return editor;
10374                            }
10375                            Ordering::Less => {
10376                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10377                            }
10378                            Ordering::Greater => {
10379                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10380                            }
10381                        };
10382                        if rename_selection_range.end > old_name.len() {
10383                            editor.select_all(&SelectAll, cx);
10384                        } else {
10385                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10386                                s.select_ranges([rename_selection_range]);
10387                            });
10388                        }
10389                        editor
10390                    });
10391                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10392                        if e == &EditorEvent::Focused {
10393                            cx.emit(EditorEvent::FocusedIn)
10394                        }
10395                    })
10396                    .detach();
10397
10398                    let write_highlights =
10399                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10400                    let read_highlights =
10401                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10402                    let ranges = write_highlights
10403                        .iter()
10404                        .flat_map(|(_, ranges)| ranges.iter())
10405                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10406                        .cloned()
10407                        .collect();
10408
10409                    this.highlight_text::<Rename>(
10410                        ranges,
10411                        HighlightStyle {
10412                            fade_out: Some(0.6),
10413                            ..Default::default()
10414                        },
10415                        cx,
10416                    );
10417                    let rename_focus_handle = rename_editor.focus_handle(cx);
10418                    cx.focus(&rename_focus_handle);
10419                    let block_id = this.insert_blocks(
10420                        [BlockProperties {
10421                            style: BlockStyle::Flex,
10422                            placement: BlockPlacement::Below(range.start),
10423                            height: 1,
10424                            render: Arc::new({
10425                                let rename_editor = rename_editor.clone();
10426                                move |cx: &mut BlockContext| {
10427                                    let mut text_style = cx.editor_style.text.clone();
10428                                    if let Some(highlight_style) = old_highlight_id
10429                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10430                                    {
10431                                        text_style = text_style.highlight(highlight_style);
10432                                    }
10433                                    div()
10434                                        .block_mouse_down()
10435                                        .pl(cx.anchor_x)
10436                                        .child(EditorElement::new(
10437                                            &rename_editor,
10438                                            EditorStyle {
10439                                                background: cx.theme().system().transparent,
10440                                                local_player: cx.editor_style.local_player,
10441                                                text: text_style,
10442                                                scrollbar_width: cx.editor_style.scrollbar_width,
10443                                                syntax: cx.editor_style.syntax.clone(),
10444                                                status: cx.editor_style.status.clone(),
10445                                                inlay_hints_style: HighlightStyle {
10446                                                    font_weight: Some(FontWeight::BOLD),
10447                                                    ..make_inlay_hints_style(cx)
10448                                                },
10449                                                suggestions_style: HighlightStyle {
10450                                                    color: Some(cx.theme().status().predictive),
10451                                                    ..HighlightStyle::default()
10452                                                },
10453                                                ..EditorStyle::default()
10454                                            },
10455                                        ))
10456                                        .into_any_element()
10457                                }
10458                            }),
10459                            priority: 0,
10460                        }],
10461                        Some(Autoscroll::fit()),
10462                        cx,
10463                    )[0];
10464                    this.pending_rename = Some(RenameState {
10465                        range,
10466                        old_name,
10467                        editor: rename_editor,
10468                        block_id,
10469                    });
10470                })?;
10471            }
10472
10473            Ok(())
10474        }))
10475    }
10476
10477    pub fn confirm_rename(
10478        &mut self,
10479        _: &ConfirmRename,
10480        cx: &mut ViewContext<Self>,
10481    ) -> Option<Task<Result<()>>> {
10482        let rename = self.take_rename(false, cx)?;
10483        let workspace = self.workspace()?.downgrade();
10484        let (buffer, start) = self
10485            .buffer
10486            .read(cx)
10487            .text_anchor_for_position(rename.range.start, cx)?;
10488        let (end_buffer, _) = self
10489            .buffer
10490            .read(cx)
10491            .text_anchor_for_position(rename.range.end, cx)?;
10492        if buffer != end_buffer {
10493            return None;
10494        }
10495
10496        let old_name = rename.old_name;
10497        let new_name = rename.editor.read(cx).text(cx);
10498
10499        let rename = self.semantics_provider.as_ref()?.perform_rename(
10500            &buffer,
10501            start,
10502            new_name.clone(),
10503            cx,
10504        )?;
10505
10506        Some(cx.spawn(|editor, mut cx| async move {
10507            let project_transaction = rename.await?;
10508            Self::open_project_transaction(
10509                &editor,
10510                workspace,
10511                project_transaction,
10512                format!("Rename: {}{}", old_name, new_name),
10513                cx.clone(),
10514            )
10515            .await?;
10516
10517            editor.update(&mut cx, |editor, cx| {
10518                editor.refresh_document_highlights(cx);
10519            })?;
10520            Ok(())
10521        }))
10522    }
10523
10524    fn take_rename(
10525        &mut self,
10526        moving_cursor: bool,
10527        cx: &mut ViewContext<Self>,
10528    ) -> Option<RenameState> {
10529        let rename = self.pending_rename.take()?;
10530        if rename.editor.focus_handle(cx).is_focused(cx) {
10531            cx.focus(&self.focus_handle);
10532        }
10533
10534        self.remove_blocks(
10535            [rename.block_id].into_iter().collect(),
10536            Some(Autoscroll::fit()),
10537            cx,
10538        );
10539        self.clear_highlights::<Rename>(cx);
10540        self.show_local_selections = true;
10541
10542        if moving_cursor {
10543            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10544                editor.selections.newest::<usize>(cx).head()
10545            });
10546
10547            // Update the selection to match the position of the selection inside
10548            // the rename editor.
10549            let snapshot = self.buffer.read(cx).read(cx);
10550            let rename_range = rename.range.to_offset(&snapshot);
10551            let cursor_in_editor = snapshot
10552                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10553                .min(rename_range.end);
10554            drop(snapshot);
10555
10556            self.change_selections(None, cx, |s| {
10557                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10558            });
10559        } else {
10560            self.refresh_document_highlights(cx);
10561        }
10562
10563        Some(rename)
10564    }
10565
10566    pub fn pending_rename(&self) -> Option<&RenameState> {
10567        self.pending_rename.as_ref()
10568    }
10569
10570    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10571        let project = match &self.project {
10572            Some(project) => project.clone(),
10573            None => return None,
10574        };
10575
10576        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10577    }
10578
10579    fn format_selections(
10580        &mut self,
10581        _: &FormatSelections,
10582        cx: &mut ViewContext<Self>,
10583    ) -> Option<Task<Result<()>>> {
10584        let project = match &self.project {
10585            Some(project) => project.clone(),
10586            None => return None,
10587        };
10588
10589        let selections = self
10590            .selections
10591            .all_adjusted(cx)
10592            .into_iter()
10593            .filter(|s| !s.is_empty())
10594            .collect_vec();
10595
10596        Some(self.perform_format(
10597            project,
10598            FormatTrigger::Manual,
10599            FormatTarget::Ranges(selections),
10600            cx,
10601        ))
10602    }
10603
10604    fn perform_format(
10605        &mut self,
10606        project: Model<Project>,
10607        trigger: FormatTrigger,
10608        target: FormatTarget,
10609        cx: &mut ViewContext<Self>,
10610    ) -> Task<Result<()>> {
10611        let buffer = self.buffer().clone();
10612        let mut buffers = buffer.read(cx).all_buffers();
10613        if trigger == FormatTrigger::Save {
10614            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10615        }
10616
10617        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10618        let format = project.update(cx, |project, cx| {
10619            project.format(buffers, true, trigger, target, cx)
10620        });
10621
10622        cx.spawn(|_, mut cx| async move {
10623            let transaction = futures::select_biased! {
10624                () = timeout => {
10625                    log::warn!("timed out waiting for formatting");
10626                    None
10627                }
10628                transaction = format.log_err().fuse() => transaction,
10629            };
10630
10631            buffer
10632                .update(&mut cx, |buffer, cx| {
10633                    if let Some(transaction) = transaction {
10634                        if !buffer.is_singleton() {
10635                            buffer.push_transaction(&transaction.0, cx);
10636                        }
10637                    }
10638
10639                    cx.notify();
10640                })
10641                .ok();
10642
10643            Ok(())
10644        })
10645    }
10646
10647    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10648        if let Some(project) = self.project.clone() {
10649            self.buffer.update(cx, |multi_buffer, cx| {
10650                project.update(cx, |project, cx| {
10651                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10652                });
10653            })
10654        }
10655    }
10656
10657    fn cancel_language_server_work(
10658        &mut self,
10659        _: &actions::CancelLanguageServerWork,
10660        cx: &mut ViewContext<Self>,
10661    ) {
10662        if let Some(project) = self.project.clone() {
10663            self.buffer.update(cx, |multi_buffer, cx| {
10664                project.update(cx, |project, cx| {
10665                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10666                });
10667            })
10668        }
10669    }
10670
10671    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10672        cx.show_character_palette();
10673    }
10674
10675    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10676        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10677            let buffer = self.buffer.read(cx).snapshot(cx);
10678            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10679            let is_valid = buffer
10680                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10681                .any(|entry| {
10682                    entry.diagnostic.is_primary
10683                        && !entry.range.is_empty()
10684                        && entry.range.start == primary_range_start
10685                        && entry.diagnostic.message == active_diagnostics.primary_message
10686                });
10687
10688            if is_valid != active_diagnostics.is_valid {
10689                active_diagnostics.is_valid = is_valid;
10690                let mut new_styles = HashMap::default();
10691                for (block_id, diagnostic) in &active_diagnostics.blocks {
10692                    new_styles.insert(
10693                        *block_id,
10694                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10695                    );
10696                }
10697                self.display_map.update(cx, |display_map, _cx| {
10698                    display_map.replace_blocks(new_styles)
10699                });
10700            }
10701        }
10702    }
10703
10704    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10705        self.dismiss_diagnostics(cx);
10706        let snapshot = self.snapshot(cx);
10707        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10708            let buffer = self.buffer.read(cx).snapshot(cx);
10709
10710            let mut primary_range = None;
10711            let mut primary_message = None;
10712            let mut group_end = Point::zero();
10713            let diagnostic_group = buffer
10714                .diagnostic_group::<MultiBufferPoint>(group_id)
10715                .filter_map(|entry| {
10716                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10717                        && (entry.range.start.row == entry.range.end.row
10718                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10719                    {
10720                        return None;
10721                    }
10722                    if entry.range.end > group_end {
10723                        group_end = entry.range.end;
10724                    }
10725                    if entry.diagnostic.is_primary {
10726                        primary_range = Some(entry.range.clone());
10727                        primary_message = Some(entry.diagnostic.message.clone());
10728                    }
10729                    Some(entry)
10730                })
10731                .collect::<Vec<_>>();
10732            let primary_range = primary_range?;
10733            let primary_message = primary_message?;
10734            let primary_range =
10735                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10736
10737            let blocks = display_map
10738                .insert_blocks(
10739                    diagnostic_group.iter().map(|entry| {
10740                        let diagnostic = entry.diagnostic.clone();
10741                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10742                        BlockProperties {
10743                            style: BlockStyle::Fixed,
10744                            placement: BlockPlacement::Below(
10745                                buffer.anchor_after(entry.range.start),
10746                            ),
10747                            height: message_height,
10748                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10749                            priority: 0,
10750                        }
10751                    }),
10752                    cx,
10753                )
10754                .into_iter()
10755                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10756                .collect();
10757
10758            Some(ActiveDiagnosticGroup {
10759                primary_range,
10760                primary_message,
10761                group_id,
10762                blocks,
10763                is_valid: true,
10764            })
10765        });
10766        self.active_diagnostics.is_some()
10767    }
10768
10769    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10770        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10771            self.display_map.update(cx, |display_map, cx| {
10772                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10773            });
10774            cx.notify();
10775        }
10776    }
10777
10778    pub fn set_selections_from_remote(
10779        &mut self,
10780        selections: Vec<Selection<Anchor>>,
10781        pending_selection: Option<Selection<Anchor>>,
10782        cx: &mut ViewContext<Self>,
10783    ) {
10784        let old_cursor_position = self.selections.newest_anchor().head();
10785        self.selections.change_with(cx, |s| {
10786            s.select_anchors(selections);
10787            if let Some(pending_selection) = pending_selection {
10788                s.set_pending(pending_selection, SelectMode::Character);
10789            } else {
10790                s.clear_pending();
10791            }
10792        });
10793        self.selections_did_change(false, &old_cursor_position, true, cx);
10794    }
10795
10796    fn push_to_selection_history(&mut self) {
10797        self.selection_history.push(SelectionHistoryEntry {
10798            selections: self.selections.disjoint_anchors(),
10799            select_next_state: self.select_next_state.clone(),
10800            select_prev_state: self.select_prev_state.clone(),
10801            add_selections_state: self.add_selections_state.clone(),
10802        });
10803    }
10804
10805    pub fn transact(
10806        &mut self,
10807        cx: &mut ViewContext<Self>,
10808        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10809    ) -> Option<TransactionId> {
10810        self.start_transaction_at(Instant::now(), cx);
10811        update(self, cx);
10812        self.end_transaction_at(Instant::now(), cx)
10813    }
10814
10815    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10816        self.end_selection(cx);
10817        if let Some(tx_id) = self
10818            .buffer
10819            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10820        {
10821            self.selection_history
10822                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10823            cx.emit(EditorEvent::TransactionBegun {
10824                transaction_id: tx_id,
10825            })
10826        }
10827    }
10828
10829    fn end_transaction_at(
10830        &mut self,
10831        now: Instant,
10832        cx: &mut ViewContext<Self>,
10833    ) -> Option<TransactionId> {
10834        if let Some(transaction_id) = self
10835            .buffer
10836            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10837        {
10838            if let Some((_, end_selections)) =
10839                self.selection_history.transaction_mut(transaction_id)
10840            {
10841                *end_selections = Some(self.selections.disjoint_anchors());
10842            } else {
10843                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10844            }
10845
10846            cx.emit(EditorEvent::Edited { transaction_id });
10847            Some(transaction_id)
10848        } else {
10849            None
10850        }
10851    }
10852
10853    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10854        let selection = self.selections.newest::<Point>(cx);
10855
10856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10857        let range = if selection.is_empty() {
10858            let point = selection.head().to_display_point(&display_map);
10859            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10860            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10861                .to_point(&display_map);
10862            start..end
10863        } else {
10864            selection.range()
10865        };
10866        if display_map.folds_in_range(range).next().is_some() {
10867            self.unfold_lines(&Default::default(), cx)
10868        } else {
10869            self.fold(&Default::default(), cx)
10870        }
10871    }
10872
10873    pub fn toggle_fold_recursive(
10874        &mut self,
10875        _: &actions::ToggleFoldRecursive,
10876        cx: &mut ViewContext<Self>,
10877    ) {
10878        let selection = self.selections.newest::<Point>(cx);
10879
10880        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10881        let range = if selection.is_empty() {
10882            let point = selection.head().to_display_point(&display_map);
10883            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10884            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10885                .to_point(&display_map);
10886            start..end
10887        } else {
10888            selection.range()
10889        };
10890        if display_map.folds_in_range(range).next().is_some() {
10891            self.unfold_recursive(&Default::default(), cx)
10892        } else {
10893            self.fold_recursive(&Default::default(), cx)
10894        }
10895    }
10896
10897    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10898        let mut to_fold = Vec::new();
10899        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10900        let selections = self.selections.all_adjusted(cx);
10901
10902        for selection in selections {
10903            let range = selection.range().sorted();
10904            let buffer_start_row = range.start.row;
10905
10906            if range.start.row != range.end.row {
10907                let mut found = false;
10908                let mut row = range.start.row;
10909                while row <= range.end.row {
10910                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10911                        found = true;
10912                        row = crease.range().end.row + 1;
10913                        to_fold.push(crease);
10914                    } else {
10915                        row += 1
10916                    }
10917                }
10918                if found {
10919                    continue;
10920                }
10921            }
10922
10923            for row in (0..=range.start.row).rev() {
10924                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10925                    if crease.range().end.row >= buffer_start_row {
10926                        to_fold.push(crease);
10927                        if row <= range.start.row {
10928                            break;
10929                        }
10930                    }
10931                }
10932            }
10933        }
10934
10935        self.fold_creases(to_fold, true, cx);
10936    }
10937
10938    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10939        let fold_at_level = fold_at.level;
10940        let snapshot = self.buffer.read(cx).snapshot(cx);
10941        let mut to_fold = Vec::new();
10942        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10943
10944        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10945            while start_row < end_row {
10946                match self
10947                    .snapshot(cx)
10948                    .crease_for_buffer_row(MultiBufferRow(start_row))
10949                {
10950                    Some(crease) => {
10951                        let nested_start_row = crease.range().start.row + 1;
10952                        let nested_end_row = crease.range().end.row;
10953
10954                        if current_level < fold_at_level {
10955                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10956                        } else if current_level == fold_at_level {
10957                            to_fold.push(crease);
10958                        }
10959
10960                        start_row = nested_end_row + 1;
10961                    }
10962                    None => start_row += 1,
10963                }
10964            }
10965        }
10966
10967        self.fold_creases(to_fold, true, cx);
10968    }
10969
10970    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10971        let mut fold_ranges = Vec::new();
10972        let snapshot = self.buffer.read(cx).snapshot(cx);
10973
10974        for row in 0..snapshot.max_buffer_row().0 {
10975            if let Some(foldable_range) =
10976                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10977            {
10978                fold_ranges.push(foldable_range);
10979            }
10980        }
10981
10982        self.fold_creases(fold_ranges, true, cx);
10983    }
10984
10985    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10986        let mut to_fold = Vec::new();
10987        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10988        let selections = self.selections.all_adjusted(cx);
10989
10990        for selection in selections {
10991            let range = selection.range().sorted();
10992            let buffer_start_row = range.start.row;
10993
10994            if range.start.row != range.end.row {
10995                let mut found = false;
10996                for row in range.start.row..=range.end.row {
10997                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10998                        found = true;
10999                        to_fold.push(crease);
11000                    }
11001                }
11002                if found {
11003                    continue;
11004                }
11005            }
11006
11007            for row in (0..=range.start.row).rev() {
11008                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11009                    if crease.range().end.row >= buffer_start_row {
11010                        to_fold.push(crease);
11011                    } else {
11012                        break;
11013                    }
11014                }
11015            }
11016        }
11017
11018        self.fold_creases(to_fold, true, cx);
11019    }
11020
11021    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11022        let buffer_row = fold_at.buffer_row;
11023        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11024
11025        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11026            let autoscroll = self
11027                .selections
11028                .all::<Point>(cx)
11029                .iter()
11030                .any(|selection| crease.range().overlaps(&selection.range()));
11031
11032            self.fold_creases(vec![crease], autoscroll, cx);
11033        }
11034    }
11035
11036    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11037        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11038        let buffer = &display_map.buffer_snapshot;
11039        let selections = self.selections.all::<Point>(cx);
11040        let ranges = selections
11041            .iter()
11042            .map(|s| {
11043                let range = s.display_range(&display_map).sorted();
11044                let mut start = range.start.to_point(&display_map);
11045                let mut end = range.end.to_point(&display_map);
11046                start.column = 0;
11047                end.column = buffer.line_len(MultiBufferRow(end.row));
11048                start..end
11049            })
11050            .collect::<Vec<_>>();
11051
11052        self.unfold_ranges(&ranges, true, true, cx);
11053    }
11054
11055    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11056        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11057        let selections = self.selections.all::<Point>(cx);
11058        let ranges = selections
11059            .iter()
11060            .map(|s| {
11061                let mut range = s.display_range(&display_map).sorted();
11062                *range.start.column_mut() = 0;
11063                *range.end.column_mut() = display_map.line_len(range.end.row());
11064                let start = range.start.to_point(&display_map);
11065                let end = range.end.to_point(&display_map);
11066                start..end
11067            })
11068            .collect::<Vec<_>>();
11069
11070        self.unfold_ranges(&ranges, true, true, cx);
11071    }
11072
11073    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11074        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11075
11076        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11077            ..Point::new(
11078                unfold_at.buffer_row.0,
11079                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11080            );
11081
11082        let autoscroll = self
11083            .selections
11084            .all::<Point>(cx)
11085            .iter()
11086            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11087
11088        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11089    }
11090
11091    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11092        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11093        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11094    }
11095
11096    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11097        let selections = self.selections.all::<Point>(cx);
11098        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11099        let line_mode = self.selections.line_mode;
11100        let ranges = selections
11101            .into_iter()
11102            .map(|s| {
11103                if line_mode {
11104                    let start = Point::new(s.start.row, 0);
11105                    let end = Point::new(
11106                        s.end.row,
11107                        display_map
11108                            .buffer_snapshot
11109                            .line_len(MultiBufferRow(s.end.row)),
11110                    );
11111                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11112                } else {
11113                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11114                }
11115            })
11116            .collect::<Vec<_>>();
11117        self.fold_creases(ranges, true, cx);
11118    }
11119
11120    pub fn fold_creases<T: ToOffset + Clone>(
11121        &mut self,
11122        creases: Vec<Crease<T>>,
11123        auto_scroll: bool,
11124        cx: &mut ViewContext<Self>,
11125    ) {
11126        if creases.is_empty() {
11127            return;
11128        }
11129
11130        let mut buffers_affected = HashMap::default();
11131        let multi_buffer = self.buffer().read(cx);
11132        for crease in &creases {
11133            if let Some((_, buffer, _)) =
11134                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11135            {
11136                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11137            };
11138        }
11139
11140        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11141
11142        if auto_scroll {
11143            self.request_autoscroll(Autoscroll::fit(), cx);
11144        }
11145
11146        for buffer in buffers_affected.into_values() {
11147            self.sync_expanded_diff_hunks(buffer, cx);
11148        }
11149
11150        cx.notify();
11151
11152        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11153            // Clear diagnostics block when folding a range that contains it.
11154            let snapshot = self.snapshot(cx);
11155            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11156                drop(snapshot);
11157                self.active_diagnostics = Some(active_diagnostics);
11158                self.dismiss_diagnostics(cx);
11159            } else {
11160                self.active_diagnostics = Some(active_diagnostics);
11161            }
11162        }
11163
11164        self.scrollbar_marker_state.dirty = true;
11165    }
11166
11167    /// Removes any folds whose ranges intersect any of the given ranges.
11168    pub fn unfold_ranges<T: ToOffset + Clone>(
11169        &mut self,
11170        ranges: &[Range<T>],
11171        inclusive: bool,
11172        auto_scroll: bool,
11173        cx: &mut ViewContext<Self>,
11174    ) {
11175        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11176            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11177        });
11178    }
11179
11180    /// Removes any folds with the given ranges.
11181    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11182        &mut self,
11183        ranges: &[Range<T>],
11184        type_id: TypeId,
11185        auto_scroll: bool,
11186        cx: &mut ViewContext<Self>,
11187    ) {
11188        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11189            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11190        });
11191    }
11192
11193    fn remove_folds_with<T: ToOffset + Clone>(
11194        &mut self,
11195        ranges: &[Range<T>],
11196        auto_scroll: bool,
11197        cx: &mut ViewContext<Self>,
11198        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11199    ) {
11200        if ranges.is_empty() {
11201            return;
11202        }
11203
11204        let mut buffers_affected = HashMap::default();
11205        let multi_buffer = self.buffer().read(cx);
11206        for range in ranges {
11207            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11208                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11209            };
11210        }
11211
11212        self.display_map.update(cx, update);
11213
11214        if auto_scroll {
11215            self.request_autoscroll(Autoscroll::fit(), cx);
11216        }
11217
11218        for buffer in buffers_affected.into_values() {
11219            self.sync_expanded_diff_hunks(buffer, cx);
11220        }
11221
11222        cx.notify();
11223        self.scrollbar_marker_state.dirty = true;
11224        self.active_indent_guides_state.dirty = true;
11225    }
11226
11227    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11228        self.display_map.read(cx).fold_placeholder.clone()
11229    }
11230
11231    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11232        if hovered != self.gutter_hovered {
11233            self.gutter_hovered = hovered;
11234            cx.notify();
11235        }
11236    }
11237
11238    pub fn insert_blocks(
11239        &mut self,
11240        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11241        autoscroll: Option<Autoscroll>,
11242        cx: &mut ViewContext<Self>,
11243    ) -> Vec<CustomBlockId> {
11244        let blocks = self
11245            .display_map
11246            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11247        if let Some(autoscroll) = autoscroll {
11248            self.request_autoscroll(autoscroll, cx);
11249        }
11250        cx.notify();
11251        blocks
11252    }
11253
11254    pub fn resize_blocks(
11255        &mut self,
11256        heights: HashMap<CustomBlockId, u32>,
11257        autoscroll: Option<Autoscroll>,
11258        cx: &mut ViewContext<Self>,
11259    ) {
11260        self.display_map
11261            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11262        if let Some(autoscroll) = autoscroll {
11263            self.request_autoscroll(autoscroll, cx);
11264        }
11265        cx.notify();
11266    }
11267
11268    pub fn replace_blocks(
11269        &mut self,
11270        renderers: HashMap<CustomBlockId, RenderBlock>,
11271        autoscroll: Option<Autoscroll>,
11272        cx: &mut ViewContext<Self>,
11273    ) {
11274        self.display_map
11275            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11276        if let Some(autoscroll) = autoscroll {
11277            self.request_autoscroll(autoscroll, cx);
11278        }
11279        cx.notify();
11280    }
11281
11282    pub fn remove_blocks(
11283        &mut self,
11284        block_ids: HashSet<CustomBlockId>,
11285        autoscroll: Option<Autoscroll>,
11286        cx: &mut ViewContext<Self>,
11287    ) {
11288        self.display_map.update(cx, |display_map, cx| {
11289            display_map.remove_blocks(block_ids, cx)
11290        });
11291        if let Some(autoscroll) = autoscroll {
11292            self.request_autoscroll(autoscroll, cx);
11293        }
11294        cx.notify();
11295    }
11296
11297    pub fn row_for_block(
11298        &self,
11299        block_id: CustomBlockId,
11300        cx: &mut ViewContext<Self>,
11301    ) -> Option<DisplayRow> {
11302        self.display_map
11303            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11304    }
11305
11306    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11307        self.focused_block = Some(focused_block);
11308    }
11309
11310    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11311        self.focused_block.take()
11312    }
11313
11314    pub fn insert_creases(
11315        &mut self,
11316        creases: impl IntoIterator<Item = Crease<Anchor>>,
11317        cx: &mut ViewContext<Self>,
11318    ) -> Vec<CreaseId> {
11319        self.display_map
11320            .update(cx, |map, cx| map.insert_creases(creases, cx))
11321    }
11322
11323    pub fn remove_creases(
11324        &mut self,
11325        ids: impl IntoIterator<Item = CreaseId>,
11326        cx: &mut ViewContext<Self>,
11327    ) {
11328        self.display_map
11329            .update(cx, |map, cx| map.remove_creases(ids, cx));
11330    }
11331
11332    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11333        self.display_map
11334            .update(cx, |map, cx| map.snapshot(cx))
11335            .longest_row()
11336    }
11337
11338    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11339        self.display_map
11340            .update(cx, |map, cx| map.snapshot(cx))
11341            .max_point()
11342    }
11343
11344    pub fn text(&self, cx: &AppContext) -> String {
11345        self.buffer.read(cx).read(cx).text()
11346    }
11347
11348    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11349        let text = self.text(cx);
11350        let text = text.trim();
11351
11352        if text.is_empty() {
11353            return None;
11354        }
11355
11356        Some(text.to_string())
11357    }
11358
11359    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11360        self.transact(cx, |this, cx| {
11361            this.buffer
11362                .read(cx)
11363                .as_singleton()
11364                .expect("you can only call set_text on editors for singleton buffers")
11365                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11366        });
11367    }
11368
11369    pub fn display_text(&self, cx: &mut AppContext) -> String {
11370        self.display_map
11371            .update(cx, |map, cx| map.snapshot(cx))
11372            .text()
11373    }
11374
11375    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11376        let mut wrap_guides = smallvec::smallvec![];
11377
11378        if self.show_wrap_guides == Some(false) {
11379            return wrap_guides;
11380        }
11381
11382        let settings = self.buffer.read(cx).settings_at(0, cx);
11383        if settings.show_wrap_guides {
11384            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11385                wrap_guides.push((soft_wrap as usize, true));
11386            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11387                wrap_guides.push((soft_wrap as usize, true));
11388            }
11389            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11390        }
11391
11392        wrap_guides
11393    }
11394
11395    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11396        let settings = self.buffer.read(cx).settings_at(0, cx);
11397        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11398        match mode {
11399            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11400                SoftWrap::None
11401            }
11402            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11403            language_settings::SoftWrap::PreferredLineLength => {
11404                SoftWrap::Column(settings.preferred_line_length)
11405            }
11406            language_settings::SoftWrap::Bounded => {
11407                SoftWrap::Bounded(settings.preferred_line_length)
11408            }
11409        }
11410    }
11411
11412    pub fn set_soft_wrap_mode(
11413        &mut self,
11414        mode: language_settings::SoftWrap,
11415        cx: &mut ViewContext<Self>,
11416    ) {
11417        self.soft_wrap_mode_override = Some(mode);
11418        cx.notify();
11419    }
11420
11421    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11422        self.text_style_refinement = Some(style);
11423    }
11424
11425    /// called by the Element so we know what style we were most recently rendered with.
11426    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11427        let rem_size = cx.rem_size();
11428        self.display_map.update(cx, |map, cx| {
11429            map.set_font(
11430                style.text.font(),
11431                style.text.font_size.to_pixels(rem_size),
11432                cx,
11433            )
11434        });
11435        self.style = Some(style);
11436    }
11437
11438    pub fn style(&self) -> Option<&EditorStyle> {
11439        self.style.as_ref()
11440    }
11441
11442    // Called by the element. This method is not designed to be called outside of the editor
11443    // element's layout code because it does not notify when rewrapping is computed synchronously.
11444    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11445        self.display_map
11446            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11447    }
11448
11449    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11450        if self.soft_wrap_mode_override.is_some() {
11451            self.soft_wrap_mode_override.take();
11452        } else {
11453            let soft_wrap = match self.soft_wrap_mode(cx) {
11454                SoftWrap::GitDiff => return,
11455                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11456                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11457                    language_settings::SoftWrap::None
11458                }
11459            };
11460            self.soft_wrap_mode_override = Some(soft_wrap);
11461        }
11462        cx.notify();
11463    }
11464
11465    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11466        let Some(workspace) = self.workspace() else {
11467            return;
11468        };
11469        let fs = workspace.read(cx).app_state().fs.clone();
11470        let current_show = TabBarSettings::get_global(cx).show;
11471        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11472            setting.show = Some(!current_show);
11473        });
11474    }
11475
11476    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11477        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11478            self.buffer
11479                .read(cx)
11480                .settings_at(0, cx)
11481                .indent_guides
11482                .enabled
11483        });
11484        self.show_indent_guides = Some(!currently_enabled);
11485        cx.notify();
11486    }
11487
11488    fn should_show_indent_guides(&self) -> Option<bool> {
11489        self.show_indent_guides
11490    }
11491
11492    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11493        let mut editor_settings = EditorSettings::get_global(cx).clone();
11494        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11495        EditorSettings::override_global(editor_settings, cx);
11496    }
11497
11498    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11499        self.use_relative_line_numbers
11500            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11501    }
11502
11503    pub fn toggle_relative_line_numbers(
11504        &mut self,
11505        _: &ToggleRelativeLineNumbers,
11506        cx: &mut ViewContext<Self>,
11507    ) {
11508        let is_relative = self.should_use_relative_line_numbers(cx);
11509        self.set_relative_line_number(Some(!is_relative), cx)
11510    }
11511
11512    pub fn set_relative_line_number(
11513        &mut self,
11514        is_relative: Option<bool>,
11515        cx: &mut ViewContext<Self>,
11516    ) {
11517        self.use_relative_line_numbers = is_relative;
11518        cx.notify();
11519    }
11520
11521    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11522        self.show_gutter = show_gutter;
11523        cx.notify();
11524    }
11525
11526    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11527        self.show_line_numbers = Some(show_line_numbers);
11528        cx.notify();
11529    }
11530
11531    pub fn set_show_git_diff_gutter(
11532        &mut self,
11533        show_git_diff_gutter: bool,
11534        cx: &mut ViewContext<Self>,
11535    ) {
11536        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11537        cx.notify();
11538    }
11539
11540    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11541        self.show_code_actions = Some(show_code_actions);
11542        cx.notify();
11543    }
11544
11545    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11546        self.show_runnables = Some(show_runnables);
11547        cx.notify();
11548    }
11549
11550    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11551        if self.display_map.read(cx).masked != masked {
11552            self.display_map.update(cx, |map, _| map.masked = masked);
11553        }
11554        cx.notify()
11555    }
11556
11557    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11558        self.show_wrap_guides = Some(show_wrap_guides);
11559        cx.notify();
11560    }
11561
11562    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11563        self.show_indent_guides = Some(show_indent_guides);
11564        cx.notify();
11565    }
11566
11567    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11568        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11569            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11570                if let Some(dir) = file.abs_path(cx).parent() {
11571                    return Some(dir.to_owned());
11572                }
11573            }
11574
11575            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11576                return Some(project_path.path.to_path_buf());
11577            }
11578        }
11579
11580        None
11581    }
11582
11583    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11584        self.active_excerpt(cx)?
11585            .1
11586            .read(cx)
11587            .file()
11588            .and_then(|f| f.as_local())
11589    }
11590
11591    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11592        if let Some(target) = self.target_file(cx) {
11593            cx.reveal_path(&target.abs_path(cx));
11594        }
11595    }
11596
11597    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11598        if let Some(file) = self.target_file(cx) {
11599            if let Some(path) = file.abs_path(cx).to_str() {
11600                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11601            }
11602        }
11603    }
11604
11605    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11606        if let Some(file) = self.target_file(cx) {
11607            if let Some(path) = file.path().to_str() {
11608                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11609            }
11610        }
11611    }
11612
11613    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11614        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11615
11616        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11617            self.start_git_blame(true, cx);
11618        }
11619
11620        cx.notify();
11621    }
11622
11623    pub fn toggle_git_blame_inline(
11624        &mut self,
11625        _: &ToggleGitBlameInline,
11626        cx: &mut ViewContext<Self>,
11627    ) {
11628        self.toggle_git_blame_inline_internal(true, cx);
11629        cx.notify();
11630    }
11631
11632    pub fn git_blame_inline_enabled(&self) -> bool {
11633        self.git_blame_inline_enabled
11634    }
11635
11636    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11637        self.show_selection_menu = self
11638            .show_selection_menu
11639            .map(|show_selections_menu| !show_selections_menu)
11640            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11641
11642        cx.notify();
11643    }
11644
11645    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11646        self.show_selection_menu
11647            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11648    }
11649
11650    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11651        if let Some(project) = self.project.as_ref() {
11652            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11653                return;
11654            };
11655
11656            if buffer.read(cx).file().is_none() {
11657                return;
11658            }
11659
11660            let focused = self.focus_handle(cx).contains_focused(cx);
11661
11662            let project = project.clone();
11663            let blame =
11664                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11665            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11666            self.blame = Some(blame);
11667        }
11668    }
11669
11670    fn toggle_git_blame_inline_internal(
11671        &mut self,
11672        user_triggered: bool,
11673        cx: &mut ViewContext<Self>,
11674    ) {
11675        if self.git_blame_inline_enabled {
11676            self.git_blame_inline_enabled = false;
11677            self.show_git_blame_inline = false;
11678            self.show_git_blame_inline_delay_task.take();
11679        } else {
11680            self.git_blame_inline_enabled = true;
11681            self.start_git_blame_inline(user_triggered, cx);
11682        }
11683
11684        cx.notify();
11685    }
11686
11687    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11688        self.start_git_blame(user_triggered, cx);
11689
11690        if ProjectSettings::get_global(cx)
11691            .git
11692            .inline_blame_delay()
11693            .is_some()
11694        {
11695            self.start_inline_blame_timer(cx);
11696        } else {
11697            self.show_git_blame_inline = true
11698        }
11699    }
11700
11701    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11702        self.blame.as_ref()
11703    }
11704
11705    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11706        self.show_git_blame_gutter && self.has_blame_entries(cx)
11707    }
11708
11709    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11710        self.show_git_blame_inline
11711            && self.focus_handle.is_focused(cx)
11712            && !self.newest_selection_head_on_empty_line(cx)
11713            && self.has_blame_entries(cx)
11714    }
11715
11716    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11717        self.blame()
11718            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11719    }
11720
11721    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11722        let cursor_anchor = self.selections.newest_anchor().head();
11723
11724        let snapshot = self.buffer.read(cx).snapshot(cx);
11725        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11726
11727        snapshot.line_len(buffer_row) == 0
11728    }
11729
11730    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11731        let buffer_and_selection = maybe!({
11732            let selection = self.selections.newest::<Point>(cx);
11733            let selection_range = selection.range();
11734
11735            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11736                (buffer, selection_range.start.row..selection_range.end.row)
11737            } else {
11738                let buffer_ranges = self
11739                    .buffer()
11740                    .read(cx)
11741                    .range_to_buffer_ranges(selection_range, cx);
11742
11743                let (buffer, range, _) = if selection.reversed {
11744                    buffer_ranges.first()
11745                } else {
11746                    buffer_ranges.last()
11747                }?;
11748
11749                let snapshot = buffer.read(cx).snapshot();
11750                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11751                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11752                (buffer.clone(), selection)
11753            };
11754
11755            Some((buffer, selection))
11756        });
11757
11758        let Some((buffer, selection)) = buffer_and_selection else {
11759            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11760        };
11761
11762        let Some(project) = self.project.as_ref() else {
11763            return Task::ready(Err(anyhow!("editor does not have project")));
11764        };
11765
11766        project.update(cx, |project, cx| {
11767            project.get_permalink_to_line(&buffer, selection, cx)
11768        })
11769    }
11770
11771    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11772        let permalink_task = self.get_permalink_to_line(cx);
11773        let workspace = self.workspace();
11774
11775        cx.spawn(|_, mut cx| async move {
11776            match permalink_task.await {
11777                Ok(permalink) => {
11778                    cx.update(|cx| {
11779                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11780                    })
11781                    .ok();
11782                }
11783                Err(err) => {
11784                    let message = format!("Failed to copy permalink: {err}");
11785
11786                    Err::<(), anyhow::Error>(err).log_err();
11787
11788                    if let Some(workspace) = workspace {
11789                        workspace
11790                            .update(&mut cx, |workspace, cx| {
11791                                struct CopyPermalinkToLine;
11792
11793                                workspace.show_toast(
11794                                    Toast::new(
11795                                        NotificationId::unique::<CopyPermalinkToLine>(),
11796                                        message,
11797                                    ),
11798                                    cx,
11799                                )
11800                            })
11801                            .ok();
11802                    }
11803                }
11804            }
11805        })
11806        .detach();
11807    }
11808
11809    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11810        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11811        if let Some(file) = self.target_file(cx) {
11812            if let Some(path) = file.path().to_str() {
11813                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11814            }
11815        }
11816    }
11817
11818    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11819        let permalink_task = self.get_permalink_to_line(cx);
11820        let workspace = self.workspace();
11821
11822        cx.spawn(|_, mut cx| async move {
11823            match permalink_task.await {
11824                Ok(permalink) => {
11825                    cx.update(|cx| {
11826                        cx.open_url(permalink.as_ref());
11827                    })
11828                    .ok();
11829                }
11830                Err(err) => {
11831                    let message = format!("Failed to open permalink: {err}");
11832
11833                    Err::<(), anyhow::Error>(err).log_err();
11834
11835                    if let Some(workspace) = workspace {
11836                        workspace
11837                            .update(&mut cx, |workspace, cx| {
11838                                struct OpenPermalinkToLine;
11839
11840                                workspace.show_toast(
11841                                    Toast::new(
11842                                        NotificationId::unique::<OpenPermalinkToLine>(),
11843                                        message,
11844                                    ),
11845                                    cx,
11846                                )
11847                            })
11848                            .ok();
11849                    }
11850                }
11851            }
11852        })
11853        .detach();
11854    }
11855
11856    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11857    /// last highlight added will be used.
11858    ///
11859    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11860    pub fn highlight_rows<T: 'static>(
11861        &mut self,
11862        range: Range<Anchor>,
11863        color: Hsla,
11864        should_autoscroll: bool,
11865        cx: &mut ViewContext<Self>,
11866    ) {
11867        let snapshot = self.buffer().read(cx).snapshot(cx);
11868        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11869        let ix = row_highlights.binary_search_by(|highlight| {
11870            Ordering::Equal
11871                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11872                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11873        });
11874
11875        if let Err(mut ix) = ix {
11876            let index = post_inc(&mut self.highlight_order);
11877
11878            // If this range intersects with the preceding highlight, then merge it with
11879            // the preceding highlight. Otherwise insert a new highlight.
11880            let mut merged = false;
11881            if ix > 0 {
11882                let prev_highlight = &mut row_highlights[ix - 1];
11883                if prev_highlight
11884                    .range
11885                    .end
11886                    .cmp(&range.start, &snapshot)
11887                    .is_ge()
11888                {
11889                    ix -= 1;
11890                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11891                        prev_highlight.range.end = range.end;
11892                    }
11893                    merged = true;
11894                    prev_highlight.index = index;
11895                    prev_highlight.color = color;
11896                    prev_highlight.should_autoscroll = should_autoscroll;
11897                }
11898            }
11899
11900            if !merged {
11901                row_highlights.insert(
11902                    ix,
11903                    RowHighlight {
11904                        range: range.clone(),
11905                        index,
11906                        color,
11907                        should_autoscroll,
11908                    },
11909                );
11910            }
11911
11912            // If any of the following highlights intersect with this one, merge them.
11913            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11914                let highlight = &row_highlights[ix];
11915                if next_highlight
11916                    .range
11917                    .start
11918                    .cmp(&highlight.range.end, &snapshot)
11919                    .is_le()
11920                {
11921                    if next_highlight
11922                        .range
11923                        .end
11924                        .cmp(&highlight.range.end, &snapshot)
11925                        .is_gt()
11926                    {
11927                        row_highlights[ix].range.end = next_highlight.range.end;
11928                    }
11929                    row_highlights.remove(ix + 1);
11930                } else {
11931                    break;
11932                }
11933            }
11934        }
11935    }
11936
11937    /// Remove any highlighted row ranges of the given type that intersect the
11938    /// given ranges.
11939    pub fn remove_highlighted_rows<T: 'static>(
11940        &mut self,
11941        ranges_to_remove: Vec<Range<Anchor>>,
11942        cx: &mut ViewContext<Self>,
11943    ) {
11944        let snapshot = self.buffer().read(cx).snapshot(cx);
11945        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11946        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11947        row_highlights.retain(|highlight| {
11948            while let Some(range_to_remove) = ranges_to_remove.peek() {
11949                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11950                    Ordering::Less | Ordering::Equal => {
11951                        ranges_to_remove.next();
11952                    }
11953                    Ordering::Greater => {
11954                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11955                            Ordering::Less | Ordering::Equal => {
11956                                return false;
11957                            }
11958                            Ordering::Greater => break,
11959                        }
11960                    }
11961                }
11962            }
11963
11964            true
11965        })
11966    }
11967
11968    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11969    pub fn clear_row_highlights<T: 'static>(&mut self) {
11970        self.highlighted_rows.remove(&TypeId::of::<T>());
11971    }
11972
11973    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11974    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11975        self.highlighted_rows
11976            .get(&TypeId::of::<T>())
11977            .map_or(&[] as &[_], |vec| vec.as_slice())
11978            .iter()
11979            .map(|highlight| (highlight.range.clone(), highlight.color))
11980    }
11981
11982    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11983    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11984    /// Allows to ignore certain kinds of highlights.
11985    pub fn highlighted_display_rows(
11986        &mut self,
11987        cx: &mut WindowContext,
11988    ) -> BTreeMap<DisplayRow, Hsla> {
11989        let snapshot = self.snapshot(cx);
11990        let mut used_highlight_orders = HashMap::default();
11991        self.highlighted_rows
11992            .iter()
11993            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11994            .fold(
11995                BTreeMap::<DisplayRow, Hsla>::new(),
11996                |mut unique_rows, highlight| {
11997                    let start = highlight.range.start.to_display_point(&snapshot);
11998                    let end = highlight.range.end.to_display_point(&snapshot);
11999                    let start_row = start.row().0;
12000                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12001                        && end.column() == 0
12002                    {
12003                        end.row().0.saturating_sub(1)
12004                    } else {
12005                        end.row().0
12006                    };
12007                    for row in start_row..=end_row {
12008                        let used_index =
12009                            used_highlight_orders.entry(row).or_insert(highlight.index);
12010                        if highlight.index >= *used_index {
12011                            *used_index = highlight.index;
12012                            unique_rows.insert(DisplayRow(row), highlight.color);
12013                        }
12014                    }
12015                    unique_rows
12016                },
12017            )
12018    }
12019
12020    pub fn highlighted_display_row_for_autoscroll(
12021        &self,
12022        snapshot: &DisplaySnapshot,
12023    ) -> Option<DisplayRow> {
12024        self.highlighted_rows
12025            .values()
12026            .flat_map(|highlighted_rows| highlighted_rows.iter())
12027            .filter_map(|highlight| {
12028                if highlight.should_autoscroll {
12029                    Some(highlight.range.start.to_display_point(snapshot).row())
12030                } else {
12031                    None
12032                }
12033            })
12034            .min()
12035    }
12036
12037    pub fn set_search_within_ranges(
12038        &mut self,
12039        ranges: &[Range<Anchor>],
12040        cx: &mut ViewContext<Self>,
12041    ) {
12042        self.highlight_background::<SearchWithinRange>(
12043            ranges,
12044            |colors| colors.editor_document_highlight_read_background,
12045            cx,
12046        )
12047    }
12048
12049    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12050        self.breadcrumb_header = Some(new_header);
12051    }
12052
12053    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12054        self.clear_background_highlights::<SearchWithinRange>(cx);
12055    }
12056
12057    pub fn highlight_background<T: 'static>(
12058        &mut self,
12059        ranges: &[Range<Anchor>],
12060        color_fetcher: fn(&ThemeColors) -> Hsla,
12061        cx: &mut ViewContext<Self>,
12062    ) {
12063        self.background_highlights
12064            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12065        self.scrollbar_marker_state.dirty = true;
12066        cx.notify();
12067    }
12068
12069    pub fn clear_background_highlights<T: 'static>(
12070        &mut self,
12071        cx: &mut ViewContext<Self>,
12072    ) -> Option<BackgroundHighlight> {
12073        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12074        if !text_highlights.1.is_empty() {
12075            self.scrollbar_marker_state.dirty = true;
12076            cx.notify();
12077        }
12078        Some(text_highlights)
12079    }
12080
12081    pub fn highlight_gutter<T: 'static>(
12082        &mut self,
12083        ranges: &[Range<Anchor>],
12084        color_fetcher: fn(&AppContext) -> Hsla,
12085        cx: &mut ViewContext<Self>,
12086    ) {
12087        self.gutter_highlights
12088            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12089        cx.notify();
12090    }
12091
12092    pub fn clear_gutter_highlights<T: 'static>(
12093        &mut self,
12094        cx: &mut ViewContext<Self>,
12095    ) -> Option<GutterHighlight> {
12096        cx.notify();
12097        self.gutter_highlights.remove(&TypeId::of::<T>())
12098    }
12099
12100    #[cfg(feature = "test-support")]
12101    pub fn all_text_background_highlights(
12102        &mut self,
12103        cx: &mut ViewContext<Self>,
12104    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12105        let snapshot = self.snapshot(cx);
12106        let buffer = &snapshot.buffer_snapshot;
12107        let start = buffer.anchor_before(0);
12108        let end = buffer.anchor_after(buffer.len());
12109        let theme = cx.theme().colors();
12110        self.background_highlights_in_range(start..end, &snapshot, theme)
12111    }
12112
12113    #[cfg(feature = "test-support")]
12114    pub fn search_background_highlights(
12115        &mut self,
12116        cx: &mut ViewContext<Self>,
12117    ) -> Vec<Range<Point>> {
12118        let snapshot = self.buffer().read(cx).snapshot(cx);
12119
12120        let highlights = self
12121            .background_highlights
12122            .get(&TypeId::of::<items::BufferSearchHighlights>());
12123
12124        if let Some((_color, ranges)) = highlights {
12125            ranges
12126                .iter()
12127                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12128                .collect_vec()
12129        } else {
12130            vec![]
12131        }
12132    }
12133
12134    fn document_highlights_for_position<'a>(
12135        &'a self,
12136        position: Anchor,
12137        buffer: &'a MultiBufferSnapshot,
12138    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12139        let read_highlights = self
12140            .background_highlights
12141            .get(&TypeId::of::<DocumentHighlightRead>())
12142            .map(|h| &h.1);
12143        let write_highlights = self
12144            .background_highlights
12145            .get(&TypeId::of::<DocumentHighlightWrite>())
12146            .map(|h| &h.1);
12147        let left_position = position.bias_left(buffer);
12148        let right_position = position.bias_right(buffer);
12149        read_highlights
12150            .into_iter()
12151            .chain(write_highlights)
12152            .flat_map(move |ranges| {
12153                let start_ix = match ranges.binary_search_by(|probe| {
12154                    let cmp = probe.end.cmp(&left_position, buffer);
12155                    if cmp.is_ge() {
12156                        Ordering::Greater
12157                    } else {
12158                        Ordering::Less
12159                    }
12160                }) {
12161                    Ok(i) | Err(i) => i,
12162                };
12163
12164                ranges[start_ix..]
12165                    .iter()
12166                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12167            })
12168    }
12169
12170    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12171        self.background_highlights
12172            .get(&TypeId::of::<T>())
12173            .map_or(false, |(_, highlights)| !highlights.is_empty())
12174    }
12175
12176    pub fn background_highlights_in_range(
12177        &self,
12178        search_range: Range<Anchor>,
12179        display_snapshot: &DisplaySnapshot,
12180        theme: &ThemeColors,
12181    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12182        let mut results = Vec::new();
12183        for (color_fetcher, ranges) in self.background_highlights.values() {
12184            let color = color_fetcher(theme);
12185            let start_ix = match ranges.binary_search_by(|probe| {
12186                let cmp = probe
12187                    .end
12188                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12189                if cmp.is_gt() {
12190                    Ordering::Greater
12191                } else {
12192                    Ordering::Less
12193                }
12194            }) {
12195                Ok(i) | Err(i) => i,
12196            };
12197            for range in &ranges[start_ix..] {
12198                if range
12199                    .start
12200                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12201                    .is_ge()
12202                {
12203                    break;
12204                }
12205
12206                let start = range.start.to_display_point(display_snapshot);
12207                let end = range.end.to_display_point(display_snapshot);
12208                results.push((start..end, color))
12209            }
12210        }
12211        results
12212    }
12213
12214    pub fn background_highlight_row_ranges<T: 'static>(
12215        &self,
12216        search_range: Range<Anchor>,
12217        display_snapshot: &DisplaySnapshot,
12218        count: usize,
12219    ) -> Vec<RangeInclusive<DisplayPoint>> {
12220        let mut results = Vec::new();
12221        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12222            return vec![];
12223        };
12224
12225        let start_ix = match ranges.binary_search_by(|probe| {
12226            let cmp = probe
12227                .end
12228                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12229            if cmp.is_gt() {
12230                Ordering::Greater
12231            } else {
12232                Ordering::Less
12233            }
12234        }) {
12235            Ok(i) | Err(i) => i,
12236        };
12237        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12238            if let (Some(start_display), Some(end_display)) = (start, end) {
12239                results.push(
12240                    start_display.to_display_point(display_snapshot)
12241                        ..=end_display.to_display_point(display_snapshot),
12242                );
12243            }
12244        };
12245        let mut start_row: Option<Point> = None;
12246        let mut end_row: Option<Point> = None;
12247        if ranges.len() > count {
12248            return Vec::new();
12249        }
12250        for range in &ranges[start_ix..] {
12251            if range
12252                .start
12253                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12254                .is_ge()
12255            {
12256                break;
12257            }
12258            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12259            if let Some(current_row) = &end_row {
12260                if end.row == current_row.row {
12261                    continue;
12262                }
12263            }
12264            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12265            if start_row.is_none() {
12266                assert_eq!(end_row, None);
12267                start_row = Some(start);
12268                end_row = Some(end);
12269                continue;
12270            }
12271            if let Some(current_end) = end_row.as_mut() {
12272                if start.row > current_end.row + 1 {
12273                    push_region(start_row, end_row);
12274                    start_row = Some(start);
12275                    end_row = Some(end);
12276                } else {
12277                    // Merge two hunks.
12278                    *current_end = end;
12279                }
12280            } else {
12281                unreachable!();
12282            }
12283        }
12284        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12285        push_region(start_row, end_row);
12286        results
12287    }
12288
12289    pub fn gutter_highlights_in_range(
12290        &self,
12291        search_range: Range<Anchor>,
12292        display_snapshot: &DisplaySnapshot,
12293        cx: &AppContext,
12294    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12295        let mut results = Vec::new();
12296        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12297            let color = color_fetcher(cx);
12298            let start_ix = match ranges.binary_search_by(|probe| {
12299                let cmp = probe
12300                    .end
12301                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12302                if cmp.is_gt() {
12303                    Ordering::Greater
12304                } else {
12305                    Ordering::Less
12306                }
12307            }) {
12308                Ok(i) | Err(i) => i,
12309            };
12310            for range in &ranges[start_ix..] {
12311                if range
12312                    .start
12313                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12314                    .is_ge()
12315                {
12316                    break;
12317                }
12318
12319                let start = range.start.to_display_point(display_snapshot);
12320                let end = range.end.to_display_point(display_snapshot);
12321                results.push((start..end, color))
12322            }
12323        }
12324        results
12325    }
12326
12327    /// Get the text ranges corresponding to the redaction query
12328    pub fn redacted_ranges(
12329        &self,
12330        search_range: Range<Anchor>,
12331        display_snapshot: &DisplaySnapshot,
12332        cx: &WindowContext,
12333    ) -> Vec<Range<DisplayPoint>> {
12334        display_snapshot
12335            .buffer_snapshot
12336            .redacted_ranges(search_range, |file| {
12337                if let Some(file) = file {
12338                    file.is_private()
12339                        && EditorSettings::get(
12340                            Some(SettingsLocation {
12341                                worktree_id: file.worktree_id(cx),
12342                                path: file.path().as_ref(),
12343                            }),
12344                            cx,
12345                        )
12346                        .redact_private_values
12347                } else {
12348                    false
12349                }
12350            })
12351            .map(|range| {
12352                range.start.to_display_point(display_snapshot)
12353                    ..range.end.to_display_point(display_snapshot)
12354            })
12355            .collect()
12356    }
12357
12358    pub fn highlight_text<T: 'static>(
12359        &mut self,
12360        ranges: Vec<Range<Anchor>>,
12361        style: HighlightStyle,
12362        cx: &mut ViewContext<Self>,
12363    ) {
12364        self.display_map.update(cx, |map, _| {
12365            map.highlight_text(TypeId::of::<T>(), ranges, style)
12366        });
12367        cx.notify();
12368    }
12369
12370    pub(crate) fn highlight_inlays<T: 'static>(
12371        &mut self,
12372        highlights: Vec<InlayHighlight>,
12373        style: HighlightStyle,
12374        cx: &mut ViewContext<Self>,
12375    ) {
12376        self.display_map.update(cx, |map, _| {
12377            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12378        });
12379        cx.notify();
12380    }
12381
12382    pub fn text_highlights<'a, T: 'static>(
12383        &'a self,
12384        cx: &'a AppContext,
12385    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12386        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12387    }
12388
12389    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12390        let cleared = self
12391            .display_map
12392            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12393        if cleared {
12394            cx.notify();
12395        }
12396    }
12397
12398    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12399        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12400            && self.focus_handle.is_focused(cx)
12401    }
12402
12403    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12404        self.show_cursor_when_unfocused = is_enabled;
12405        cx.notify();
12406    }
12407
12408    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12409        cx.notify();
12410    }
12411
12412    fn on_buffer_event(
12413        &mut self,
12414        multibuffer: Model<MultiBuffer>,
12415        event: &multi_buffer::Event,
12416        cx: &mut ViewContext<Self>,
12417    ) {
12418        match event {
12419            multi_buffer::Event::Edited {
12420                singleton_buffer_edited,
12421            } => {
12422                self.scrollbar_marker_state.dirty = true;
12423                self.active_indent_guides_state.dirty = true;
12424                self.refresh_active_diagnostics(cx);
12425                self.refresh_code_actions(cx);
12426                if self.has_active_inline_completion(cx) {
12427                    self.update_visible_inline_completion(cx);
12428                }
12429                cx.emit(EditorEvent::BufferEdited);
12430                cx.emit(SearchEvent::MatchesInvalidated);
12431                if *singleton_buffer_edited {
12432                    if let Some(project) = &self.project {
12433                        let project = project.read(cx);
12434                        #[allow(clippy::mutable_key_type)]
12435                        let languages_affected = multibuffer
12436                            .read(cx)
12437                            .all_buffers()
12438                            .into_iter()
12439                            .filter_map(|buffer| {
12440                                let buffer = buffer.read(cx);
12441                                let language = buffer.language()?;
12442                                if project.is_local()
12443                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12444                                {
12445                                    None
12446                                } else {
12447                                    Some(language)
12448                                }
12449                            })
12450                            .cloned()
12451                            .collect::<HashSet<_>>();
12452                        if !languages_affected.is_empty() {
12453                            self.refresh_inlay_hints(
12454                                InlayHintRefreshReason::BufferEdited(languages_affected),
12455                                cx,
12456                            );
12457                        }
12458                    }
12459                }
12460
12461                let Some(project) = &self.project else { return };
12462                let (telemetry, is_via_ssh) = {
12463                    let project = project.read(cx);
12464                    let telemetry = project.client().telemetry().clone();
12465                    let is_via_ssh = project.is_via_ssh();
12466                    (telemetry, is_via_ssh)
12467                };
12468                refresh_linked_ranges(self, cx);
12469                telemetry.log_edit_event("editor", is_via_ssh);
12470            }
12471            multi_buffer::Event::ExcerptsAdded {
12472                buffer,
12473                predecessor,
12474                excerpts,
12475            } => {
12476                self.tasks_update_task = Some(self.refresh_runnables(cx));
12477                cx.emit(EditorEvent::ExcerptsAdded {
12478                    buffer: buffer.clone(),
12479                    predecessor: *predecessor,
12480                    excerpts: excerpts.clone(),
12481                });
12482                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12483            }
12484            multi_buffer::Event::ExcerptsRemoved { ids } => {
12485                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12486                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12487            }
12488            multi_buffer::Event::ExcerptsEdited { ids } => {
12489                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12490            }
12491            multi_buffer::Event::ExcerptsExpanded { ids } => {
12492                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12493            }
12494            multi_buffer::Event::Reparsed(buffer_id) => {
12495                self.tasks_update_task = Some(self.refresh_runnables(cx));
12496
12497                cx.emit(EditorEvent::Reparsed(*buffer_id));
12498            }
12499            multi_buffer::Event::LanguageChanged(buffer_id) => {
12500                linked_editing_ranges::refresh_linked_ranges(self, cx);
12501                cx.emit(EditorEvent::Reparsed(*buffer_id));
12502                cx.notify();
12503            }
12504            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12505            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12506            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12507                cx.emit(EditorEvent::TitleChanged)
12508            }
12509            multi_buffer::Event::DiffBaseChanged => {
12510                self.scrollbar_marker_state.dirty = true;
12511                cx.emit(EditorEvent::DiffBaseChanged);
12512                cx.notify();
12513            }
12514            multi_buffer::Event::DiffUpdated { buffer } => {
12515                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12516                cx.notify();
12517            }
12518            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12519            multi_buffer::Event::DiagnosticsUpdated => {
12520                self.refresh_active_diagnostics(cx);
12521                self.scrollbar_marker_state.dirty = true;
12522                cx.notify();
12523            }
12524            _ => {}
12525        };
12526    }
12527
12528    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12529        cx.notify();
12530    }
12531
12532    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12533        self.tasks_update_task = Some(self.refresh_runnables(cx));
12534        self.refresh_inline_completion(true, false, cx);
12535        self.refresh_inlay_hints(
12536            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12537                self.selections.newest_anchor().head(),
12538                &self.buffer.read(cx).snapshot(cx),
12539                cx,
12540            )),
12541            cx,
12542        );
12543
12544        let old_cursor_shape = self.cursor_shape;
12545
12546        {
12547            let editor_settings = EditorSettings::get_global(cx);
12548            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12549            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12550            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12551        }
12552
12553        if old_cursor_shape != self.cursor_shape {
12554            cx.emit(EditorEvent::CursorShapeChanged);
12555        }
12556
12557        let project_settings = ProjectSettings::get_global(cx);
12558        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12559
12560        if self.mode == EditorMode::Full {
12561            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12562            if self.git_blame_inline_enabled != inline_blame_enabled {
12563                self.toggle_git_blame_inline_internal(false, cx);
12564            }
12565        }
12566
12567        cx.notify();
12568    }
12569
12570    pub fn set_searchable(&mut self, searchable: bool) {
12571        self.searchable = searchable;
12572    }
12573
12574    pub fn searchable(&self) -> bool {
12575        self.searchable
12576    }
12577
12578    fn open_proposed_changes_editor(
12579        &mut self,
12580        _: &OpenProposedChangesEditor,
12581        cx: &mut ViewContext<Self>,
12582    ) {
12583        let Some(workspace) = self.workspace() else {
12584            cx.propagate();
12585            return;
12586        };
12587
12588        let selections = self.selections.all::<usize>(cx);
12589        let buffer = self.buffer.read(cx);
12590        let mut new_selections_by_buffer = HashMap::default();
12591        for selection in selections {
12592            for (buffer, range, _) in
12593                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12594            {
12595                let mut range = range.to_point(buffer.read(cx));
12596                range.start.column = 0;
12597                range.end.column = buffer.read(cx).line_len(range.end.row);
12598                new_selections_by_buffer
12599                    .entry(buffer)
12600                    .or_insert(Vec::new())
12601                    .push(range)
12602            }
12603        }
12604
12605        let proposed_changes_buffers = new_selections_by_buffer
12606            .into_iter()
12607            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12608            .collect::<Vec<_>>();
12609        let proposed_changes_editor = cx.new_view(|cx| {
12610            ProposedChangesEditor::new(
12611                "Proposed changes",
12612                proposed_changes_buffers,
12613                self.project.clone(),
12614                cx,
12615            )
12616        });
12617
12618        cx.window_context().defer(move |cx| {
12619            workspace.update(cx, |workspace, cx| {
12620                workspace.active_pane().update(cx, |pane, cx| {
12621                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12622                });
12623            });
12624        });
12625    }
12626
12627    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12628        self.open_excerpts_common(None, true, cx)
12629    }
12630
12631    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12632        self.open_excerpts_common(None, false, cx)
12633    }
12634
12635    fn open_excerpts_common(
12636        &mut self,
12637        jump_data: Option<JumpData>,
12638        split: bool,
12639        cx: &mut ViewContext<Self>,
12640    ) {
12641        let Some(workspace) = self.workspace() else {
12642            cx.propagate();
12643            return;
12644        };
12645
12646        if self.buffer.read(cx).is_singleton() {
12647            cx.propagate();
12648            return;
12649        }
12650
12651        let mut new_selections_by_buffer = HashMap::default();
12652        match &jump_data {
12653            Some(jump_data) => {
12654                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12655                if let Some(buffer) = multi_buffer_snapshot
12656                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12657                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12658                {
12659                    let buffer_snapshot = buffer.read(cx).snapshot();
12660                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12661                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12662                    } else {
12663                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12664                    };
12665                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12666                    new_selections_by_buffer.insert(
12667                        buffer,
12668                        (
12669                            vec![jump_to_offset..jump_to_offset],
12670                            Some(jump_data.line_offset_from_top),
12671                        ),
12672                    );
12673                }
12674            }
12675            None => {
12676                let selections = self.selections.all::<usize>(cx);
12677                let buffer = self.buffer.read(cx);
12678                for selection in selections {
12679                    for (mut buffer_handle, mut range, _) in
12680                        buffer.range_to_buffer_ranges(selection.range(), cx)
12681                    {
12682                        // When editing branch buffers, jump to the corresponding location
12683                        // in their base buffer.
12684                        let buffer = buffer_handle.read(cx);
12685                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12686                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12687                            buffer_handle = base_buffer;
12688                        }
12689
12690                        if selection.reversed {
12691                            mem::swap(&mut range.start, &mut range.end);
12692                        }
12693                        new_selections_by_buffer
12694                            .entry(buffer_handle)
12695                            .or_insert((Vec::new(), None))
12696                            .0
12697                            .push(range)
12698                    }
12699                }
12700            }
12701        }
12702
12703        if new_selections_by_buffer.is_empty() {
12704            return;
12705        }
12706
12707        // We defer the pane interaction because we ourselves are a workspace item
12708        // and activating a new item causes the pane to call a method on us reentrantly,
12709        // which panics if we're on the stack.
12710        cx.window_context().defer(move |cx| {
12711            workspace.update(cx, |workspace, cx| {
12712                let pane = if split {
12713                    workspace.adjacent_pane(cx)
12714                } else {
12715                    workspace.active_pane().clone()
12716                };
12717
12718                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12719                    let editor =
12720                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12721                    editor.update(cx, |editor, cx| {
12722                        let autoscroll = match scroll_offset {
12723                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12724                            None => Autoscroll::newest(),
12725                        };
12726                        let nav_history = editor.nav_history.take();
12727                        editor.change_selections(Some(autoscroll), cx, |s| {
12728                            s.select_ranges(ranges);
12729                        });
12730                        editor.nav_history = nav_history;
12731                    });
12732                }
12733            })
12734        });
12735    }
12736
12737    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12738        let snapshot = self.buffer.read(cx).read(cx);
12739        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12740        Some(
12741            ranges
12742                .iter()
12743                .map(move |range| {
12744                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12745                })
12746                .collect(),
12747        )
12748    }
12749
12750    fn selection_replacement_ranges(
12751        &self,
12752        range: Range<OffsetUtf16>,
12753        cx: &mut AppContext,
12754    ) -> Vec<Range<OffsetUtf16>> {
12755        let selections = self.selections.all::<OffsetUtf16>(cx);
12756        let newest_selection = selections
12757            .iter()
12758            .max_by_key(|selection| selection.id)
12759            .unwrap();
12760        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12761        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12762        let snapshot = self.buffer.read(cx).read(cx);
12763        selections
12764            .into_iter()
12765            .map(|mut selection| {
12766                selection.start.0 =
12767                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12768                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12769                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12770                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12771            })
12772            .collect()
12773    }
12774
12775    fn report_editor_event(
12776        &self,
12777        operation: &'static str,
12778        file_extension: Option<String>,
12779        cx: &AppContext,
12780    ) {
12781        if cfg!(any(test, feature = "test-support")) {
12782            return;
12783        }
12784
12785        let Some(project) = &self.project else { return };
12786
12787        // If None, we are in a file without an extension
12788        let file = self
12789            .buffer
12790            .read(cx)
12791            .as_singleton()
12792            .and_then(|b| b.read(cx).file());
12793        let file_extension = file_extension.or(file
12794            .as_ref()
12795            .and_then(|file| Path::new(file.file_name(cx)).extension())
12796            .and_then(|e| e.to_str())
12797            .map(|a| a.to_string()));
12798
12799        let vim_mode = cx
12800            .global::<SettingsStore>()
12801            .raw_user_settings()
12802            .get("vim_mode")
12803            == Some(&serde_json::Value::Bool(true));
12804
12805        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12806            == language::language_settings::InlineCompletionProvider::Copilot;
12807        let copilot_enabled_for_language = self
12808            .buffer
12809            .read(cx)
12810            .settings_at(0, cx)
12811            .show_inline_completions;
12812
12813        let project = project.read(cx);
12814        let telemetry = project.client().telemetry().clone();
12815        telemetry.report_editor_event(
12816            file_extension,
12817            vim_mode,
12818            operation,
12819            copilot_enabled,
12820            copilot_enabled_for_language,
12821            project.is_via_ssh(),
12822        )
12823    }
12824
12825    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12826    /// with each line being an array of {text, highlight} objects.
12827    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12828        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12829            return;
12830        };
12831
12832        #[derive(Serialize)]
12833        struct Chunk<'a> {
12834            text: String,
12835            highlight: Option<&'a str>,
12836        }
12837
12838        let snapshot = buffer.read(cx).snapshot();
12839        let range = self
12840            .selected_text_range(false, cx)
12841            .and_then(|selection| {
12842                if selection.range.is_empty() {
12843                    None
12844                } else {
12845                    Some(selection.range)
12846                }
12847            })
12848            .unwrap_or_else(|| 0..snapshot.len());
12849
12850        let chunks = snapshot.chunks(range, true);
12851        let mut lines = Vec::new();
12852        let mut line: VecDeque<Chunk> = VecDeque::new();
12853
12854        let Some(style) = self.style.as_ref() else {
12855            return;
12856        };
12857
12858        for chunk in chunks {
12859            let highlight = chunk
12860                .syntax_highlight_id
12861                .and_then(|id| id.name(&style.syntax));
12862            let mut chunk_lines = chunk.text.split('\n').peekable();
12863            while let Some(text) = chunk_lines.next() {
12864                let mut merged_with_last_token = false;
12865                if let Some(last_token) = line.back_mut() {
12866                    if last_token.highlight == highlight {
12867                        last_token.text.push_str(text);
12868                        merged_with_last_token = true;
12869                    }
12870                }
12871
12872                if !merged_with_last_token {
12873                    line.push_back(Chunk {
12874                        text: text.into(),
12875                        highlight,
12876                    });
12877                }
12878
12879                if chunk_lines.peek().is_some() {
12880                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12881                        line.pop_front();
12882                    }
12883                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12884                        line.pop_back();
12885                    }
12886
12887                    lines.push(mem::take(&mut line));
12888                }
12889            }
12890        }
12891
12892        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12893            return;
12894        };
12895        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12896    }
12897
12898    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12899        &self.inlay_hint_cache
12900    }
12901
12902    pub fn replay_insert_event(
12903        &mut self,
12904        text: &str,
12905        relative_utf16_range: Option<Range<isize>>,
12906        cx: &mut ViewContext<Self>,
12907    ) {
12908        if !self.input_enabled {
12909            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12910            return;
12911        }
12912        if let Some(relative_utf16_range) = relative_utf16_range {
12913            let selections = self.selections.all::<OffsetUtf16>(cx);
12914            self.change_selections(None, cx, |s| {
12915                let new_ranges = selections.into_iter().map(|range| {
12916                    let start = OffsetUtf16(
12917                        range
12918                            .head()
12919                            .0
12920                            .saturating_add_signed(relative_utf16_range.start),
12921                    );
12922                    let end = OffsetUtf16(
12923                        range
12924                            .head()
12925                            .0
12926                            .saturating_add_signed(relative_utf16_range.end),
12927                    );
12928                    start..end
12929                });
12930                s.select_ranges(new_ranges);
12931            });
12932        }
12933
12934        self.handle_input(text, cx);
12935    }
12936
12937    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12938        let Some(provider) = self.semantics_provider.as_ref() else {
12939            return false;
12940        };
12941
12942        let mut supports = false;
12943        self.buffer().read(cx).for_each_buffer(|buffer| {
12944            supports |= provider.supports_inlay_hints(buffer, cx);
12945        });
12946        supports
12947    }
12948
12949    pub fn focus(&self, cx: &mut WindowContext) {
12950        cx.focus(&self.focus_handle)
12951    }
12952
12953    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12954        self.focus_handle.is_focused(cx)
12955    }
12956
12957    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12958        cx.emit(EditorEvent::Focused);
12959
12960        if let Some(descendant) = self
12961            .last_focused_descendant
12962            .take()
12963            .and_then(|descendant| descendant.upgrade())
12964        {
12965            cx.focus(&descendant);
12966        } else {
12967            if let Some(blame) = self.blame.as_ref() {
12968                blame.update(cx, GitBlame::focus)
12969            }
12970
12971            self.blink_manager.update(cx, BlinkManager::enable);
12972            self.show_cursor_names(cx);
12973            self.buffer.update(cx, |buffer, cx| {
12974                buffer.finalize_last_transaction(cx);
12975                if self.leader_peer_id.is_none() {
12976                    buffer.set_active_selections(
12977                        &self.selections.disjoint_anchors(),
12978                        self.selections.line_mode,
12979                        self.cursor_shape,
12980                        cx,
12981                    );
12982                }
12983            });
12984        }
12985    }
12986
12987    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12988        cx.emit(EditorEvent::FocusedIn)
12989    }
12990
12991    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12992        if event.blurred != self.focus_handle {
12993            self.last_focused_descendant = Some(event.blurred);
12994        }
12995    }
12996
12997    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12998        self.blink_manager.update(cx, BlinkManager::disable);
12999        self.buffer
13000            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13001
13002        if let Some(blame) = self.blame.as_ref() {
13003            blame.update(cx, GitBlame::blur)
13004        }
13005        if !self.hover_state.focused(cx) {
13006            hide_hover(self, cx);
13007        }
13008
13009        self.hide_context_menu(cx);
13010        cx.emit(EditorEvent::Blurred);
13011        cx.notify();
13012    }
13013
13014    pub fn register_action<A: Action>(
13015        &mut self,
13016        listener: impl Fn(&A, &mut WindowContext) + 'static,
13017    ) -> Subscription {
13018        let id = self.next_editor_action_id.post_inc();
13019        let listener = Arc::new(listener);
13020        self.editor_actions.borrow_mut().insert(
13021            id,
13022            Box::new(move |cx| {
13023                let cx = cx.window_context();
13024                let listener = listener.clone();
13025                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13026                    let action = action.downcast_ref().unwrap();
13027                    if phase == DispatchPhase::Bubble {
13028                        listener(action, cx)
13029                    }
13030                })
13031            }),
13032        );
13033
13034        let editor_actions = self.editor_actions.clone();
13035        Subscription::new(move || {
13036            editor_actions.borrow_mut().remove(&id);
13037        })
13038    }
13039
13040    pub fn file_header_size(&self) -> u32 {
13041        FILE_HEADER_HEIGHT
13042    }
13043
13044    pub fn revert(
13045        &mut self,
13046        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13047        cx: &mut ViewContext<Self>,
13048    ) {
13049        self.buffer().update(cx, |multi_buffer, cx| {
13050            for (buffer_id, changes) in revert_changes {
13051                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13052                    buffer.update(cx, |buffer, cx| {
13053                        buffer.edit(
13054                            changes.into_iter().map(|(range, text)| {
13055                                (range, text.to_string().map(Arc::<str>::from))
13056                            }),
13057                            None,
13058                            cx,
13059                        );
13060                    });
13061                }
13062            }
13063        });
13064        self.change_selections(None, cx, |selections| selections.refresh());
13065    }
13066
13067    pub fn to_pixel_point(
13068        &mut self,
13069        source: multi_buffer::Anchor,
13070        editor_snapshot: &EditorSnapshot,
13071        cx: &mut ViewContext<Self>,
13072    ) -> Option<gpui::Point<Pixels>> {
13073        let source_point = source.to_display_point(editor_snapshot);
13074        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13075    }
13076
13077    pub fn display_to_pixel_point(
13078        &mut self,
13079        source: DisplayPoint,
13080        editor_snapshot: &EditorSnapshot,
13081        cx: &mut ViewContext<Self>,
13082    ) -> Option<gpui::Point<Pixels>> {
13083        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13084        let text_layout_details = self.text_layout_details(cx);
13085        let scroll_top = text_layout_details
13086            .scroll_anchor
13087            .scroll_position(editor_snapshot)
13088            .y;
13089
13090        if source.row().as_f32() < scroll_top.floor() {
13091            return None;
13092        }
13093        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13094        let source_y = line_height * (source.row().as_f32() - scroll_top);
13095        Some(gpui::Point::new(source_x, source_y))
13096    }
13097
13098    pub fn has_active_completions_menu(&self) -> bool {
13099        self.context_menu.read().as_ref().map_or(false, |menu| {
13100            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13101        })
13102    }
13103
13104    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13105        self.addons
13106            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13107    }
13108
13109    pub fn unregister_addon<T: Addon>(&mut self) {
13110        self.addons.remove(&std::any::TypeId::of::<T>());
13111    }
13112
13113    pub fn addon<T: Addon>(&self) -> Option<&T> {
13114        let type_id = std::any::TypeId::of::<T>();
13115        self.addons
13116            .get(&type_id)
13117            .and_then(|item| item.to_any().downcast_ref::<T>())
13118    }
13119}
13120
13121fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13122    let tab_size = tab_size.get() as usize;
13123    let mut width = offset;
13124
13125    for ch in text.chars() {
13126        width += if ch == '\t' {
13127            tab_size - (width % tab_size)
13128        } else {
13129            1
13130        };
13131    }
13132
13133    width - offset
13134}
13135
13136#[cfg(test)]
13137mod tests {
13138    use super::*;
13139
13140    #[test]
13141    fn test_string_size_with_expanded_tabs() {
13142        let nz = |val| NonZeroU32::new(val).unwrap();
13143        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13144        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13145        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13146        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13147        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13148        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13149        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13150        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13151    }
13152}
13153
13154/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13155struct WordBreakingTokenizer<'a> {
13156    input: &'a str,
13157}
13158
13159impl<'a> WordBreakingTokenizer<'a> {
13160    fn new(input: &'a str) -> Self {
13161        Self { input }
13162    }
13163}
13164
13165fn is_char_ideographic(ch: char) -> bool {
13166    use unicode_script::Script::*;
13167    use unicode_script::UnicodeScript;
13168    matches!(ch.script(), Han | Tangut | Yi)
13169}
13170
13171fn is_grapheme_ideographic(text: &str) -> bool {
13172    text.chars().any(is_char_ideographic)
13173}
13174
13175fn is_grapheme_whitespace(text: &str) -> bool {
13176    text.chars().any(|x| x.is_whitespace())
13177}
13178
13179fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13180    text.chars().next().map_or(false, |ch| {
13181        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13182    })
13183}
13184
13185#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13186struct WordBreakToken<'a> {
13187    token: &'a str,
13188    grapheme_len: usize,
13189    is_whitespace: bool,
13190}
13191
13192impl<'a> Iterator for WordBreakingTokenizer<'a> {
13193    /// Yields a span, the count of graphemes in the token, and whether it was
13194    /// whitespace. Note that it also breaks at word boundaries.
13195    type Item = WordBreakToken<'a>;
13196
13197    fn next(&mut self) -> Option<Self::Item> {
13198        use unicode_segmentation::UnicodeSegmentation;
13199        if self.input.is_empty() {
13200            return None;
13201        }
13202
13203        let mut iter = self.input.graphemes(true).peekable();
13204        let mut offset = 0;
13205        let mut graphemes = 0;
13206        if let Some(first_grapheme) = iter.next() {
13207            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13208            offset += first_grapheme.len();
13209            graphemes += 1;
13210            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13211                if let Some(grapheme) = iter.peek().copied() {
13212                    if should_stay_with_preceding_ideograph(grapheme) {
13213                        offset += grapheme.len();
13214                        graphemes += 1;
13215                    }
13216                }
13217            } else {
13218                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13219                let mut next_word_bound = words.peek().copied();
13220                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13221                    next_word_bound = words.next();
13222                }
13223                while let Some(grapheme) = iter.peek().copied() {
13224                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13225                        break;
13226                    };
13227                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13228                        break;
13229                    };
13230                    offset += grapheme.len();
13231                    graphemes += 1;
13232                    iter.next();
13233                }
13234            }
13235            let token = &self.input[..offset];
13236            self.input = &self.input[offset..];
13237            if is_whitespace {
13238                Some(WordBreakToken {
13239                    token: " ",
13240                    grapheme_len: 1,
13241                    is_whitespace: true,
13242                })
13243            } else {
13244                Some(WordBreakToken {
13245                    token,
13246                    grapheme_len: graphemes,
13247                    is_whitespace: false,
13248                })
13249            }
13250        } else {
13251            None
13252        }
13253    }
13254}
13255
13256#[test]
13257fn test_word_breaking_tokenizer() {
13258    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13259        ("", &[]),
13260        ("  ", &[(" ", 1, true)]),
13261        ("Ʒ", &[("Ʒ", 1, false)]),
13262        ("Ǽ", &[("Ǽ", 1, false)]),
13263        ("", &[("", 1, false)]),
13264        ("⋑⋑", &[("⋑⋑", 2, false)]),
13265        (
13266            "原理,进而",
13267            &[
13268                ("", 1, false),
13269                ("理,", 2, false),
13270                ("", 1, false),
13271                ("", 1, false),
13272            ],
13273        ),
13274        (
13275            "hello world",
13276            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13277        ),
13278        (
13279            "hello, world",
13280            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13281        ),
13282        (
13283            "  hello world",
13284            &[
13285                (" ", 1, true),
13286                ("hello", 5, false),
13287                (" ", 1, true),
13288                ("world", 5, false),
13289            ],
13290        ),
13291        (
13292            "这是什么 \n 钢笔",
13293            &[
13294                ("", 1, false),
13295                ("", 1, false),
13296                ("", 1, false),
13297                ("", 1, false),
13298                (" ", 1, true),
13299                ("", 1, false),
13300                ("", 1, false),
13301            ],
13302        ),
13303        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13304    ];
13305
13306    for (input, result) in tests {
13307        assert_eq!(
13308            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13309            result
13310                .iter()
13311                .copied()
13312                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13313                    token,
13314                    grapheme_len,
13315                    is_whitespace,
13316                })
13317                .collect::<Vec<_>>()
13318        );
13319    }
13320}
13321
13322fn wrap_with_prefix(
13323    line_prefix: String,
13324    unwrapped_text: String,
13325    wrap_column: usize,
13326    tab_size: NonZeroU32,
13327) -> String {
13328    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13329    let mut wrapped_text = String::new();
13330    let mut current_line = line_prefix.clone();
13331
13332    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13333    let mut current_line_len = line_prefix_len;
13334    for WordBreakToken {
13335        token,
13336        grapheme_len,
13337        is_whitespace,
13338    } in tokenizer
13339    {
13340        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13341            wrapped_text.push_str(current_line.trim_end());
13342            wrapped_text.push('\n');
13343            current_line.truncate(line_prefix.len());
13344            current_line_len = line_prefix_len;
13345            if !is_whitespace {
13346                current_line.push_str(token);
13347                current_line_len += grapheme_len;
13348            }
13349        } else if !is_whitespace {
13350            current_line.push_str(token);
13351            current_line_len += grapheme_len;
13352        } else if current_line_len != line_prefix_len {
13353            current_line.push(' ');
13354            current_line_len += 1;
13355        }
13356    }
13357
13358    if !current_line.is_empty() {
13359        wrapped_text.push_str(&current_line);
13360    }
13361    wrapped_text
13362}
13363
13364#[test]
13365fn test_wrap_with_prefix() {
13366    assert_eq!(
13367        wrap_with_prefix(
13368            "# ".to_string(),
13369            "abcdefg".to_string(),
13370            4,
13371            NonZeroU32::new(4).unwrap()
13372        ),
13373        "# abcdefg"
13374    );
13375    assert_eq!(
13376        wrap_with_prefix(
13377            "".to_string(),
13378            "\thello world".to_string(),
13379            8,
13380            NonZeroU32::new(4).unwrap()
13381        ),
13382        "hello\nworld"
13383    );
13384    assert_eq!(
13385        wrap_with_prefix(
13386            "// ".to_string(),
13387            "xx \nyy zz aa bb cc".to_string(),
13388            12,
13389            NonZeroU32::new(4).unwrap()
13390        ),
13391        "// xx yy zz\n// aa bb cc"
13392    );
13393    assert_eq!(
13394        wrap_with_prefix(
13395            String::new(),
13396            "这是什么 \n 钢笔".to_string(),
13397            3,
13398            NonZeroU32::new(4).unwrap()
13399        ),
13400        "这是什\n么 钢\n"
13401    );
13402}
13403
13404fn hunks_for_selections(
13405    multi_buffer_snapshot: &MultiBufferSnapshot,
13406    selections: &[Selection<Anchor>],
13407) -> Vec<MultiBufferDiffHunk> {
13408    let buffer_rows_for_selections = selections.iter().map(|selection| {
13409        let head = selection.head();
13410        let tail = selection.tail();
13411        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13412        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13413        if start > end {
13414            end..start
13415        } else {
13416            start..end
13417        }
13418    });
13419
13420    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13421}
13422
13423pub fn hunks_for_rows(
13424    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13425    multi_buffer_snapshot: &MultiBufferSnapshot,
13426) -> Vec<MultiBufferDiffHunk> {
13427    let mut hunks = Vec::new();
13428    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13429        HashMap::default();
13430    for selected_multi_buffer_rows in rows {
13431        let query_rows =
13432            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13433        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13434            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13435            // when the caret is just above or just below the deleted hunk.
13436            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13437            let related_to_selection = if allow_adjacent {
13438                hunk.row_range.overlaps(&query_rows)
13439                    || hunk.row_range.start == query_rows.end
13440                    || hunk.row_range.end == query_rows.start
13441            } else {
13442                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13443                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13444                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13445                    || selected_multi_buffer_rows.end == hunk.row_range.start
13446            };
13447            if related_to_selection {
13448                if !processed_buffer_rows
13449                    .entry(hunk.buffer_id)
13450                    .or_default()
13451                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13452                {
13453                    continue;
13454                }
13455                hunks.push(hunk);
13456            }
13457        }
13458    }
13459
13460    hunks
13461}
13462
13463pub trait CollaborationHub {
13464    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13465    fn user_participant_indices<'a>(
13466        &self,
13467        cx: &'a AppContext,
13468    ) -> &'a HashMap<u64, ParticipantIndex>;
13469    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13470}
13471
13472impl CollaborationHub for Model<Project> {
13473    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13474        self.read(cx).collaborators()
13475    }
13476
13477    fn user_participant_indices<'a>(
13478        &self,
13479        cx: &'a AppContext,
13480    ) -> &'a HashMap<u64, ParticipantIndex> {
13481        self.read(cx).user_store().read(cx).participant_indices()
13482    }
13483
13484    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13485        let this = self.read(cx);
13486        let user_ids = this.collaborators().values().map(|c| c.user_id);
13487        this.user_store().read_with(cx, |user_store, cx| {
13488            user_store.participant_names(user_ids, cx)
13489        })
13490    }
13491}
13492
13493pub trait SemanticsProvider {
13494    fn hover(
13495        &self,
13496        buffer: &Model<Buffer>,
13497        position: text::Anchor,
13498        cx: &mut AppContext,
13499    ) -> Option<Task<Vec<project::Hover>>>;
13500
13501    fn inlay_hints(
13502        &self,
13503        buffer_handle: Model<Buffer>,
13504        range: Range<text::Anchor>,
13505        cx: &mut AppContext,
13506    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13507
13508    fn resolve_inlay_hint(
13509        &self,
13510        hint: InlayHint,
13511        buffer_handle: Model<Buffer>,
13512        server_id: LanguageServerId,
13513        cx: &mut AppContext,
13514    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13515
13516    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13517
13518    fn document_highlights(
13519        &self,
13520        buffer: &Model<Buffer>,
13521        position: text::Anchor,
13522        cx: &mut AppContext,
13523    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13524
13525    fn definitions(
13526        &self,
13527        buffer: &Model<Buffer>,
13528        position: text::Anchor,
13529        kind: GotoDefinitionKind,
13530        cx: &mut AppContext,
13531    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13532
13533    fn range_for_rename(
13534        &self,
13535        buffer: &Model<Buffer>,
13536        position: text::Anchor,
13537        cx: &mut AppContext,
13538    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13539
13540    fn perform_rename(
13541        &self,
13542        buffer: &Model<Buffer>,
13543        position: text::Anchor,
13544        new_name: String,
13545        cx: &mut AppContext,
13546    ) -> Option<Task<Result<ProjectTransaction>>>;
13547}
13548
13549pub trait CompletionProvider {
13550    fn completions(
13551        &self,
13552        buffer: &Model<Buffer>,
13553        buffer_position: text::Anchor,
13554        trigger: CompletionContext,
13555        cx: &mut ViewContext<Editor>,
13556    ) -> Task<Result<Vec<Completion>>>;
13557
13558    fn resolve_completions(
13559        &self,
13560        buffer: Model<Buffer>,
13561        completion_indices: Vec<usize>,
13562        completions: Arc<RwLock<Box<[Completion]>>>,
13563        cx: &mut ViewContext<Editor>,
13564    ) -> Task<Result<bool>>;
13565
13566    fn apply_additional_edits_for_completion(
13567        &self,
13568        buffer: Model<Buffer>,
13569        completion: Completion,
13570        push_to_history: bool,
13571        cx: &mut ViewContext<Editor>,
13572    ) -> Task<Result<Option<language::Transaction>>>;
13573
13574    fn is_completion_trigger(
13575        &self,
13576        buffer: &Model<Buffer>,
13577        position: language::Anchor,
13578        text: &str,
13579        trigger_in_words: bool,
13580        cx: &mut ViewContext<Editor>,
13581    ) -> bool;
13582
13583    fn sort_completions(&self) -> bool {
13584        true
13585    }
13586}
13587
13588pub trait CodeActionProvider {
13589    fn code_actions(
13590        &self,
13591        buffer: &Model<Buffer>,
13592        range: Range<text::Anchor>,
13593        cx: &mut WindowContext,
13594    ) -> Task<Result<Vec<CodeAction>>>;
13595
13596    fn apply_code_action(
13597        &self,
13598        buffer_handle: Model<Buffer>,
13599        action: CodeAction,
13600        excerpt_id: ExcerptId,
13601        push_to_history: bool,
13602        cx: &mut WindowContext,
13603    ) -> Task<Result<ProjectTransaction>>;
13604}
13605
13606impl CodeActionProvider for Model<Project> {
13607    fn code_actions(
13608        &self,
13609        buffer: &Model<Buffer>,
13610        range: Range<text::Anchor>,
13611        cx: &mut WindowContext,
13612    ) -> Task<Result<Vec<CodeAction>>> {
13613        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13614    }
13615
13616    fn apply_code_action(
13617        &self,
13618        buffer_handle: Model<Buffer>,
13619        action: CodeAction,
13620        _excerpt_id: ExcerptId,
13621        push_to_history: bool,
13622        cx: &mut WindowContext,
13623    ) -> Task<Result<ProjectTransaction>> {
13624        self.update(cx, |project, cx| {
13625            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13626        })
13627    }
13628}
13629
13630fn snippet_completions(
13631    project: &Project,
13632    buffer: &Model<Buffer>,
13633    buffer_position: text::Anchor,
13634    cx: &mut AppContext,
13635) -> Vec<Completion> {
13636    let language = buffer.read(cx).language_at(buffer_position);
13637    let language_name = language.as_ref().map(|language| language.lsp_id());
13638    let snippet_store = project.snippets().read(cx);
13639    let snippets = snippet_store.snippets_for(language_name, cx);
13640
13641    if snippets.is_empty() {
13642        return vec![];
13643    }
13644    let snapshot = buffer.read(cx).text_snapshot();
13645    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13646
13647    let scope = language.map(|language| language.default_scope());
13648    let classifier = CharClassifier::new(scope).for_completion(true);
13649    let mut last_word = chars
13650        .take_while(|c| classifier.is_word(*c))
13651        .collect::<String>();
13652    last_word = last_word.chars().rev().collect();
13653    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13654    let to_lsp = |point: &text::Anchor| {
13655        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13656        point_to_lsp(end)
13657    };
13658    let lsp_end = to_lsp(&buffer_position);
13659    snippets
13660        .into_iter()
13661        .filter_map(|snippet| {
13662            let matching_prefix = snippet
13663                .prefix
13664                .iter()
13665                .find(|prefix| prefix.starts_with(&last_word))?;
13666            let start = as_offset - last_word.len();
13667            let start = snapshot.anchor_before(start);
13668            let range = start..buffer_position;
13669            let lsp_start = to_lsp(&start);
13670            let lsp_range = lsp::Range {
13671                start: lsp_start,
13672                end: lsp_end,
13673            };
13674            Some(Completion {
13675                old_range: range,
13676                new_text: snippet.body.clone(),
13677                label: CodeLabel {
13678                    text: matching_prefix.clone(),
13679                    runs: vec![],
13680                    filter_range: 0..matching_prefix.len(),
13681                },
13682                server_id: LanguageServerId(usize::MAX),
13683                documentation: snippet.description.clone().map(Documentation::SingleLine),
13684                lsp_completion: lsp::CompletionItem {
13685                    label: snippet.prefix.first().unwrap().clone(),
13686                    kind: Some(CompletionItemKind::SNIPPET),
13687                    label_details: snippet.description.as_ref().map(|description| {
13688                        lsp::CompletionItemLabelDetails {
13689                            detail: Some(description.clone()),
13690                            description: None,
13691                        }
13692                    }),
13693                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13694                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13695                        lsp::InsertReplaceEdit {
13696                            new_text: snippet.body.clone(),
13697                            insert: lsp_range,
13698                            replace: lsp_range,
13699                        },
13700                    )),
13701                    filter_text: Some(snippet.body.clone()),
13702                    sort_text: Some(char::MAX.to_string()),
13703                    ..Default::default()
13704                },
13705                confirm: None,
13706            })
13707        })
13708        .collect()
13709}
13710
13711impl CompletionProvider for Model<Project> {
13712    fn completions(
13713        &self,
13714        buffer: &Model<Buffer>,
13715        buffer_position: text::Anchor,
13716        options: CompletionContext,
13717        cx: &mut ViewContext<Editor>,
13718    ) -> Task<Result<Vec<Completion>>> {
13719        self.update(cx, |project, cx| {
13720            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13721            let project_completions = project.completions(buffer, buffer_position, options, cx);
13722            cx.background_executor().spawn(async move {
13723                let mut completions = project_completions.await?;
13724                //let snippets = snippets.into_iter().;
13725                completions.extend(snippets);
13726                Ok(completions)
13727            })
13728        })
13729    }
13730
13731    fn resolve_completions(
13732        &self,
13733        buffer: Model<Buffer>,
13734        completion_indices: Vec<usize>,
13735        completions: Arc<RwLock<Box<[Completion]>>>,
13736        cx: &mut ViewContext<Editor>,
13737    ) -> Task<Result<bool>> {
13738        self.update(cx, |project, cx| {
13739            project.resolve_completions(buffer, completion_indices, completions, cx)
13740        })
13741    }
13742
13743    fn apply_additional_edits_for_completion(
13744        &self,
13745        buffer: Model<Buffer>,
13746        completion: Completion,
13747        push_to_history: bool,
13748        cx: &mut ViewContext<Editor>,
13749    ) -> Task<Result<Option<language::Transaction>>> {
13750        self.update(cx, |project, cx| {
13751            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13752        })
13753    }
13754
13755    fn is_completion_trigger(
13756        &self,
13757        buffer: &Model<Buffer>,
13758        position: language::Anchor,
13759        text: &str,
13760        trigger_in_words: bool,
13761        cx: &mut ViewContext<Editor>,
13762    ) -> bool {
13763        if !EditorSettings::get_global(cx).show_completions_on_input {
13764            return false;
13765        }
13766
13767        let mut chars = text.chars();
13768        let char = if let Some(char) = chars.next() {
13769            char
13770        } else {
13771            return false;
13772        };
13773        if chars.next().is_some() {
13774            return false;
13775        }
13776
13777        let buffer = buffer.read(cx);
13778        let classifier = buffer
13779            .snapshot()
13780            .char_classifier_at(position)
13781            .for_completion(true);
13782        if trigger_in_words && classifier.is_word(char) {
13783            return true;
13784        }
13785
13786        buffer.completion_triggers().contains(text)
13787    }
13788}
13789
13790impl SemanticsProvider for Model<Project> {
13791    fn hover(
13792        &self,
13793        buffer: &Model<Buffer>,
13794        position: text::Anchor,
13795        cx: &mut AppContext,
13796    ) -> Option<Task<Vec<project::Hover>>> {
13797        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13798    }
13799
13800    fn document_highlights(
13801        &self,
13802        buffer: &Model<Buffer>,
13803        position: text::Anchor,
13804        cx: &mut AppContext,
13805    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13806        Some(self.update(cx, |project, cx| {
13807            project.document_highlights(buffer, position, cx)
13808        }))
13809    }
13810
13811    fn definitions(
13812        &self,
13813        buffer: &Model<Buffer>,
13814        position: text::Anchor,
13815        kind: GotoDefinitionKind,
13816        cx: &mut AppContext,
13817    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13818        Some(self.update(cx, |project, cx| match kind {
13819            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13820            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13821            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13822            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13823        }))
13824    }
13825
13826    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13827        // TODO: make this work for remote projects
13828        self.read(cx)
13829            .language_servers_for_buffer(buffer.read(cx), cx)
13830            .any(
13831                |(_, server)| match server.capabilities().inlay_hint_provider {
13832                    Some(lsp::OneOf::Left(enabled)) => enabled,
13833                    Some(lsp::OneOf::Right(_)) => true,
13834                    None => false,
13835                },
13836            )
13837    }
13838
13839    fn inlay_hints(
13840        &self,
13841        buffer_handle: Model<Buffer>,
13842        range: Range<text::Anchor>,
13843        cx: &mut AppContext,
13844    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13845        Some(self.update(cx, |project, cx| {
13846            project.inlay_hints(buffer_handle, range, cx)
13847        }))
13848    }
13849
13850    fn resolve_inlay_hint(
13851        &self,
13852        hint: InlayHint,
13853        buffer_handle: Model<Buffer>,
13854        server_id: LanguageServerId,
13855        cx: &mut AppContext,
13856    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13857        Some(self.update(cx, |project, cx| {
13858            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13859        }))
13860    }
13861
13862    fn range_for_rename(
13863        &self,
13864        buffer: &Model<Buffer>,
13865        position: text::Anchor,
13866        cx: &mut AppContext,
13867    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13868        Some(self.update(cx, |project, cx| {
13869            project.prepare_rename(buffer.clone(), position, cx)
13870        }))
13871    }
13872
13873    fn perform_rename(
13874        &self,
13875        buffer: &Model<Buffer>,
13876        position: text::Anchor,
13877        new_name: String,
13878        cx: &mut AppContext,
13879    ) -> Option<Task<Result<ProjectTransaction>>> {
13880        Some(self.update(cx, |project, cx| {
13881            project.perform_rename(buffer.clone(), position, new_name, cx)
13882        }))
13883    }
13884}
13885
13886fn inlay_hint_settings(
13887    location: Anchor,
13888    snapshot: &MultiBufferSnapshot,
13889    cx: &mut ViewContext<'_, Editor>,
13890) -> InlayHintSettings {
13891    let file = snapshot.file_at(location);
13892    let language = snapshot.language_at(location).map(|l| l.name());
13893    language_settings(language, file, cx).inlay_hints
13894}
13895
13896fn consume_contiguous_rows(
13897    contiguous_row_selections: &mut Vec<Selection<Point>>,
13898    selection: &Selection<Point>,
13899    display_map: &DisplaySnapshot,
13900    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13901) -> (MultiBufferRow, MultiBufferRow) {
13902    contiguous_row_selections.push(selection.clone());
13903    let start_row = MultiBufferRow(selection.start.row);
13904    let mut end_row = ending_row(selection, display_map);
13905
13906    while let Some(next_selection) = selections.peek() {
13907        if next_selection.start.row <= end_row.0 {
13908            end_row = ending_row(next_selection, display_map);
13909            contiguous_row_selections.push(selections.next().unwrap().clone());
13910        } else {
13911            break;
13912        }
13913    }
13914    (start_row, end_row)
13915}
13916
13917fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13918    if next_selection.end.column > 0 || next_selection.is_empty() {
13919        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13920    } else {
13921        MultiBufferRow(next_selection.end.row)
13922    }
13923}
13924
13925impl EditorSnapshot {
13926    pub fn remote_selections_in_range<'a>(
13927        &'a self,
13928        range: &'a Range<Anchor>,
13929        collaboration_hub: &dyn CollaborationHub,
13930        cx: &'a AppContext,
13931    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13932        let participant_names = collaboration_hub.user_names(cx);
13933        let participant_indices = collaboration_hub.user_participant_indices(cx);
13934        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13935        let collaborators_by_replica_id = collaborators_by_peer_id
13936            .iter()
13937            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13938            .collect::<HashMap<_, _>>();
13939        self.buffer_snapshot
13940            .selections_in_range(range, false)
13941            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13942                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13943                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13944                let user_name = participant_names.get(&collaborator.user_id).cloned();
13945                Some(RemoteSelection {
13946                    replica_id,
13947                    selection,
13948                    cursor_shape,
13949                    line_mode,
13950                    participant_index,
13951                    peer_id: collaborator.peer_id,
13952                    user_name,
13953                })
13954            })
13955    }
13956
13957    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13958        self.display_snapshot.buffer_snapshot.language_at(position)
13959    }
13960
13961    pub fn is_focused(&self) -> bool {
13962        self.is_focused
13963    }
13964
13965    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13966        self.placeholder_text.as_ref()
13967    }
13968
13969    pub fn scroll_position(&self) -> gpui::Point<f32> {
13970        self.scroll_anchor.scroll_position(&self.display_snapshot)
13971    }
13972
13973    fn gutter_dimensions(
13974        &self,
13975        font_id: FontId,
13976        font_size: Pixels,
13977        em_width: Pixels,
13978        em_advance: Pixels,
13979        max_line_number_width: Pixels,
13980        cx: &AppContext,
13981    ) -> GutterDimensions {
13982        if !self.show_gutter {
13983            return GutterDimensions::default();
13984        }
13985        let descent = cx.text_system().descent(font_id, font_size);
13986
13987        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13988            matches!(
13989                ProjectSettings::get_global(cx).git.git_gutter,
13990                Some(GitGutterSetting::TrackedFiles)
13991            )
13992        });
13993        let gutter_settings = EditorSettings::get_global(cx).gutter;
13994        let show_line_numbers = self
13995            .show_line_numbers
13996            .unwrap_or(gutter_settings.line_numbers);
13997        let line_gutter_width = if show_line_numbers {
13998            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13999            let min_width_for_number_on_gutter = em_advance * 4.0;
14000            max_line_number_width.max(min_width_for_number_on_gutter)
14001        } else {
14002            0.0.into()
14003        };
14004
14005        let show_code_actions = self
14006            .show_code_actions
14007            .unwrap_or(gutter_settings.code_actions);
14008
14009        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14010
14011        let git_blame_entries_width =
14012            self.git_blame_gutter_max_author_length
14013                .map(|max_author_length| {
14014                    // Length of the author name, but also space for the commit hash,
14015                    // the spacing and the timestamp.
14016                    let max_char_count = max_author_length
14017                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14018                        + 7 // length of commit sha
14019                        + 14 // length of max relative timestamp ("60 minutes ago")
14020                        + 4; // gaps and margins
14021
14022                    em_advance * max_char_count
14023                });
14024
14025        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14026        left_padding += if show_code_actions || show_runnables {
14027            em_width * 3.0
14028        } else if show_git_gutter && show_line_numbers {
14029            em_width * 2.0
14030        } else if show_git_gutter || show_line_numbers {
14031            em_width
14032        } else {
14033            px(0.)
14034        };
14035
14036        let right_padding = if gutter_settings.folds && show_line_numbers {
14037            em_width * 4.0
14038        } else if gutter_settings.folds {
14039            em_width * 3.0
14040        } else if show_line_numbers {
14041            em_width
14042        } else {
14043            px(0.)
14044        };
14045
14046        GutterDimensions {
14047            left_padding,
14048            right_padding,
14049            width: line_gutter_width + left_padding + right_padding,
14050            margin: -descent,
14051            git_blame_entries_width,
14052        }
14053    }
14054
14055    pub fn render_crease_toggle(
14056        &self,
14057        buffer_row: MultiBufferRow,
14058        row_contains_cursor: bool,
14059        editor: View<Editor>,
14060        cx: &mut WindowContext,
14061    ) -> Option<AnyElement> {
14062        let folded = self.is_line_folded(buffer_row);
14063        let mut is_foldable = false;
14064
14065        if let Some(crease) = self
14066            .crease_snapshot
14067            .query_row(buffer_row, &self.buffer_snapshot)
14068        {
14069            is_foldable = true;
14070            match crease {
14071                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14072                    if let Some(render_toggle) = render_toggle {
14073                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14074                            if folded {
14075                                editor.update(cx, |editor, cx| {
14076                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14077                                });
14078                            } else {
14079                                editor.update(cx, |editor, cx| {
14080                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14081                                });
14082                            }
14083                        });
14084                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14085                    }
14086                }
14087            }
14088        }
14089
14090        is_foldable |= self.starts_indent(buffer_row);
14091
14092        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14093            Some(
14094                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14095                    .selected(folded)
14096                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14097                        if folded {
14098                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14099                        } else {
14100                            this.fold_at(&FoldAt { buffer_row }, cx);
14101                        }
14102                    }))
14103                    .into_any_element(),
14104            )
14105        } else {
14106            None
14107        }
14108    }
14109
14110    pub fn render_crease_trailer(
14111        &self,
14112        buffer_row: MultiBufferRow,
14113        cx: &mut WindowContext,
14114    ) -> Option<AnyElement> {
14115        let folded = self.is_line_folded(buffer_row);
14116        if let Crease::Inline { render_trailer, .. } = self
14117            .crease_snapshot
14118            .query_row(buffer_row, &self.buffer_snapshot)?
14119        {
14120            let render_trailer = render_trailer.as_ref()?;
14121            Some(render_trailer(buffer_row, folded, cx))
14122        } else {
14123            None
14124        }
14125    }
14126}
14127
14128impl Deref for EditorSnapshot {
14129    type Target = DisplaySnapshot;
14130
14131    fn deref(&self) -> &Self::Target {
14132        &self.display_snapshot
14133    }
14134}
14135
14136#[derive(Clone, Debug, PartialEq, Eq)]
14137pub enum EditorEvent {
14138    InputIgnored {
14139        text: Arc<str>,
14140    },
14141    InputHandled {
14142        utf16_range_to_replace: Option<Range<isize>>,
14143        text: Arc<str>,
14144    },
14145    ExcerptsAdded {
14146        buffer: Model<Buffer>,
14147        predecessor: ExcerptId,
14148        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14149    },
14150    ExcerptsRemoved {
14151        ids: Vec<ExcerptId>,
14152    },
14153    ExcerptsEdited {
14154        ids: Vec<ExcerptId>,
14155    },
14156    ExcerptsExpanded {
14157        ids: Vec<ExcerptId>,
14158    },
14159    BufferEdited,
14160    Edited {
14161        transaction_id: clock::Lamport,
14162    },
14163    Reparsed(BufferId),
14164    Focused,
14165    FocusedIn,
14166    Blurred,
14167    DirtyChanged,
14168    Saved,
14169    TitleChanged,
14170    DiffBaseChanged,
14171    SelectionsChanged {
14172        local: bool,
14173    },
14174    ScrollPositionChanged {
14175        local: bool,
14176        autoscroll: bool,
14177    },
14178    Closed,
14179    TransactionUndone {
14180        transaction_id: clock::Lamport,
14181    },
14182    TransactionBegun {
14183        transaction_id: clock::Lamport,
14184    },
14185    Reloaded,
14186    CursorShapeChanged,
14187}
14188
14189impl EventEmitter<EditorEvent> for Editor {}
14190
14191impl FocusableView for Editor {
14192    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14193        self.focus_handle.clone()
14194    }
14195}
14196
14197impl Render for Editor {
14198    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14199        let settings = ThemeSettings::get_global(cx);
14200
14201        let mut text_style = match self.mode {
14202            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14203                color: cx.theme().colors().editor_foreground,
14204                font_family: settings.ui_font.family.clone(),
14205                font_features: settings.ui_font.features.clone(),
14206                font_fallbacks: settings.ui_font.fallbacks.clone(),
14207                font_size: rems(0.875).into(),
14208                font_weight: settings.ui_font.weight,
14209                line_height: relative(settings.buffer_line_height.value()),
14210                ..Default::default()
14211            },
14212            EditorMode::Full => TextStyle {
14213                color: cx.theme().colors().editor_foreground,
14214                font_family: settings.buffer_font.family.clone(),
14215                font_features: settings.buffer_font.features.clone(),
14216                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14217                font_size: settings.buffer_font_size(cx).into(),
14218                font_weight: settings.buffer_font.weight,
14219                line_height: relative(settings.buffer_line_height.value()),
14220                ..Default::default()
14221            },
14222        };
14223        if let Some(text_style_refinement) = &self.text_style_refinement {
14224            text_style.refine(text_style_refinement)
14225        }
14226
14227        let background = match self.mode {
14228            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14229            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14230            EditorMode::Full => cx.theme().colors().editor_background,
14231        };
14232
14233        EditorElement::new(
14234            cx.view(),
14235            EditorStyle {
14236                background,
14237                local_player: cx.theme().players().local(),
14238                text: text_style,
14239                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14240                syntax: cx.theme().syntax().clone(),
14241                status: cx.theme().status().clone(),
14242                inlay_hints_style: make_inlay_hints_style(cx),
14243                suggestions_style: HighlightStyle {
14244                    color: Some(cx.theme().status().predictive),
14245                    ..HighlightStyle::default()
14246                },
14247                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14248            },
14249        )
14250    }
14251}
14252
14253impl ViewInputHandler for Editor {
14254    fn text_for_range(
14255        &mut self,
14256        range_utf16: Range<usize>,
14257        cx: &mut ViewContext<Self>,
14258    ) -> Option<String> {
14259        Some(
14260            self.buffer
14261                .read(cx)
14262                .read(cx)
14263                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14264                .collect(),
14265        )
14266    }
14267
14268    fn selected_text_range(
14269        &mut self,
14270        ignore_disabled_input: bool,
14271        cx: &mut ViewContext<Self>,
14272    ) -> Option<UTF16Selection> {
14273        // Prevent the IME menu from appearing when holding down an alphabetic key
14274        // while input is disabled.
14275        if !ignore_disabled_input && !self.input_enabled {
14276            return None;
14277        }
14278
14279        let selection = self.selections.newest::<OffsetUtf16>(cx);
14280        let range = selection.range();
14281
14282        Some(UTF16Selection {
14283            range: range.start.0..range.end.0,
14284            reversed: selection.reversed,
14285        })
14286    }
14287
14288    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14289        let snapshot = self.buffer.read(cx).read(cx);
14290        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14291        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14292    }
14293
14294    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14295        self.clear_highlights::<InputComposition>(cx);
14296        self.ime_transaction.take();
14297    }
14298
14299    fn replace_text_in_range(
14300        &mut self,
14301        range_utf16: Option<Range<usize>>,
14302        text: &str,
14303        cx: &mut ViewContext<Self>,
14304    ) {
14305        if !self.input_enabled {
14306            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14307            return;
14308        }
14309
14310        self.transact(cx, |this, cx| {
14311            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14312                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14313                Some(this.selection_replacement_ranges(range_utf16, cx))
14314            } else {
14315                this.marked_text_ranges(cx)
14316            };
14317
14318            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14319                let newest_selection_id = this.selections.newest_anchor().id;
14320                this.selections
14321                    .all::<OffsetUtf16>(cx)
14322                    .iter()
14323                    .zip(ranges_to_replace.iter())
14324                    .find_map(|(selection, range)| {
14325                        if selection.id == newest_selection_id {
14326                            Some(
14327                                (range.start.0 as isize - selection.head().0 as isize)
14328                                    ..(range.end.0 as isize - selection.head().0 as isize),
14329                            )
14330                        } else {
14331                            None
14332                        }
14333                    })
14334            });
14335
14336            cx.emit(EditorEvent::InputHandled {
14337                utf16_range_to_replace: range_to_replace,
14338                text: text.into(),
14339            });
14340
14341            if let Some(new_selected_ranges) = new_selected_ranges {
14342                this.change_selections(None, cx, |selections| {
14343                    selections.select_ranges(new_selected_ranges)
14344                });
14345                this.backspace(&Default::default(), cx);
14346            }
14347
14348            this.handle_input(text, cx);
14349        });
14350
14351        if let Some(transaction) = self.ime_transaction {
14352            self.buffer.update(cx, |buffer, cx| {
14353                buffer.group_until_transaction(transaction, cx);
14354            });
14355        }
14356
14357        self.unmark_text(cx);
14358    }
14359
14360    fn replace_and_mark_text_in_range(
14361        &mut self,
14362        range_utf16: Option<Range<usize>>,
14363        text: &str,
14364        new_selected_range_utf16: Option<Range<usize>>,
14365        cx: &mut ViewContext<Self>,
14366    ) {
14367        if !self.input_enabled {
14368            return;
14369        }
14370
14371        let transaction = self.transact(cx, |this, cx| {
14372            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14373                let snapshot = this.buffer.read(cx).read(cx);
14374                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14375                    for marked_range in &mut marked_ranges {
14376                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14377                        marked_range.start.0 += relative_range_utf16.start;
14378                        marked_range.start =
14379                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14380                        marked_range.end =
14381                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14382                    }
14383                }
14384                Some(marked_ranges)
14385            } else if let Some(range_utf16) = range_utf16 {
14386                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14387                Some(this.selection_replacement_ranges(range_utf16, cx))
14388            } else {
14389                None
14390            };
14391
14392            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14393                let newest_selection_id = this.selections.newest_anchor().id;
14394                this.selections
14395                    .all::<OffsetUtf16>(cx)
14396                    .iter()
14397                    .zip(ranges_to_replace.iter())
14398                    .find_map(|(selection, range)| {
14399                        if selection.id == newest_selection_id {
14400                            Some(
14401                                (range.start.0 as isize - selection.head().0 as isize)
14402                                    ..(range.end.0 as isize - selection.head().0 as isize),
14403                            )
14404                        } else {
14405                            None
14406                        }
14407                    })
14408            });
14409
14410            cx.emit(EditorEvent::InputHandled {
14411                utf16_range_to_replace: range_to_replace,
14412                text: text.into(),
14413            });
14414
14415            if let Some(ranges) = ranges_to_replace {
14416                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14417            }
14418
14419            let marked_ranges = {
14420                let snapshot = this.buffer.read(cx).read(cx);
14421                this.selections
14422                    .disjoint_anchors()
14423                    .iter()
14424                    .map(|selection| {
14425                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14426                    })
14427                    .collect::<Vec<_>>()
14428            };
14429
14430            if text.is_empty() {
14431                this.unmark_text(cx);
14432            } else {
14433                this.highlight_text::<InputComposition>(
14434                    marked_ranges.clone(),
14435                    HighlightStyle {
14436                        underline: Some(UnderlineStyle {
14437                            thickness: px(1.),
14438                            color: None,
14439                            wavy: false,
14440                        }),
14441                        ..Default::default()
14442                    },
14443                    cx,
14444                );
14445            }
14446
14447            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14448            let use_autoclose = this.use_autoclose;
14449            let use_auto_surround = this.use_auto_surround;
14450            this.set_use_autoclose(false);
14451            this.set_use_auto_surround(false);
14452            this.handle_input(text, cx);
14453            this.set_use_autoclose(use_autoclose);
14454            this.set_use_auto_surround(use_auto_surround);
14455
14456            if let Some(new_selected_range) = new_selected_range_utf16 {
14457                let snapshot = this.buffer.read(cx).read(cx);
14458                let new_selected_ranges = marked_ranges
14459                    .into_iter()
14460                    .map(|marked_range| {
14461                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14462                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14463                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14464                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14465                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14466                    })
14467                    .collect::<Vec<_>>();
14468
14469                drop(snapshot);
14470                this.change_selections(None, cx, |selections| {
14471                    selections.select_ranges(new_selected_ranges)
14472                });
14473            }
14474        });
14475
14476        self.ime_transaction = self.ime_transaction.or(transaction);
14477        if let Some(transaction) = self.ime_transaction {
14478            self.buffer.update(cx, |buffer, cx| {
14479                buffer.group_until_transaction(transaction, cx);
14480            });
14481        }
14482
14483        if self.text_highlights::<InputComposition>(cx).is_none() {
14484            self.ime_transaction.take();
14485        }
14486    }
14487
14488    fn bounds_for_range(
14489        &mut self,
14490        range_utf16: Range<usize>,
14491        element_bounds: gpui::Bounds<Pixels>,
14492        cx: &mut ViewContext<Self>,
14493    ) -> Option<gpui::Bounds<Pixels>> {
14494        let text_layout_details = self.text_layout_details(cx);
14495        let style = &text_layout_details.editor_style;
14496        let font_id = cx.text_system().resolve_font(&style.text.font());
14497        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14498        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14499
14500        let em_width = cx
14501            .text_system()
14502            .typographic_bounds(font_id, font_size, 'm')
14503            .unwrap()
14504            .size
14505            .width;
14506
14507        let snapshot = self.snapshot(cx);
14508        let scroll_position = snapshot.scroll_position();
14509        let scroll_left = scroll_position.x * em_width;
14510
14511        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14512        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14513            + self.gutter_dimensions.width;
14514        let y = line_height * (start.row().as_f32() - scroll_position.y);
14515
14516        Some(Bounds {
14517            origin: element_bounds.origin + point(x, y),
14518            size: size(em_width, line_height),
14519        })
14520    }
14521}
14522
14523trait SelectionExt {
14524    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14525    fn spanned_rows(
14526        &self,
14527        include_end_if_at_line_start: bool,
14528        map: &DisplaySnapshot,
14529    ) -> Range<MultiBufferRow>;
14530}
14531
14532impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14533    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14534        let start = self
14535            .start
14536            .to_point(&map.buffer_snapshot)
14537            .to_display_point(map);
14538        let end = self
14539            .end
14540            .to_point(&map.buffer_snapshot)
14541            .to_display_point(map);
14542        if self.reversed {
14543            end..start
14544        } else {
14545            start..end
14546        }
14547    }
14548
14549    fn spanned_rows(
14550        &self,
14551        include_end_if_at_line_start: bool,
14552        map: &DisplaySnapshot,
14553    ) -> Range<MultiBufferRow> {
14554        let start = self.start.to_point(&map.buffer_snapshot);
14555        let mut end = self.end.to_point(&map.buffer_snapshot);
14556        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14557            end.row -= 1;
14558        }
14559
14560        let buffer_start = map.prev_line_boundary(start).0;
14561        let buffer_end = map.next_line_boundary(end).0;
14562        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14563    }
14564}
14565
14566impl<T: InvalidationRegion> InvalidationStack<T> {
14567    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14568    where
14569        S: Clone + ToOffset,
14570    {
14571        while let Some(region) = self.last() {
14572            let all_selections_inside_invalidation_ranges =
14573                if selections.len() == region.ranges().len() {
14574                    selections
14575                        .iter()
14576                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14577                        .all(|(selection, invalidation_range)| {
14578                            let head = selection.head().to_offset(buffer);
14579                            invalidation_range.start <= head && invalidation_range.end >= head
14580                        })
14581                } else {
14582                    false
14583                };
14584
14585            if all_selections_inside_invalidation_ranges {
14586                break;
14587            } else {
14588                self.pop();
14589            }
14590        }
14591    }
14592}
14593
14594impl<T> Default for InvalidationStack<T> {
14595    fn default() -> Self {
14596        Self(Default::default())
14597    }
14598}
14599
14600impl<T> Deref for InvalidationStack<T> {
14601    type Target = Vec<T>;
14602
14603    fn deref(&self) -> &Self::Target {
14604        &self.0
14605    }
14606}
14607
14608impl<T> DerefMut for InvalidationStack<T> {
14609    fn deref_mut(&mut self) -> &mut Self::Target {
14610        &mut self.0
14611    }
14612}
14613
14614impl InvalidationRegion for SnippetState {
14615    fn ranges(&self) -> &[Range<Anchor>] {
14616        &self.ranges[self.active_index]
14617    }
14618}
14619
14620pub fn diagnostic_block_renderer(
14621    diagnostic: Diagnostic,
14622    max_message_rows: Option<u8>,
14623    allow_closing: bool,
14624    _is_valid: bool,
14625) -> RenderBlock {
14626    let (text_without_backticks, code_ranges) =
14627        highlight_diagnostic_message(&diagnostic, max_message_rows);
14628
14629    Arc::new(move |cx: &mut BlockContext| {
14630        let group_id: SharedString = cx.block_id.to_string().into();
14631
14632        let mut text_style = cx.text_style().clone();
14633        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14634        let theme_settings = ThemeSettings::get_global(cx);
14635        text_style.font_family = theme_settings.buffer_font.family.clone();
14636        text_style.font_style = theme_settings.buffer_font.style;
14637        text_style.font_features = theme_settings.buffer_font.features.clone();
14638        text_style.font_weight = theme_settings.buffer_font.weight;
14639
14640        let multi_line_diagnostic = diagnostic.message.contains('\n');
14641
14642        let buttons = |diagnostic: &Diagnostic| {
14643            if multi_line_diagnostic {
14644                v_flex()
14645            } else {
14646                h_flex()
14647            }
14648            .when(allow_closing, |div| {
14649                div.children(diagnostic.is_primary.then(|| {
14650                    IconButton::new("close-block", IconName::XCircle)
14651                        .icon_color(Color::Muted)
14652                        .size(ButtonSize::Compact)
14653                        .style(ButtonStyle::Transparent)
14654                        .visible_on_hover(group_id.clone())
14655                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14656                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14657                }))
14658            })
14659            .child(
14660                IconButton::new("copy-block", IconName::Copy)
14661                    .icon_color(Color::Muted)
14662                    .size(ButtonSize::Compact)
14663                    .style(ButtonStyle::Transparent)
14664                    .visible_on_hover(group_id.clone())
14665                    .on_click({
14666                        let message = diagnostic.message.clone();
14667                        move |_click, cx| {
14668                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14669                        }
14670                    })
14671                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14672            )
14673        };
14674
14675        let icon_size = buttons(&diagnostic)
14676            .into_any_element()
14677            .layout_as_root(AvailableSpace::min_size(), cx);
14678
14679        h_flex()
14680            .id(cx.block_id)
14681            .group(group_id.clone())
14682            .relative()
14683            .size_full()
14684            .block_mouse_down()
14685            .pl(cx.gutter_dimensions.width)
14686            .w(cx.max_width - cx.gutter_dimensions.full_width())
14687            .child(
14688                div()
14689                    .flex()
14690                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14691                    .flex_shrink(),
14692            )
14693            .child(buttons(&diagnostic))
14694            .child(div().flex().flex_shrink_0().child(
14695                StyledText::new(text_without_backticks.clone()).with_highlights(
14696                    &text_style,
14697                    code_ranges.iter().map(|range| {
14698                        (
14699                            range.clone(),
14700                            HighlightStyle {
14701                                font_weight: Some(FontWeight::BOLD),
14702                                ..Default::default()
14703                            },
14704                        )
14705                    }),
14706                ),
14707            ))
14708            .into_any_element()
14709    })
14710}
14711
14712pub fn highlight_diagnostic_message(
14713    diagnostic: &Diagnostic,
14714    mut max_message_rows: Option<u8>,
14715) -> (SharedString, Vec<Range<usize>>) {
14716    let mut text_without_backticks = String::new();
14717    let mut code_ranges = Vec::new();
14718
14719    if let Some(source) = &diagnostic.source {
14720        text_without_backticks.push_str(source);
14721        code_ranges.push(0..source.len());
14722        text_without_backticks.push_str(": ");
14723    }
14724
14725    let mut prev_offset = 0;
14726    let mut in_code_block = false;
14727    let has_row_limit = max_message_rows.is_some();
14728    let mut newline_indices = diagnostic
14729        .message
14730        .match_indices('\n')
14731        .filter(|_| has_row_limit)
14732        .map(|(ix, _)| ix)
14733        .fuse()
14734        .peekable();
14735
14736    for (quote_ix, _) in diagnostic
14737        .message
14738        .match_indices('`')
14739        .chain([(diagnostic.message.len(), "")])
14740    {
14741        let mut first_newline_ix = None;
14742        let mut last_newline_ix = None;
14743        while let Some(newline_ix) = newline_indices.peek() {
14744            if *newline_ix < quote_ix {
14745                if first_newline_ix.is_none() {
14746                    first_newline_ix = Some(*newline_ix);
14747                }
14748                last_newline_ix = Some(*newline_ix);
14749
14750                if let Some(rows_left) = &mut max_message_rows {
14751                    if *rows_left == 0 {
14752                        break;
14753                    } else {
14754                        *rows_left -= 1;
14755                    }
14756                }
14757                let _ = newline_indices.next();
14758            } else {
14759                break;
14760            }
14761        }
14762        let prev_len = text_without_backticks.len();
14763        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14764        text_without_backticks.push_str(new_text);
14765        if in_code_block {
14766            code_ranges.push(prev_len..text_without_backticks.len());
14767        }
14768        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14769        in_code_block = !in_code_block;
14770        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14771            text_without_backticks.push_str("...");
14772            break;
14773        }
14774    }
14775
14776    (text_without_backticks.into(), code_ranges)
14777}
14778
14779fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14780    match severity {
14781        DiagnosticSeverity::ERROR => colors.error,
14782        DiagnosticSeverity::WARNING => colors.warning,
14783        DiagnosticSeverity::INFORMATION => colors.info,
14784        DiagnosticSeverity::HINT => colors.info,
14785        _ => colors.ignored,
14786    }
14787}
14788
14789pub fn styled_runs_for_code_label<'a>(
14790    label: &'a CodeLabel,
14791    syntax_theme: &'a theme::SyntaxTheme,
14792) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14793    let fade_out = HighlightStyle {
14794        fade_out: Some(0.35),
14795        ..Default::default()
14796    };
14797
14798    let mut prev_end = label.filter_range.end;
14799    label
14800        .runs
14801        .iter()
14802        .enumerate()
14803        .flat_map(move |(ix, (range, highlight_id))| {
14804            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14805                style
14806            } else {
14807                return Default::default();
14808            };
14809            let mut muted_style = style;
14810            muted_style.highlight(fade_out);
14811
14812            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14813            if range.start >= label.filter_range.end {
14814                if range.start > prev_end {
14815                    runs.push((prev_end..range.start, fade_out));
14816                }
14817                runs.push((range.clone(), muted_style));
14818            } else if range.end <= label.filter_range.end {
14819                runs.push((range.clone(), style));
14820            } else {
14821                runs.push((range.start..label.filter_range.end, style));
14822                runs.push((label.filter_range.end..range.end, muted_style));
14823            }
14824            prev_end = cmp::max(prev_end, range.end);
14825
14826            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14827                runs.push((prev_end..label.text.len(), fade_out));
14828            }
14829
14830            runs
14831        })
14832}
14833
14834pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14835    let mut prev_index = 0;
14836    let mut prev_codepoint: Option<char> = None;
14837    text.char_indices()
14838        .chain([(text.len(), '\0')])
14839        .filter_map(move |(index, codepoint)| {
14840            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14841            let is_boundary = index == text.len()
14842                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14843                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14844            if is_boundary {
14845                let chunk = &text[prev_index..index];
14846                prev_index = index;
14847                Some(chunk)
14848            } else {
14849                None
14850            }
14851        })
14852}
14853
14854pub trait RangeToAnchorExt: Sized {
14855    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14856
14857    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14858        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14859        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14860    }
14861}
14862
14863impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14864    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14865        let start_offset = self.start.to_offset(snapshot);
14866        let end_offset = self.end.to_offset(snapshot);
14867        if start_offset == end_offset {
14868            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14869        } else {
14870            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14871        }
14872    }
14873}
14874
14875pub trait RowExt {
14876    fn as_f32(&self) -> f32;
14877
14878    fn next_row(&self) -> Self;
14879
14880    fn previous_row(&self) -> Self;
14881
14882    fn minus(&self, other: Self) -> u32;
14883}
14884
14885impl RowExt for DisplayRow {
14886    fn as_f32(&self) -> f32 {
14887        self.0 as f32
14888    }
14889
14890    fn next_row(&self) -> Self {
14891        Self(self.0 + 1)
14892    }
14893
14894    fn previous_row(&self) -> Self {
14895        Self(self.0.saturating_sub(1))
14896    }
14897
14898    fn minus(&self, other: Self) -> u32 {
14899        self.0 - other.0
14900    }
14901}
14902
14903impl RowExt for MultiBufferRow {
14904    fn as_f32(&self) -> f32 {
14905        self.0 as f32
14906    }
14907
14908    fn next_row(&self) -> Self {
14909        Self(self.0 + 1)
14910    }
14911
14912    fn previous_row(&self) -> Self {
14913        Self(self.0.saturating_sub(1))
14914    }
14915
14916    fn minus(&self, other: Self) -> u32 {
14917        self.0 - other.0
14918    }
14919}
14920
14921trait RowRangeExt {
14922    type Row;
14923
14924    fn len(&self) -> usize;
14925
14926    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14927}
14928
14929impl RowRangeExt for Range<MultiBufferRow> {
14930    type Row = MultiBufferRow;
14931
14932    fn len(&self) -> usize {
14933        (self.end.0 - self.start.0) as usize
14934    }
14935
14936    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14937        (self.start.0..self.end.0).map(MultiBufferRow)
14938    }
14939}
14940
14941impl RowRangeExt for Range<DisplayRow> {
14942    type Row = DisplayRow;
14943
14944    fn len(&self) -> usize {
14945        (self.end.0 - self.start.0) as usize
14946    }
14947
14948    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14949        (self.start.0..self.end.0).map(DisplayRow)
14950    }
14951}
14952
14953fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14954    if hunk.diff_base_byte_range.is_empty() {
14955        DiffHunkStatus::Added
14956    } else if hunk.row_range.is_empty() {
14957        DiffHunkStatus::Removed
14958    } else {
14959        DiffHunkStatus::Modified
14960    }
14961}
14962
14963/// If select range has more than one line, we
14964/// just point the cursor to range.start.
14965fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14966    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14967        range
14968    } else {
14969        range.start..range.start
14970    }
14971}
14972
14973const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);