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_ranges = 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_ranges.push((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_ranges(refold_ranges, 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_ranges = 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_ranges.push((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_ranges(refold_ranges, 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: Box::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                                        .pl(cx.anchor_x)
10435                                        .child(EditorElement::new(
10436                                            &rename_editor,
10437                                            EditorStyle {
10438                                                background: cx.theme().system().transparent,
10439                                                local_player: cx.editor_style.local_player,
10440                                                text: text_style,
10441                                                scrollbar_width: cx.editor_style.scrollbar_width,
10442                                                syntax: cx.editor_style.syntax.clone(),
10443                                                status: cx.editor_style.status.clone(),
10444                                                inlay_hints_style: HighlightStyle {
10445                                                    font_weight: Some(FontWeight::BOLD),
10446                                                    ..make_inlay_hints_style(cx)
10447                                                },
10448                                                suggestions_style: HighlightStyle {
10449                                                    color: Some(cx.theme().status().predictive),
10450                                                    ..HighlightStyle::default()
10451                                                },
10452                                                ..EditorStyle::default()
10453                                            },
10454                                        ))
10455                                        .into_any_element()
10456                                }
10457                            }),
10458                            priority: 0,
10459                        }],
10460                        Some(Autoscroll::fit()),
10461                        cx,
10462                    )[0];
10463                    this.pending_rename = Some(RenameState {
10464                        range,
10465                        old_name,
10466                        editor: rename_editor,
10467                        block_id,
10468                    });
10469                })?;
10470            }
10471
10472            Ok(())
10473        }))
10474    }
10475
10476    pub fn confirm_rename(
10477        &mut self,
10478        _: &ConfirmRename,
10479        cx: &mut ViewContext<Self>,
10480    ) -> Option<Task<Result<()>>> {
10481        let rename = self.take_rename(false, cx)?;
10482        let workspace = self.workspace()?.downgrade();
10483        let (buffer, start) = self
10484            .buffer
10485            .read(cx)
10486            .text_anchor_for_position(rename.range.start, cx)?;
10487        let (end_buffer, _) = self
10488            .buffer
10489            .read(cx)
10490            .text_anchor_for_position(rename.range.end, cx)?;
10491        if buffer != end_buffer {
10492            return None;
10493        }
10494
10495        let old_name = rename.old_name;
10496        let new_name = rename.editor.read(cx).text(cx);
10497
10498        let rename = self.semantics_provider.as_ref()?.perform_rename(
10499            &buffer,
10500            start,
10501            new_name.clone(),
10502            cx,
10503        )?;
10504
10505        Some(cx.spawn(|editor, mut cx| async move {
10506            let project_transaction = rename.await?;
10507            Self::open_project_transaction(
10508                &editor,
10509                workspace,
10510                project_transaction,
10511                format!("Rename: {}{}", old_name, new_name),
10512                cx.clone(),
10513            )
10514            .await?;
10515
10516            editor.update(&mut cx, |editor, cx| {
10517                editor.refresh_document_highlights(cx);
10518            })?;
10519            Ok(())
10520        }))
10521    }
10522
10523    fn take_rename(
10524        &mut self,
10525        moving_cursor: bool,
10526        cx: &mut ViewContext<Self>,
10527    ) -> Option<RenameState> {
10528        let rename = self.pending_rename.take()?;
10529        if rename.editor.focus_handle(cx).is_focused(cx) {
10530            cx.focus(&self.focus_handle);
10531        }
10532
10533        self.remove_blocks(
10534            [rename.block_id].into_iter().collect(),
10535            Some(Autoscroll::fit()),
10536            cx,
10537        );
10538        self.clear_highlights::<Rename>(cx);
10539        self.show_local_selections = true;
10540
10541        if moving_cursor {
10542            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10543                editor.selections.newest::<usize>(cx).head()
10544            });
10545
10546            // Update the selection to match the position of the selection inside
10547            // the rename editor.
10548            let snapshot = self.buffer.read(cx).read(cx);
10549            let rename_range = rename.range.to_offset(&snapshot);
10550            let cursor_in_editor = snapshot
10551                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10552                .min(rename_range.end);
10553            drop(snapshot);
10554
10555            self.change_selections(None, cx, |s| {
10556                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10557            });
10558        } else {
10559            self.refresh_document_highlights(cx);
10560        }
10561
10562        Some(rename)
10563    }
10564
10565    pub fn pending_rename(&self) -> Option<&RenameState> {
10566        self.pending_rename.as_ref()
10567    }
10568
10569    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10570        let project = match &self.project {
10571            Some(project) => project.clone(),
10572            None => return None,
10573        };
10574
10575        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10576    }
10577
10578    fn format_selections(
10579        &mut self,
10580        _: &FormatSelections,
10581        cx: &mut ViewContext<Self>,
10582    ) -> Option<Task<Result<()>>> {
10583        let project = match &self.project {
10584            Some(project) => project.clone(),
10585            None => return None,
10586        };
10587
10588        let selections = self
10589            .selections
10590            .all_adjusted(cx)
10591            .into_iter()
10592            .filter(|s| !s.is_empty())
10593            .collect_vec();
10594
10595        Some(self.perform_format(
10596            project,
10597            FormatTrigger::Manual,
10598            FormatTarget::Ranges(selections),
10599            cx,
10600        ))
10601    }
10602
10603    fn perform_format(
10604        &mut self,
10605        project: Model<Project>,
10606        trigger: FormatTrigger,
10607        target: FormatTarget,
10608        cx: &mut ViewContext<Self>,
10609    ) -> Task<Result<()>> {
10610        let buffer = self.buffer().clone();
10611        let mut buffers = buffer.read(cx).all_buffers();
10612        if trigger == FormatTrigger::Save {
10613            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10614        }
10615
10616        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10617        let format = project.update(cx, |project, cx| {
10618            project.format(buffers, true, trigger, target, cx)
10619        });
10620
10621        cx.spawn(|_, mut cx| async move {
10622            let transaction = futures::select_biased! {
10623                () = timeout => {
10624                    log::warn!("timed out waiting for formatting");
10625                    None
10626                }
10627                transaction = format.log_err().fuse() => transaction,
10628            };
10629
10630            buffer
10631                .update(&mut cx, |buffer, cx| {
10632                    if let Some(transaction) = transaction {
10633                        if !buffer.is_singleton() {
10634                            buffer.push_transaction(&transaction.0, cx);
10635                        }
10636                    }
10637
10638                    cx.notify();
10639                })
10640                .ok();
10641
10642            Ok(())
10643        })
10644    }
10645
10646    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10647        if let Some(project) = self.project.clone() {
10648            self.buffer.update(cx, |multi_buffer, cx| {
10649                project.update(cx, |project, cx| {
10650                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10651                });
10652            })
10653        }
10654    }
10655
10656    fn cancel_language_server_work(
10657        &mut self,
10658        _: &actions::CancelLanguageServerWork,
10659        cx: &mut ViewContext<Self>,
10660    ) {
10661        if let Some(project) = self.project.clone() {
10662            self.buffer.update(cx, |multi_buffer, cx| {
10663                project.update(cx, |project, cx| {
10664                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10665                });
10666            })
10667        }
10668    }
10669
10670    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10671        cx.show_character_palette();
10672    }
10673
10674    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10675        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10676            let buffer = self.buffer.read(cx).snapshot(cx);
10677            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10678            let is_valid = buffer
10679                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10680                .any(|entry| {
10681                    entry.diagnostic.is_primary
10682                        && !entry.range.is_empty()
10683                        && entry.range.start == primary_range_start
10684                        && entry.diagnostic.message == active_diagnostics.primary_message
10685                });
10686
10687            if is_valid != active_diagnostics.is_valid {
10688                active_diagnostics.is_valid = is_valid;
10689                let mut new_styles = HashMap::default();
10690                for (block_id, diagnostic) in &active_diagnostics.blocks {
10691                    new_styles.insert(
10692                        *block_id,
10693                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10694                    );
10695                }
10696                self.display_map.update(cx, |display_map, _cx| {
10697                    display_map.replace_blocks(new_styles)
10698                });
10699            }
10700        }
10701    }
10702
10703    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10704        self.dismiss_diagnostics(cx);
10705        let snapshot = self.snapshot(cx);
10706        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10707            let buffer = self.buffer.read(cx).snapshot(cx);
10708
10709            let mut primary_range = None;
10710            let mut primary_message = None;
10711            let mut group_end = Point::zero();
10712            let diagnostic_group = buffer
10713                .diagnostic_group::<MultiBufferPoint>(group_id)
10714                .filter_map(|entry| {
10715                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10716                        && (entry.range.start.row == entry.range.end.row
10717                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10718                    {
10719                        return None;
10720                    }
10721                    if entry.range.end > group_end {
10722                        group_end = entry.range.end;
10723                    }
10724                    if entry.diagnostic.is_primary {
10725                        primary_range = Some(entry.range.clone());
10726                        primary_message = Some(entry.diagnostic.message.clone());
10727                    }
10728                    Some(entry)
10729                })
10730                .collect::<Vec<_>>();
10731            let primary_range = primary_range?;
10732            let primary_message = primary_message?;
10733            let primary_range =
10734                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10735
10736            let blocks = display_map
10737                .insert_blocks(
10738                    diagnostic_group.iter().map(|entry| {
10739                        let diagnostic = entry.diagnostic.clone();
10740                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10741                        BlockProperties {
10742                            style: BlockStyle::Fixed,
10743                            placement: BlockPlacement::Below(
10744                                buffer.anchor_after(entry.range.start),
10745                            ),
10746                            height: message_height,
10747                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10748                            priority: 0,
10749                        }
10750                    }),
10751                    cx,
10752                )
10753                .into_iter()
10754                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10755                .collect();
10756
10757            Some(ActiveDiagnosticGroup {
10758                primary_range,
10759                primary_message,
10760                group_id,
10761                blocks,
10762                is_valid: true,
10763            })
10764        });
10765        self.active_diagnostics.is_some()
10766    }
10767
10768    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10769        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10770            self.display_map.update(cx, |display_map, cx| {
10771                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10772            });
10773            cx.notify();
10774        }
10775    }
10776
10777    pub fn set_selections_from_remote(
10778        &mut self,
10779        selections: Vec<Selection<Anchor>>,
10780        pending_selection: Option<Selection<Anchor>>,
10781        cx: &mut ViewContext<Self>,
10782    ) {
10783        let old_cursor_position = self.selections.newest_anchor().head();
10784        self.selections.change_with(cx, |s| {
10785            s.select_anchors(selections);
10786            if let Some(pending_selection) = pending_selection {
10787                s.set_pending(pending_selection, SelectMode::Character);
10788            } else {
10789                s.clear_pending();
10790            }
10791        });
10792        self.selections_did_change(false, &old_cursor_position, true, cx);
10793    }
10794
10795    fn push_to_selection_history(&mut self) {
10796        self.selection_history.push(SelectionHistoryEntry {
10797            selections: self.selections.disjoint_anchors(),
10798            select_next_state: self.select_next_state.clone(),
10799            select_prev_state: self.select_prev_state.clone(),
10800            add_selections_state: self.add_selections_state.clone(),
10801        });
10802    }
10803
10804    pub fn transact(
10805        &mut self,
10806        cx: &mut ViewContext<Self>,
10807        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10808    ) -> Option<TransactionId> {
10809        self.start_transaction_at(Instant::now(), cx);
10810        update(self, cx);
10811        self.end_transaction_at(Instant::now(), cx)
10812    }
10813
10814    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10815        self.end_selection(cx);
10816        if let Some(tx_id) = self
10817            .buffer
10818            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10819        {
10820            self.selection_history
10821                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10822            cx.emit(EditorEvent::TransactionBegun {
10823                transaction_id: tx_id,
10824            })
10825        }
10826    }
10827
10828    fn end_transaction_at(
10829        &mut self,
10830        now: Instant,
10831        cx: &mut ViewContext<Self>,
10832    ) -> Option<TransactionId> {
10833        if let Some(transaction_id) = self
10834            .buffer
10835            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10836        {
10837            if let Some((_, end_selections)) =
10838                self.selection_history.transaction_mut(transaction_id)
10839            {
10840                *end_selections = Some(self.selections.disjoint_anchors());
10841            } else {
10842                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10843            }
10844
10845            cx.emit(EditorEvent::Edited { transaction_id });
10846            Some(transaction_id)
10847        } else {
10848            None
10849        }
10850    }
10851
10852    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10853        let selection = self.selections.newest::<Point>(cx);
10854
10855        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10856        let range = if selection.is_empty() {
10857            let point = selection.head().to_display_point(&display_map);
10858            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10859            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10860                .to_point(&display_map);
10861            start..end
10862        } else {
10863            selection.range()
10864        };
10865        if display_map.folds_in_range(range).next().is_some() {
10866            self.unfold_lines(&Default::default(), cx)
10867        } else {
10868            self.fold(&Default::default(), cx)
10869        }
10870    }
10871
10872    pub fn toggle_fold_recursive(
10873        &mut self,
10874        _: &actions::ToggleFoldRecursive,
10875        cx: &mut ViewContext<Self>,
10876    ) {
10877        let selection = self.selections.newest::<Point>(cx);
10878
10879        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10880        let range = if selection.is_empty() {
10881            let point = selection.head().to_display_point(&display_map);
10882            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10883            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10884                .to_point(&display_map);
10885            start..end
10886        } else {
10887            selection.range()
10888        };
10889        if display_map.folds_in_range(range).next().is_some() {
10890            self.unfold_recursive(&Default::default(), cx)
10891        } else {
10892            self.fold_recursive(&Default::default(), cx)
10893        }
10894    }
10895
10896    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10897        let mut fold_ranges = Vec::new();
10898        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10899        let selections = self.selections.all_adjusted(cx);
10900
10901        for selection in selections {
10902            let range = selection.range().sorted();
10903            let buffer_start_row = range.start.row;
10904
10905            if range.start.row != range.end.row {
10906                let mut found = false;
10907                let mut row = range.start.row;
10908                while row <= range.end.row {
10909                    if let Some((foldable_range, fold_text)) =
10910                        { display_map.foldable_range(MultiBufferRow(row)) }
10911                    {
10912                        found = true;
10913                        row = foldable_range.end.row + 1;
10914                        fold_ranges.push((foldable_range, fold_text));
10915                    } else {
10916                        row += 1
10917                    }
10918                }
10919                if found {
10920                    continue;
10921                }
10922            }
10923
10924            for row in (0..=range.start.row).rev() {
10925                if let Some((foldable_range, fold_text)) =
10926                    display_map.foldable_range(MultiBufferRow(row))
10927                {
10928                    if foldable_range.end.row >= buffer_start_row {
10929                        fold_ranges.push((foldable_range, fold_text));
10930                        if row <= range.start.row {
10931                            break;
10932                        }
10933                    }
10934                }
10935            }
10936        }
10937
10938        self.fold_ranges(fold_ranges, true, cx);
10939    }
10940
10941    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10942        let fold_at_level = fold_at.level;
10943        let snapshot = self.buffer.read(cx).snapshot(cx);
10944        let mut fold_ranges = Vec::new();
10945        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10946
10947        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10948            while start_row < end_row {
10949                match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10950                    Some(foldable_range) => {
10951                        let nested_start_row = foldable_range.0.start.row + 1;
10952                        let nested_end_row = foldable_range.0.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                            fold_ranges.push(foldable_range);
10958                        }
10959
10960                        start_row = nested_end_row + 1;
10961                    }
10962                    None => start_row += 1,
10963                }
10964            }
10965        }
10966
10967        self.fold_ranges(fold_ranges, 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) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10976                fold_ranges.push(foldable_range);
10977            }
10978        }
10979
10980        self.fold_ranges(fold_ranges, true, cx);
10981    }
10982
10983    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10984        let mut fold_ranges = Vec::new();
10985        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10986        let selections = self.selections.all_adjusted(cx);
10987
10988        for selection in selections {
10989            let range = selection.range().sorted();
10990            let buffer_start_row = range.start.row;
10991
10992            if range.start.row != range.end.row {
10993                let mut found = false;
10994                for row in range.start.row..=range.end.row {
10995                    if let Some((foldable_range, fold_text)) =
10996                        { display_map.foldable_range(MultiBufferRow(row)) }
10997                    {
10998                        found = true;
10999                        fold_ranges.push((foldable_range, fold_text));
11000                    }
11001                }
11002                if found {
11003                    continue;
11004                }
11005            }
11006
11007            for row in (0..=range.start.row).rev() {
11008                if let Some((foldable_range, fold_text)) =
11009                    display_map.foldable_range(MultiBufferRow(row))
11010                {
11011                    if foldable_range.end.row >= buffer_start_row {
11012                        fold_ranges.push((foldable_range, fold_text));
11013                    } else {
11014                        break;
11015                    }
11016                }
11017            }
11018        }
11019
11020        self.fold_ranges(fold_ranges, true, cx);
11021    }
11022
11023    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11024        let buffer_row = fold_at.buffer_row;
11025        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11026
11027        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
11028            let autoscroll = self
11029                .selections
11030                .all::<Point>(cx)
11031                .iter()
11032                .any(|selection| fold_range.overlaps(&selection.range()));
11033
11034            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
11035        }
11036    }
11037
11038    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11039        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11040        let buffer = &display_map.buffer_snapshot;
11041        let selections = self.selections.all::<Point>(cx);
11042        let ranges = selections
11043            .iter()
11044            .map(|s| {
11045                let range = s.display_range(&display_map).sorted();
11046                let mut start = range.start.to_point(&display_map);
11047                let mut end = range.end.to_point(&display_map);
11048                start.column = 0;
11049                end.column = buffer.line_len(MultiBufferRow(end.row));
11050                start..end
11051            })
11052            .collect::<Vec<_>>();
11053
11054        self.unfold_ranges(&ranges, true, true, cx);
11055    }
11056
11057    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11058        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11059        let selections = self.selections.all::<Point>(cx);
11060        let ranges = selections
11061            .iter()
11062            .map(|s| {
11063                let mut range = s.display_range(&display_map).sorted();
11064                *range.start.column_mut() = 0;
11065                *range.end.column_mut() = display_map.line_len(range.end.row());
11066                let start = range.start.to_point(&display_map);
11067                let end = range.end.to_point(&display_map);
11068                start..end
11069            })
11070            .collect::<Vec<_>>();
11071
11072        self.unfold_ranges(&ranges, true, true, cx);
11073    }
11074
11075    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11076        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11077
11078        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11079            ..Point::new(
11080                unfold_at.buffer_row.0,
11081                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11082            );
11083
11084        let autoscroll = self
11085            .selections
11086            .all::<Point>(cx)
11087            .iter()
11088            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11089
11090        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11091    }
11092
11093    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11094        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11095        self.unfold_ranges(
11096            &[Point::zero()..display_map.max_point().to_point(&display_map)],
11097            true,
11098            true,
11099            cx,
11100        );
11101    }
11102
11103    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11104        let selections = self.selections.all::<Point>(cx);
11105        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11106        let line_mode = self.selections.line_mode;
11107        let ranges = selections.into_iter().map(|s| {
11108            if line_mode {
11109                let start = Point::new(s.start.row, 0);
11110                let end = Point::new(
11111                    s.end.row,
11112                    display_map
11113                        .buffer_snapshot
11114                        .line_len(MultiBufferRow(s.end.row)),
11115                );
11116                (start..end, display_map.fold_placeholder.clone())
11117            } else {
11118                (s.start..s.end, display_map.fold_placeholder.clone())
11119            }
11120        });
11121        self.fold_ranges(ranges, true, cx);
11122    }
11123
11124    pub fn fold_ranges<T: ToOffset + Clone>(
11125        &mut self,
11126        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11127        auto_scroll: bool,
11128        cx: &mut ViewContext<Self>,
11129    ) {
11130        let mut fold_ranges = Vec::new();
11131        let mut buffers_affected = HashMap::default();
11132        let multi_buffer = self.buffer().read(cx);
11133        for (fold_range, fold_text) in ranges {
11134            if let Some((_, buffer, _)) =
11135                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11136            {
11137                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11138            };
11139            fold_ranges.push((fold_range, fold_text));
11140        }
11141
11142        let mut ranges = fold_ranges.into_iter().peekable();
11143        if ranges.peek().is_some() {
11144            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11145
11146            if auto_scroll {
11147                self.request_autoscroll(Autoscroll::fit(), cx);
11148            }
11149
11150            for buffer in buffers_affected.into_values() {
11151                self.sync_expanded_diff_hunks(buffer, cx);
11152            }
11153
11154            cx.notify();
11155
11156            if let Some(active_diagnostics) = self.active_diagnostics.take() {
11157                // Clear diagnostics block when folding a range that contains it.
11158                let snapshot = self.snapshot(cx);
11159                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11160                    drop(snapshot);
11161                    self.active_diagnostics = Some(active_diagnostics);
11162                    self.dismiss_diagnostics(cx);
11163                } else {
11164                    self.active_diagnostics = Some(active_diagnostics);
11165                }
11166            }
11167
11168            self.scrollbar_marker_state.dirty = true;
11169        }
11170    }
11171
11172    /// Removes any folds whose ranges intersect any of the given ranges.
11173    pub fn unfold_ranges<T: ToOffset + Clone>(
11174        &mut self,
11175        ranges: &[Range<T>],
11176        inclusive: bool,
11177        auto_scroll: bool,
11178        cx: &mut ViewContext<Self>,
11179    ) {
11180        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11181            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11182        });
11183    }
11184
11185    /// Removes any folds with the given ranges.
11186    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11187        &mut self,
11188        ranges: &[Range<T>],
11189        type_id: TypeId,
11190        auto_scroll: bool,
11191        cx: &mut ViewContext<Self>,
11192    ) {
11193        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11194            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11195        });
11196    }
11197
11198    fn remove_folds_with<T: ToOffset + Clone>(
11199        &mut self,
11200        ranges: &[Range<T>],
11201        auto_scroll: bool,
11202        cx: &mut ViewContext<Self>,
11203        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11204    ) {
11205        if ranges.is_empty() {
11206            return;
11207        }
11208
11209        let mut buffers_affected = HashMap::default();
11210        let multi_buffer = self.buffer().read(cx);
11211        for range in ranges {
11212            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11213                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11214            };
11215        }
11216
11217        self.display_map.update(cx, update);
11218        if auto_scroll {
11219            self.request_autoscroll(Autoscroll::fit(), cx);
11220        }
11221
11222        for buffer in buffers_affected.into_values() {
11223            self.sync_expanded_diff_hunks(buffer, cx);
11224        }
11225
11226        cx.notify();
11227        self.scrollbar_marker_state.dirty = true;
11228        self.active_indent_guides_state.dirty = true;
11229    }
11230
11231    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11232        self.display_map.read(cx).fold_placeholder.clone()
11233    }
11234
11235    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11236        if hovered != self.gutter_hovered {
11237            self.gutter_hovered = hovered;
11238            cx.notify();
11239        }
11240    }
11241
11242    pub fn insert_blocks(
11243        &mut self,
11244        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11245        autoscroll: Option<Autoscroll>,
11246        cx: &mut ViewContext<Self>,
11247    ) -> Vec<CustomBlockId> {
11248        let blocks = self
11249            .display_map
11250            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11251        if let Some(autoscroll) = autoscroll {
11252            self.request_autoscroll(autoscroll, cx);
11253        }
11254        cx.notify();
11255        blocks
11256    }
11257
11258    pub fn resize_blocks(
11259        &mut self,
11260        heights: HashMap<CustomBlockId, u32>,
11261        autoscroll: Option<Autoscroll>,
11262        cx: &mut ViewContext<Self>,
11263    ) {
11264        self.display_map
11265            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11266        if let Some(autoscroll) = autoscroll {
11267            self.request_autoscroll(autoscroll, cx);
11268        }
11269        cx.notify();
11270    }
11271
11272    pub fn replace_blocks(
11273        &mut self,
11274        renderers: HashMap<CustomBlockId, RenderBlock>,
11275        autoscroll: Option<Autoscroll>,
11276        cx: &mut ViewContext<Self>,
11277    ) {
11278        self.display_map
11279            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11280        if let Some(autoscroll) = autoscroll {
11281            self.request_autoscroll(autoscroll, cx);
11282        }
11283        cx.notify();
11284    }
11285
11286    pub fn remove_blocks(
11287        &mut self,
11288        block_ids: HashSet<CustomBlockId>,
11289        autoscroll: Option<Autoscroll>,
11290        cx: &mut ViewContext<Self>,
11291    ) {
11292        self.display_map.update(cx, |display_map, cx| {
11293            display_map.remove_blocks(block_ids, cx)
11294        });
11295        if let Some(autoscroll) = autoscroll {
11296            self.request_autoscroll(autoscroll, cx);
11297        }
11298        cx.notify();
11299    }
11300
11301    pub fn row_for_block(
11302        &self,
11303        block_id: CustomBlockId,
11304        cx: &mut ViewContext<Self>,
11305    ) -> Option<DisplayRow> {
11306        self.display_map
11307            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11308    }
11309
11310    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11311        self.focused_block = Some(focused_block);
11312    }
11313
11314    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11315        self.focused_block.take()
11316    }
11317
11318    pub fn insert_creases(
11319        &mut self,
11320        creases: impl IntoIterator<Item = Crease>,
11321        cx: &mut ViewContext<Self>,
11322    ) -> Vec<CreaseId> {
11323        self.display_map
11324            .update(cx, |map, cx| map.insert_creases(creases, cx))
11325    }
11326
11327    pub fn remove_creases(
11328        &mut self,
11329        ids: impl IntoIterator<Item = CreaseId>,
11330        cx: &mut ViewContext<Self>,
11331    ) {
11332        self.display_map
11333            .update(cx, |map, cx| map.remove_creases(ids, cx));
11334    }
11335
11336    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11337        self.display_map
11338            .update(cx, |map, cx| map.snapshot(cx))
11339            .longest_row()
11340    }
11341
11342    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11343        self.display_map
11344            .update(cx, |map, cx| map.snapshot(cx))
11345            .max_point()
11346    }
11347
11348    pub fn text(&self, cx: &AppContext) -> String {
11349        self.buffer.read(cx).read(cx).text()
11350    }
11351
11352    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11353        let text = self.text(cx);
11354        let text = text.trim();
11355
11356        if text.is_empty() {
11357            return None;
11358        }
11359
11360        Some(text.to_string())
11361    }
11362
11363    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11364        self.transact(cx, |this, cx| {
11365            this.buffer
11366                .read(cx)
11367                .as_singleton()
11368                .expect("you can only call set_text on editors for singleton buffers")
11369                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11370        });
11371    }
11372
11373    pub fn display_text(&self, cx: &mut AppContext) -> String {
11374        self.display_map
11375            .update(cx, |map, cx| map.snapshot(cx))
11376            .text()
11377    }
11378
11379    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11380        let mut wrap_guides = smallvec::smallvec![];
11381
11382        if self.show_wrap_guides == Some(false) {
11383            return wrap_guides;
11384        }
11385
11386        let settings = self.buffer.read(cx).settings_at(0, cx);
11387        if settings.show_wrap_guides {
11388            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11389                wrap_guides.push((soft_wrap as usize, true));
11390            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11391                wrap_guides.push((soft_wrap as usize, true));
11392            }
11393            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11394        }
11395
11396        wrap_guides
11397    }
11398
11399    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11400        let settings = self.buffer.read(cx).settings_at(0, cx);
11401        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11402        match mode {
11403            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11404                SoftWrap::None
11405            }
11406            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11407            language_settings::SoftWrap::PreferredLineLength => {
11408                SoftWrap::Column(settings.preferred_line_length)
11409            }
11410            language_settings::SoftWrap::Bounded => {
11411                SoftWrap::Bounded(settings.preferred_line_length)
11412            }
11413        }
11414    }
11415
11416    pub fn set_soft_wrap_mode(
11417        &mut self,
11418        mode: language_settings::SoftWrap,
11419        cx: &mut ViewContext<Self>,
11420    ) {
11421        self.soft_wrap_mode_override = Some(mode);
11422        cx.notify();
11423    }
11424
11425    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11426        self.text_style_refinement = Some(style);
11427    }
11428
11429    /// called by the Element so we know what style we were most recently rendered with.
11430    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11431        let rem_size = cx.rem_size();
11432        self.display_map.update(cx, |map, cx| {
11433            map.set_font(
11434                style.text.font(),
11435                style.text.font_size.to_pixels(rem_size),
11436                cx,
11437            )
11438        });
11439        self.style = Some(style);
11440    }
11441
11442    pub fn style(&self) -> Option<&EditorStyle> {
11443        self.style.as_ref()
11444    }
11445
11446    // Called by the element. This method is not designed to be called outside of the editor
11447    // element's layout code because it does not notify when rewrapping is computed synchronously.
11448    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11449        self.display_map
11450            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11451    }
11452
11453    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11454        if self.soft_wrap_mode_override.is_some() {
11455            self.soft_wrap_mode_override.take();
11456        } else {
11457            let soft_wrap = match self.soft_wrap_mode(cx) {
11458                SoftWrap::GitDiff => return,
11459                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11460                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11461                    language_settings::SoftWrap::None
11462                }
11463            };
11464            self.soft_wrap_mode_override = Some(soft_wrap);
11465        }
11466        cx.notify();
11467    }
11468
11469    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11470        let Some(workspace) = self.workspace() else {
11471            return;
11472        };
11473        let fs = workspace.read(cx).app_state().fs.clone();
11474        let current_show = TabBarSettings::get_global(cx).show;
11475        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11476            setting.show = Some(!current_show);
11477        });
11478    }
11479
11480    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11481        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11482            self.buffer
11483                .read(cx)
11484                .settings_at(0, cx)
11485                .indent_guides
11486                .enabled
11487        });
11488        self.show_indent_guides = Some(!currently_enabled);
11489        cx.notify();
11490    }
11491
11492    fn should_show_indent_guides(&self) -> Option<bool> {
11493        self.show_indent_guides
11494    }
11495
11496    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11497        let mut editor_settings = EditorSettings::get_global(cx).clone();
11498        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11499        EditorSettings::override_global(editor_settings, cx);
11500    }
11501
11502    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11503        self.use_relative_line_numbers
11504            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11505    }
11506
11507    pub fn toggle_relative_line_numbers(
11508        &mut self,
11509        _: &ToggleRelativeLineNumbers,
11510        cx: &mut ViewContext<Self>,
11511    ) {
11512        let is_relative = self.should_use_relative_line_numbers(cx);
11513        self.set_relative_line_number(Some(!is_relative), cx)
11514    }
11515
11516    pub fn set_relative_line_number(
11517        &mut self,
11518        is_relative: Option<bool>,
11519        cx: &mut ViewContext<Self>,
11520    ) {
11521        self.use_relative_line_numbers = is_relative;
11522        cx.notify();
11523    }
11524
11525    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11526        self.show_gutter = show_gutter;
11527        cx.notify();
11528    }
11529
11530    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11531        self.show_line_numbers = Some(show_line_numbers);
11532        cx.notify();
11533    }
11534
11535    pub fn set_show_git_diff_gutter(
11536        &mut self,
11537        show_git_diff_gutter: bool,
11538        cx: &mut ViewContext<Self>,
11539    ) {
11540        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11541        cx.notify();
11542    }
11543
11544    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11545        self.show_code_actions = Some(show_code_actions);
11546        cx.notify();
11547    }
11548
11549    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11550        self.show_runnables = Some(show_runnables);
11551        cx.notify();
11552    }
11553
11554    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11555        if self.display_map.read(cx).masked != masked {
11556            self.display_map.update(cx, |map, _| map.masked = masked);
11557        }
11558        cx.notify()
11559    }
11560
11561    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11562        self.show_wrap_guides = Some(show_wrap_guides);
11563        cx.notify();
11564    }
11565
11566    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11567        self.show_indent_guides = Some(show_indent_guides);
11568        cx.notify();
11569    }
11570
11571    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11572        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11573            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11574                if let Some(dir) = file.abs_path(cx).parent() {
11575                    return Some(dir.to_owned());
11576                }
11577            }
11578
11579            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11580                return Some(project_path.path.to_path_buf());
11581            }
11582        }
11583
11584        None
11585    }
11586
11587    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11588        self.active_excerpt(cx)?
11589            .1
11590            .read(cx)
11591            .file()
11592            .and_then(|f| f.as_local())
11593    }
11594
11595    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11596        if let Some(target) = self.target_file(cx) {
11597            cx.reveal_path(&target.abs_path(cx));
11598        }
11599    }
11600
11601    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11602        if let Some(file) = self.target_file(cx) {
11603            if let Some(path) = file.abs_path(cx).to_str() {
11604                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11605            }
11606        }
11607    }
11608
11609    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11610        if let Some(file) = self.target_file(cx) {
11611            if let Some(path) = file.path().to_str() {
11612                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11613            }
11614        }
11615    }
11616
11617    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11618        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11619
11620        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11621            self.start_git_blame(true, cx);
11622        }
11623
11624        cx.notify();
11625    }
11626
11627    pub fn toggle_git_blame_inline(
11628        &mut self,
11629        _: &ToggleGitBlameInline,
11630        cx: &mut ViewContext<Self>,
11631    ) {
11632        self.toggle_git_blame_inline_internal(true, cx);
11633        cx.notify();
11634    }
11635
11636    pub fn git_blame_inline_enabled(&self) -> bool {
11637        self.git_blame_inline_enabled
11638    }
11639
11640    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11641        self.show_selection_menu = self
11642            .show_selection_menu
11643            .map(|show_selections_menu| !show_selections_menu)
11644            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11645
11646        cx.notify();
11647    }
11648
11649    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11650        self.show_selection_menu
11651            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11652    }
11653
11654    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11655        if let Some(project) = self.project.as_ref() {
11656            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11657                return;
11658            };
11659
11660            if buffer.read(cx).file().is_none() {
11661                return;
11662            }
11663
11664            let focused = self.focus_handle(cx).contains_focused(cx);
11665
11666            let project = project.clone();
11667            let blame =
11668                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11669            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11670            self.blame = Some(blame);
11671        }
11672    }
11673
11674    fn toggle_git_blame_inline_internal(
11675        &mut self,
11676        user_triggered: bool,
11677        cx: &mut ViewContext<Self>,
11678    ) {
11679        if self.git_blame_inline_enabled {
11680            self.git_blame_inline_enabled = false;
11681            self.show_git_blame_inline = false;
11682            self.show_git_blame_inline_delay_task.take();
11683        } else {
11684            self.git_blame_inline_enabled = true;
11685            self.start_git_blame_inline(user_triggered, cx);
11686        }
11687
11688        cx.notify();
11689    }
11690
11691    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11692        self.start_git_blame(user_triggered, cx);
11693
11694        if ProjectSettings::get_global(cx)
11695            .git
11696            .inline_blame_delay()
11697            .is_some()
11698        {
11699            self.start_inline_blame_timer(cx);
11700        } else {
11701            self.show_git_blame_inline = true
11702        }
11703    }
11704
11705    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11706        self.blame.as_ref()
11707    }
11708
11709    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11710        self.show_git_blame_gutter && self.has_blame_entries(cx)
11711    }
11712
11713    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11714        self.show_git_blame_inline
11715            && self.focus_handle.is_focused(cx)
11716            && !self.newest_selection_head_on_empty_line(cx)
11717            && self.has_blame_entries(cx)
11718    }
11719
11720    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11721        self.blame()
11722            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11723    }
11724
11725    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11726        let cursor_anchor = self.selections.newest_anchor().head();
11727
11728        let snapshot = self.buffer.read(cx).snapshot(cx);
11729        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11730
11731        snapshot.line_len(buffer_row) == 0
11732    }
11733
11734    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11735        let buffer_and_selection = maybe!({
11736            let selection = self.selections.newest::<Point>(cx);
11737            let selection_range = selection.range();
11738
11739            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11740                (buffer, selection_range.start.row..selection_range.end.row)
11741            } else {
11742                let buffer_ranges = self
11743                    .buffer()
11744                    .read(cx)
11745                    .range_to_buffer_ranges(selection_range, cx);
11746
11747                let (buffer, range, _) = if selection.reversed {
11748                    buffer_ranges.first()
11749                } else {
11750                    buffer_ranges.last()
11751                }?;
11752
11753                let snapshot = buffer.read(cx).snapshot();
11754                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11755                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11756                (buffer.clone(), selection)
11757            };
11758
11759            Some((buffer, selection))
11760        });
11761
11762        let Some((buffer, selection)) = buffer_and_selection else {
11763            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11764        };
11765
11766        let Some(project) = self.project.as_ref() else {
11767            return Task::ready(Err(anyhow!("editor does not have project")));
11768        };
11769
11770        project.update(cx, |project, cx| {
11771            project.get_permalink_to_line(&buffer, selection, cx)
11772        })
11773    }
11774
11775    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11776        let permalink_task = self.get_permalink_to_line(cx);
11777        let workspace = self.workspace();
11778
11779        cx.spawn(|_, mut cx| async move {
11780            match permalink_task.await {
11781                Ok(permalink) => {
11782                    cx.update(|cx| {
11783                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11784                    })
11785                    .ok();
11786                }
11787                Err(err) => {
11788                    let message = format!("Failed to copy permalink: {err}");
11789
11790                    Err::<(), anyhow::Error>(err).log_err();
11791
11792                    if let Some(workspace) = workspace {
11793                        workspace
11794                            .update(&mut cx, |workspace, cx| {
11795                                struct CopyPermalinkToLine;
11796
11797                                workspace.show_toast(
11798                                    Toast::new(
11799                                        NotificationId::unique::<CopyPermalinkToLine>(),
11800                                        message,
11801                                    ),
11802                                    cx,
11803                                )
11804                            })
11805                            .ok();
11806                    }
11807                }
11808            }
11809        })
11810        .detach();
11811    }
11812
11813    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11814        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11815        if let Some(file) = self.target_file(cx) {
11816            if let Some(path) = file.path().to_str() {
11817                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11818            }
11819        }
11820    }
11821
11822    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11823        let permalink_task = self.get_permalink_to_line(cx);
11824        let workspace = self.workspace();
11825
11826        cx.spawn(|_, mut cx| async move {
11827            match permalink_task.await {
11828                Ok(permalink) => {
11829                    cx.update(|cx| {
11830                        cx.open_url(permalink.as_ref());
11831                    })
11832                    .ok();
11833                }
11834                Err(err) => {
11835                    let message = format!("Failed to open permalink: {err}");
11836
11837                    Err::<(), anyhow::Error>(err).log_err();
11838
11839                    if let Some(workspace) = workspace {
11840                        workspace
11841                            .update(&mut cx, |workspace, cx| {
11842                                struct OpenPermalinkToLine;
11843
11844                                workspace.show_toast(
11845                                    Toast::new(
11846                                        NotificationId::unique::<OpenPermalinkToLine>(),
11847                                        message,
11848                                    ),
11849                                    cx,
11850                                )
11851                            })
11852                            .ok();
11853                    }
11854                }
11855            }
11856        })
11857        .detach();
11858    }
11859
11860    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11861    /// last highlight added will be used.
11862    ///
11863    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11864    pub fn highlight_rows<T: 'static>(
11865        &mut self,
11866        range: Range<Anchor>,
11867        color: Hsla,
11868        should_autoscroll: bool,
11869        cx: &mut ViewContext<Self>,
11870    ) {
11871        let snapshot = self.buffer().read(cx).snapshot(cx);
11872        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11873        let ix = row_highlights.binary_search_by(|highlight| {
11874            Ordering::Equal
11875                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11876                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11877        });
11878
11879        if let Err(mut ix) = ix {
11880            let index = post_inc(&mut self.highlight_order);
11881
11882            // If this range intersects with the preceding highlight, then merge it with
11883            // the preceding highlight. Otherwise insert a new highlight.
11884            let mut merged = false;
11885            if ix > 0 {
11886                let prev_highlight = &mut row_highlights[ix - 1];
11887                if prev_highlight
11888                    .range
11889                    .end
11890                    .cmp(&range.start, &snapshot)
11891                    .is_ge()
11892                {
11893                    ix -= 1;
11894                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11895                        prev_highlight.range.end = range.end;
11896                    }
11897                    merged = true;
11898                    prev_highlight.index = index;
11899                    prev_highlight.color = color;
11900                    prev_highlight.should_autoscroll = should_autoscroll;
11901                }
11902            }
11903
11904            if !merged {
11905                row_highlights.insert(
11906                    ix,
11907                    RowHighlight {
11908                        range: range.clone(),
11909                        index,
11910                        color,
11911                        should_autoscroll,
11912                    },
11913                );
11914            }
11915
11916            // If any of the following highlights intersect with this one, merge them.
11917            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11918                let highlight = &row_highlights[ix];
11919                if next_highlight
11920                    .range
11921                    .start
11922                    .cmp(&highlight.range.end, &snapshot)
11923                    .is_le()
11924                {
11925                    if next_highlight
11926                        .range
11927                        .end
11928                        .cmp(&highlight.range.end, &snapshot)
11929                        .is_gt()
11930                    {
11931                        row_highlights[ix].range.end = next_highlight.range.end;
11932                    }
11933                    row_highlights.remove(ix + 1);
11934                } else {
11935                    break;
11936                }
11937            }
11938        }
11939    }
11940
11941    /// Remove any highlighted row ranges of the given type that intersect the
11942    /// given ranges.
11943    pub fn remove_highlighted_rows<T: 'static>(
11944        &mut self,
11945        ranges_to_remove: Vec<Range<Anchor>>,
11946        cx: &mut ViewContext<Self>,
11947    ) {
11948        let snapshot = self.buffer().read(cx).snapshot(cx);
11949        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11950        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11951        row_highlights.retain(|highlight| {
11952            while let Some(range_to_remove) = ranges_to_remove.peek() {
11953                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11954                    Ordering::Less | Ordering::Equal => {
11955                        ranges_to_remove.next();
11956                    }
11957                    Ordering::Greater => {
11958                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11959                            Ordering::Less | Ordering::Equal => {
11960                                return false;
11961                            }
11962                            Ordering::Greater => break,
11963                        }
11964                    }
11965                }
11966            }
11967
11968            true
11969        })
11970    }
11971
11972    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11973    pub fn clear_row_highlights<T: 'static>(&mut self) {
11974        self.highlighted_rows.remove(&TypeId::of::<T>());
11975    }
11976
11977    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11978    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11979        self.highlighted_rows
11980            .get(&TypeId::of::<T>())
11981            .map_or(&[] as &[_], |vec| vec.as_slice())
11982            .iter()
11983            .map(|highlight| (highlight.range.clone(), highlight.color))
11984    }
11985
11986    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11987    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11988    /// Allows to ignore certain kinds of highlights.
11989    pub fn highlighted_display_rows(
11990        &mut self,
11991        cx: &mut WindowContext,
11992    ) -> BTreeMap<DisplayRow, Hsla> {
11993        let snapshot = self.snapshot(cx);
11994        let mut used_highlight_orders = HashMap::default();
11995        self.highlighted_rows
11996            .iter()
11997            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11998            .fold(
11999                BTreeMap::<DisplayRow, Hsla>::new(),
12000                |mut unique_rows, highlight| {
12001                    let start = highlight.range.start.to_display_point(&snapshot);
12002                    let end = highlight.range.end.to_display_point(&snapshot);
12003                    let start_row = start.row().0;
12004                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12005                        && end.column() == 0
12006                    {
12007                        end.row().0.saturating_sub(1)
12008                    } else {
12009                        end.row().0
12010                    };
12011                    for row in start_row..=end_row {
12012                        let used_index =
12013                            used_highlight_orders.entry(row).or_insert(highlight.index);
12014                        if highlight.index >= *used_index {
12015                            *used_index = highlight.index;
12016                            unique_rows.insert(DisplayRow(row), highlight.color);
12017                        }
12018                    }
12019                    unique_rows
12020                },
12021            )
12022    }
12023
12024    pub fn highlighted_display_row_for_autoscroll(
12025        &self,
12026        snapshot: &DisplaySnapshot,
12027    ) -> Option<DisplayRow> {
12028        self.highlighted_rows
12029            .values()
12030            .flat_map(|highlighted_rows| highlighted_rows.iter())
12031            .filter_map(|highlight| {
12032                if highlight.should_autoscroll {
12033                    Some(highlight.range.start.to_display_point(snapshot).row())
12034                } else {
12035                    None
12036                }
12037            })
12038            .min()
12039    }
12040
12041    pub fn set_search_within_ranges(
12042        &mut self,
12043        ranges: &[Range<Anchor>],
12044        cx: &mut ViewContext<Self>,
12045    ) {
12046        self.highlight_background::<SearchWithinRange>(
12047            ranges,
12048            |colors| colors.editor_document_highlight_read_background,
12049            cx,
12050        )
12051    }
12052
12053    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12054        self.breadcrumb_header = Some(new_header);
12055    }
12056
12057    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12058        self.clear_background_highlights::<SearchWithinRange>(cx);
12059    }
12060
12061    pub fn highlight_background<T: 'static>(
12062        &mut self,
12063        ranges: &[Range<Anchor>],
12064        color_fetcher: fn(&ThemeColors) -> Hsla,
12065        cx: &mut ViewContext<Self>,
12066    ) {
12067        self.background_highlights
12068            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12069        self.scrollbar_marker_state.dirty = true;
12070        cx.notify();
12071    }
12072
12073    pub fn clear_background_highlights<T: 'static>(
12074        &mut self,
12075        cx: &mut ViewContext<Self>,
12076    ) -> Option<BackgroundHighlight> {
12077        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12078        if !text_highlights.1.is_empty() {
12079            self.scrollbar_marker_state.dirty = true;
12080            cx.notify();
12081        }
12082        Some(text_highlights)
12083    }
12084
12085    pub fn highlight_gutter<T: 'static>(
12086        &mut self,
12087        ranges: &[Range<Anchor>],
12088        color_fetcher: fn(&AppContext) -> Hsla,
12089        cx: &mut ViewContext<Self>,
12090    ) {
12091        self.gutter_highlights
12092            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12093        cx.notify();
12094    }
12095
12096    pub fn clear_gutter_highlights<T: 'static>(
12097        &mut self,
12098        cx: &mut ViewContext<Self>,
12099    ) -> Option<GutterHighlight> {
12100        cx.notify();
12101        self.gutter_highlights.remove(&TypeId::of::<T>())
12102    }
12103
12104    #[cfg(feature = "test-support")]
12105    pub fn all_text_background_highlights(
12106        &mut self,
12107        cx: &mut ViewContext<Self>,
12108    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12109        let snapshot = self.snapshot(cx);
12110        let buffer = &snapshot.buffer_snapshot;
12111        let start = buffer.anchor_before(0);
12112        let end = buffer.anchor_after(buffer.len());
12113        let theme = cx.theme().colors();
12114        self.background_highlights_in_range(start..end, &snapshot, theme)
12115    }
12116
12117    #[cfg(feature = "test-support")]
12118    pub fn search_background_highlights(
12119        &mut self,
12120        cx: &mut ViewContext<Self>,
12121    ) -> Vec<Range<Point>> {
12122        let snapshot = self.buffer().read(cx).snapshot(cx);
12123
12124        let highlights = self
12125            .background_highlights
12126            .get(&TypeId::of::<items::BufferSearchHighlights>());
12127
12128        if let Some((_color, ranges)) = highlights {
12129            ranges
12130                .iter()
12131                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12132                .collect_vec()
12133        } else {
12134            vec![]
12135        }
12136    }
12137
12138    fn document_highlights_for_position<'a>(
12139        &'a self,
12140        position: Anchor,
12141        buffer: &'a MultiBufferSnapshot,
12142    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12143        let read_highlights = self
12144            .background_highlights
12145            .get(&TypeId::of::<DocumentHighlightRead>())
12146            .map(|h| &h.1);
12147        let write_highlights = self
12148            .background_highlights
12149            .get(&TypeId::of::<DocumentHighlightWrite>())
12150            .map(|h| &h.1);
12151        let left_position = position.bias_left(buffer);
12152        let right_position = position.bias_right(buffer);
12153        read_highlights
12154            .into_iter()
12155            .chain(write_highlights)
12156            .flat_map(move |ranges| {
12157                let start_ix = match ranges.binary_search_by(|probe| {
12158                    let cmp = probe.end.cmp(&left_position, buffer);
12159                    if cmp.is_ge() {
12160                        Ordering::Greater
12161                    } else {
12162                        Ordering::Less
12163                    }
12164                }) {
12165                    Ok(i) | Err(i) => i,
12166                };
12167
12168                ranges[start_ix..]
12169                    .iter()
12170                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12171            })
12172    }
12173
12174    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12175        self.background_highlights
12176            .get(&TypeId::of::<T>())
12177            .map_or(false, |(_, highlights)| !highlights.is_empty())
12178    }
12179
12180    pub fn background_highlights_in_range(
12181        &self,
12182        search_range: Range<Anchor>,
12183        display_snapshot: &DisplaySnapshot,
12184        theme: &ThemeColors,
12185    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12186        let mut results = Vec::new();
12187        for (color_fetcher, ranges) in self.background_highlights.values() {
12188            let color = color_fetcher(theme);
12189            let start_ix = match ranges.binary_search_by(|probe| {
12190                let cmp = probe
12191                    .end
12192                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12193                if cmp.is_gt() {
12194                    Ordering::Greater
12195                } else {
12196                    Ordering::Less
12197                }
12198            }) {
12199                Ok(i) | Err(i) => i,
12200            };
12201            for range in &ranges[start_ix..] {
12202                if range
12203                    .start
12204                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12205                    .is_ge()
12206                {
12207                    break;
12208                }
12209
12210                let start = range.start.to_display_point(display_snapshot);
12211                let end = range.end.to_display_point(display_snapshot);
12212                results.push((start..end, color))
12213            }
12214        }
12215        results
12216    }
12217
12218    pub fn background_highlight_row_ranges<T: 'static>(
12219        &self,
12220        search_range: Range<Anchor>,
12221        display_snapshot: &DisplaySnapshot,
12222        count: usize,
12223    ) -> Vec<RangeInclusive<DisplayPoint>> {
12224        let mut results = Vec::new();
12225        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12226            return vec![];
12227        };
12228
12229        let start_ix = match ranges.binary_search_by(|probe| {
12230            let cmp = probe
12231                .end
12232                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12233            if cmp.is_gt() {
12234                Ordering::Greater
12235            } else {
12236                Ordering::Less
12237            }
12238        }) {
12239            Ok(i) | Err(i) => i,
12240        };
12241        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12242            if let (Some(start_display), Some(end_display)) = (start, end) {
12243                results.push(
12244                    start_display.to_display_point(display_snapshot)
12245                        ..=end_display.to_display_point(display_snapshot),
12246                );
12247            }
12248        };
12249        let mut start_row: Option<Point> = None;
12250        let mut end_row: Option<Point> = None;
12251        if ranges.len() > count {
12252            return Vec::new();
12253        }
12254        for range in &ranges[start_ix..] {
12255            if range
12256                .start
12257                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12258                .is_ge()
12259            {
12260                break;
12261            }
12262            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12263            if let Some(current_row) = &end_row {
12264                if end.row == current_row.row {
12265                    continue;
12266                }
12267            }
12268            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12269            if start_row.is_none() {
12270                assert_eq!(end_row, None);
12271                start_row = Some(start);
12272                end_row = Some(end);
12273                continue;
12274            }
12275            if let Some(current_end) = end_row.as_mut() {
12276                if start.row > current_end.row + 1 {
12277                    push_region(start_row, end_row);
12278                    start_row = Some(start);
12279                    end_row = Some(end);
12280                } else {
12281                    // Merge two hunks.
12282                    *current_end = end;
12283                }
12284            } else {
12285                unreachable!();
12286            }
12287        }
12288        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12289        push_region(start_row, end_row);
12290        results
12291    }
12292
12293    pub fn gutter_highlights_in_range(
12294        &self,
12295        search_range: Range<Anchor>,
12296        display_snapshot: &DisplaySnapshot,
12297        cx: &AppContext,
12298    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12299        let mut results = Vec::new();
12300        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12301            let color = color_fetcher(cx);
12302            let start_ix = match ranges.binary_search_by(|probe| {
12303                let cmp = probe
12304                    .end
12305                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12306                if cmp.is_gt() {
12307                    Ordering::Greater
12308                } else {
12309                    Ordering::Less
12310                }
12311            }) {
12312                Ok(i) | Err(i) => i,
12313            };
12314            for range in &ranges[start_ix..] {
12315                if range
12316                    .start
12317                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12318                    .is_ge()
12319                {
12320                    break;
12321                }
12322
12323                let start = range.start.to_display_point(display_snapshot);
12324                let end = range.end.to_display_point(display_snapshot);
12325                results.push((start..end, color))
12326            }
12327        }
12328        results
12329    }
12330
12331    /// Get the text ranges corresponding to the redaction query
12332    pub fn redacted_ranges(
12333        &self,
12334        search_range: Range<Anchor>,
12335        display_snapshot: &DisplaySnapshot,
12336        cx: &WindowContext,
12337    ) -> Vec<Range<DisplayPoint>> {
12338        display_snapshot
12339            .buffer_snapshot
12340            .redacted_ranges(search_range, |file| {
12341                if let Some(file) = file {
12342                    file.is_private()
12343                        && EditorSettings::get(
12344                            Some(SettingsLocation {
12345                                worktree_id: file.worktree_id(cx),
12346                                path: file.path().as_ref(),
12347                            }),
12348                            cx,
12349                        )
12350                        .redact_private_values
12351                } else {
12352                    false
12353                }
12354            })
12355            .map(|range| {
12356                range.start.to_display_point(display_snapshot)
12357                    ..range.end.to_display_point(display_snapshot)
12358            })
12359            .collect()
12360    }
12361
12362    pub fn highlight_text<T: 'static>(
12363        &mut self,
12364        ranges: Vec<Range<Anchor>>,
12365        style: HighlightStyle,
12366        cx: &mut ViewContext<Self>,
12367    ) {
12368        self.display_map.update(cx, |map, _| {
12369            map.highlight_text(TypeId::of::<T>(), ranges, style)
12370        });
12371        cx.notify();
12372    }
12373
12374    pub(crate) fn highlight_inlays<T: 'static>(
12375        &mut self,
12376        highlights: Vec<InlayHighlight>,
12377        style: HighlightStyle,
12378        cx: &mut ViewContext<Self>,
12379    ) {
12380        self.display_map.update(cx, |map, _| {
12381            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12382        });
12383        cx.notify();
12384    }
12385
12386    pub fn text_highlights<'a, T: 'static>(
12387        &'a self,
12388        cx: &'a AppContext,
12389    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12390        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12391    }
12392
12393    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12394        let cleared = self
12395            .display_map
12396            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12397        if cleared {
12398            cx.notify();
12399        }
12400    }
12401
12402    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12403        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12404            && self.focus_handle.is_focused(cx)
12405    }
12406
12407    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12408        self.show_cursor_when_unfocused = is_enabled;
12409        cx.notify();
12410    }
12411
12412    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12413        cx.notify();
12414    }
12415
12416    fn on_buffer_event(
12417        &mut self,
12418        multibuffer: Model<MultiBuffer>,
12419        event: &multi_buffer::Event,
12420        cx: &mut ViewContext<Self>,
12421    ) {
12422        match event {
12423            multi_buffer::Event::Edited {
12424                singleton_buffer_edited,
12425            } => {
12426                self.scrollbar_marker_state.dirty = true;
12427                self.active_indent_guides_state.dirty = true;
12428                self.refresh_active_diagnostics(cx);
12429                self.refresh_code_actions(cx);
12430                if self.has_active_inline_completion(cx) {
12431                    self.update_visible_inline_completion(cx);
12432                }
12433                cx.emit(EditorEvent::BufferEdited);
12434                cx.emit(SearchEvent::MatchesInvalidated);
12435                if *singleton_buffer_edited {
12436                    if let Some(project) = &self.project {
12437                        let project = project.read(cx);
12438                        #[allow(clippy::mutable_key_type)]
12439                        let languages_affected = multibuffer
12440                            .read(cx)
12441                            .all_buffers()
12442                            .into_iter()
12443                            .filter_map(|buffer| {
12444                                let buffer = buffer.read(cx);
12445                                let language = buffer.language()?;
12446                                if project.is_local()
12447                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12448                                {
12449                                    None
12450                                } else {
12451                                    Some(language)
12452                                }
12453                            })
12454                            .cloned()
12455                            .collect::<HashSet<_>>();
12456                        if !languages_affected.is_empty() {
12457                            self.refresh_inlay_hints(
12458                                InlayHintRefreshReason::BufferEdited(languages_affected),
12459                                cx,
12460                            );
12461                        }
12462                    }
12463                }
12464
12465                let Some(project) = &self.project else { return };
12466                let (telemetry, is_via_ssh) = {
12467                    let project = project.read(cx);
12468                    let telemetry = project.client().telemetry().clone();
12469                    let is_via_ssh = project.is_via_ssh();
12470                    (telemetry, is_via_ssh)
12471                };
12472                refresh_linked_ranges(self, cx);
12473                telemetry.log_edit_event("editor", is_via_ssh);
12474            }
12475            multi_buffer::Event::ExcerptsAdded {
12476                buffer,
12477                predecessor,
12478                excerpts,
12479            } => {
12480                self.tasks_update_task = Some(self.refresh_runnables(cx));
12481                cx.emit(EditorEvent::ExcerptsAdded {
12482                    buffer: buffer.clone(),
12483                    predecessor: *predecessor,
12484                    excerpts: excerpts.clone(),
12485                });
12486                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12487            }
12488            multi_buffer::Event::ExcerptsRemoved { ids } => {
12489                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12490                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12491            }
12492            multi_buffer::Event::ExcerptsEdited { ids } => {
12493                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12494            }
12495            multi_buffer::Event::ExcerptsExpanded { ids } => {
12496                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12497            }
12498            multi_buffer::Event::Reparsed(buffer_id) => {
12499                self.tasks_update_task = Some(self.refresh_runnables(cx));
12500
12501                cx.emit(EditorEvent::Reparsed(*buffer_id));
12502            }
12503            multi_buffer::Event::LanguageChanged(buffer_id) => {
12504                linked_editing_ranges::refresh_linked_ranges(self, cx);
12505                cx.emit(EditorEvent::Reparsed(*buffer_id));
12506                cx.notify();
12507            }
12508            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12509            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12510            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12511                cx.emit(EditorEvent::TitleChanged)
12512            }
12513            multi_buffer::Event::DiffBaseChanged => {
12514                self.scrollbar_marker_state.dirty = true;
12515                cx.emit(EditorEvent::DiffBaseChanged);
12516                cx.notify();
12517            }
12518            multi_buffer::Event::DiffUpdated { buffer } => {
12519                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12520                cx.notify();
12521            }
12522            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12523            multi_buffer::Event::DiagnosticsUpdated => {
12524                self.refresh_active_diagnostics(cx);
12525                self.scrollbar_marker_state.dirty = true;
12526                cx.notify();
12527            }
12528            _ => {}
12529        };
12530    }
12531
12532    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12533        cx.notify();
12534    }
12535
12536    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12537        self.tasks_update_task = Some(self.refresh_runnables(cx));
12538        self.refresh_inline_completion(true, false, cx);
12539        self.refresh_inlay_hints(
12540            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12541                self.selections.newest_anchor().head(),
12542                &self.buffer.read(cx).snapshot(cx),
12543                cx,
12544            )),
12545            cx,
12546        );
12547
12548        let old_cursor_shape = self.cursor_shape;
12549
12550        {
12551            let editor_settings = EditorSettings::get_global(cx);
12552            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12553            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12554            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12555        }
12556
12557        if old_cursor_shape != self.cursor_shape {
12558            cx.emit(EditorEvent::CursorShapeChanged);
12559        }
12560
12561        let project_settings = ProjectSettings::get_global(cx);
12562        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12563
12564        if self.mode == EditorMode::Full {
12565            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12566            if self.git_blame_inline_enabled != inline_blame_enabled {
12567                self.toggle_git_blame_inline_internal(false, cx);
12568            }
12569        }
12570
12571        cx.notify();
12572    }
12573
12574    pub fn set_searchable(&mut self, searchable: bool) {
12575        self.searchable = searchable;
12576    }
12577
12578    pub fn searchable(&self) -> bool {
12579        self.searchable
12580    }
12581
12582    fn open_proposed_changes_editor(
12583        &mut self,
12584        _: &OpenProposedChangesEditor,
12585        cx: &mut ViewContext<Self>,
12586    ) {
12587        let Some(workspace) = self.workspace() else {
12588            cx.propagate();
12589            return;
12590        };
12591
12592        let selections = self.selections.all::<usize>(cx);
12593        let buffer = self.buffer.read(cx);
12594        let mut new_selections_by_buffer = HashMap::default();
12595        for selection in selections {
12596            for (buffer, range, _) in
12597                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12598            {
12599                let mut range = range.to_point(buffer.read(cx));
12600                range.start.column = 0;
12601                range.end.column = buffer.read(cx).line_len(range.end.row);
12602                new_selections_by_buffer
12603                    .entry(buffer)
12604                    .or_insert(Vec::new())
12605                    .push(range)
12606            }
12607        }
12608
12609        let proposed_changes_buffers = new_selections_by_buffer
12610            .into_iter()
12611            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12612            .collect::<Vec<_>>();
12613        let proposed_changes_editor = cx.new_view(|cx| {
12614            ProposedChangesEditor::new(
12615                "Proposed changes",
12616                proposed_changes_buffers,
12617                self.project.clone(),
12618                cx,
12619            )
12620        });
12621
12622        cx.window_context().defer(move |cx| {
12623            workspace.update(cx, |workspace, cx| {
12624                workspace.active_pane().update(cx, |pane, cx| {
12625                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12626                });
12627            });
12628        });
12629    }
12630
12631    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12632        self.open_excerpts_common(None, true, cx)
12633    }
12634
12635    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12636        self.open_excerpts_common(None, false, cx)
12637    }
12638
12639    fn open_excerpts_common(
12640        &mut self,
12641        jump_data: Option<JumpData>,
12642        split: bool,
12643        cx: &mut ViewContext<Self>,
12644    ) {
12645        let Some(workspace) = self.workspace() else {
12646            cx.propagate();
12647            return;
12648        };
12649
12650        if self.buffer.read(cx).is_singleton() {
12651            cx.propagate();
12652            return;
12653        }
12654
12655        let mut new_selections_by_buffer = HashMap::default();
12656        match &jump_data {
12657            Some(jump_data) => {
12658                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12659                if let Some(buffer) = multi_buffer_snapshot
12660                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12661                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12662                {
12663                    let buffer_snapshot = buffer.read(cx).snapshot();
12664                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12665                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12666                    } else {
12667                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12668                    };
12669                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12670                    new_selections_by_buffer.insert(
12671                        buffer,
12672                        (
12673                            vec![jump_to_offset..jump_to_offset],
12674                            Some(jump_data.line_offset_from_top),
12675                        ),
12676                    );
12677                }
12678            }
12679            None => {
12680                let selections = self.selections.all::<usize>(cx);
12681                let buffer = self.buffer.read(cx);
12682                for selection in selections {
12683                    for (mut buffer_handle, mut range, _) in
12684                        buffer.range_to_buffer_ranges(selection.range(), cx)
12685                    {
12686                        // When editing branch buffers, jump to the corresponding location
12687                        // in their base buffer.
12688                        let buffer = buffer_handle.read(cx);
12689                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12690                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12691                            buffer_handle = base_buffer;
12692                        }
12693
12694                        if selection.reversed {
12695                            mem::swap(&mut range.start, &mut range.end);
12696                        }
12697                        new_selections_by_buffer
12698                            .entry(buffer_handle)
12699                            .or_insert((Vec::new(), None))
12700                            .0
12701                            .push(range)
12702                    }
12703                }
12704            }
12705        }
12706
12707        if new_selections_by_buffer.is_empty() {
12708            return;
12709        }
12710
12711        // We defer the pane interaction because we ourselves are a workspace item
12712        // and activating a new item causes the pane to call a method on us reentrantly,
12713        // which panics if we're on the stack.
12714        cx.window_context().defer(move |cx| {
12715            workspace.update(cx, |workspace, cx| {
12716                let pane = if split {
12717                    workspace.adjacent_pane(cx)
12718                } else {
12719                    workspace.active_pane().clone()
12720                };
12721
12722                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12723                    let editor =
12724                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12725                    editor.update(cx, |editor, cx| {
12726                        let autoscroll = match scroll_offset {
12727                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12728                            None => Autoscroll::newest(),
12729                        };
12730                        let nav_history = editor.nav_history.take();
12731                        editor.change_selections(Some(autoscroll), cx, |s| {
12732                            s.select_ranges(ranges);
12733                        });
12734                        editor.nav_history = nav_history;
12735                    });
12736                }
12737            })
12738        });
12739    }
12740
12741    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12742        let snapshot = self.buffer.read(cx).read(cx);
12743        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12744        Some(
12745            ranges
12746                .iter()
12747                .map(move |range| {
12748                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12749                })
12750                .collect(),
12751        )
12752    }
12753
12754    fn selection_replacement_ranges(
12755        &self,
12756        range: Range<OffsetUtf16>,
12757        cx: &mut AppContext,
12758    ) -> Vec<Range<OffsetUtf16>> {
12759        let selections = self.selections.all::<OffsetUtf16>(cx);
12760        let newest_selection = selections
12761            .iter()
12762            .max_by_key(|selection| selection.id)
12763            .unwrap();
12764        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12765        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12766        let snapshot = self.buffer.read(cx).read(cx);
12767        selections
12768            .into_iter()
12769            .map(|mut selection| {
12770                selection.start.0 =
12771                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12772                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12773                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12774                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12775            })
12776            .collect()
12777    }
12778
12779    fn report_editor_event(
12780        &self,
12781        operation: &'static str,
12782        file_extension: Option<String>,
12783        cx: &AppContext,
12784    ) {
12785        if cfg!(any(test, feature = "test-support")) {
12786            return;
12787        }
12788
12789        let Some(project) = &self.project else { return };
12790
12791        // If None, we are in a file without an extension
12792        let file = self
12793            .buffer
12794            .read(cx)
12795            .as_singleton()
12796            .and_then(|b| b.read(cx).file());
12797        let file_extension = file_extension.or(file
12798            .as_ref()
12799            .and_then(|file| Path::new(file.file_name(cx)).extension())
12800            .and_then(|e| e.to_str())
12801            .map(|a| a.to_string()));
12802
12803        let vim_mode = cx
12804            .global::<SettingsStore>()
12805            .raw_user_settings()
12806            .get("vim_mode")
12807            == Some(&serde_json::Value::Bool(true));
12808
12809        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12810            == language::language_settings::InlineCompletionProvider::Copilot;
12811        let copilot_enabled_for_language = self
12812            .buffer
12813            .read(cx)
12814            .settings_at(0, cx)
12815            .show_inline_completions;
12816
12817        let project = project.read(cx);
12818        let telemetry = project.client().telemetry().clone();
12819        telemetry.report_editor_event(
12820            file_extension,
12821            vim_mode,
12822            operation,
12823            copilot_enabled,
12824            copilot_enabled_for_language,
12825            project.is_via_ssh(),
12826        )
12827    }
12828
12829    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12830    /// with each line being an array of {text, highlight} objects.
12831    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12832        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12833            return;
12834        };
12835
12836        #[derive(Serialize)]
12837        struct Chunk<'a> {
12838            text: String,
12839            highlight: Option<&'a str>,
12840        }
12841
12842        let snapshot = buffer.read(cx).snapshot();
12843        let range = self
12844            .selected_text_range(false, cx)
12845            .and_then(|selection| {
12846                if selection.range.is_empty() {
12847                    None
12848                } else {
12849                    Some(selection.range)
12850                }
12851            })
12852            .unwrap_or_else(|| 0..snapshot.len());
12853
12854        let chunks = snapshot.chunks(range, true);
12855        let mut lines = Vec::new();
12856        let mut line: VecDeque<Chunk> = VecDeque::new();
12857
12858        let Some(style) = self.style.as_ref() else {
12859            return;
12860        };
12861
12862        for chunk in chunks {
12863            let highlight = chunk
12864                .syntax_highlight_id
12865                .and_then(|id| id.name(&style.syntax));
12866            let mut chunk_lines = chunk.text.split('\n').peekable();
12867            while let Some(text) = chunk_lines.next() {
12868                let mut merged_with_last_token = false;
12869                if let Some(last_token) = line.back_mut() {
12870                    if last_token.highlight == highlight {
12871                        last_token.text.push_str(text);
12872                        merged_with_last_token = true;
12873                    }
12874                }
12875
12876                if !merged_with_last_token {
12877                    line.push_back(Chunk {
12878                        text: text.into(),
12879                        highlight,
12880                    });
12881                }
12882
12883                if chunk_lines.peek().is_some() {
12884                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12885                        line.pop_front();
12886                    }
12887                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12888                        line.pop_back();
12889                    }
12890
12891                    lines.push(mem::take(&mut line));
12892                }
12893            }
12894        }
12895
12896        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12897            return;
12898        };
12899        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12900    }
12901
12902    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12903        &self.inlay_hint_cache
12904    }
12905
12906    pub fn replay_insert_event(
12907        &mut self,
12908        text: &str,
12909        relative_utf16_range: Option<Range<isize>>,
12910        cx: &mut ViewContext<Self>,
12911    ) {
12912        if !self.input_enabled {
12913            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12914            return;
12915        }
12916        if let Some(relative_utf16_range) = relative_utf16_range {
12917            let selections = self.selections.all::<OffsetUtf16>(cx);
12918            self.change_selections(None, cx, |s| {
12919                let new_ranges = selections.into_iter().map(|range| {
12920                    let start = OffsetUtf16(
12921                        range
12922                            .head()
12923                            .0
12924                            .saturating_add_signed(relative_utf16_range.start),
12925                    );
12926                    let end = OffsetUtf16(
12927                        range
12928                            .head()
12929                            .0
12930                            .saturating_add_signed(relative_utf16_range.end),
12931                    );
12932                    start..end
12933                });
12934                s.select_ranges(new_ranges);
12935            });
12936        }
12937
12938        self.handle_input(text, cx);
12939    }
12940
12941    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12942        let Some(provider) = self.semantics_provider.as_ref() else {
12943            return false;
12944        };
12945
12946        let mut supports = false;
12947        self.buffer().read(cx).for_each_buffer(|buffer| {
12948            supports |= provider.supports_inlay_hints(buffer, cx);
12949        });
12950        supports
12951    }
12952
12953    pub fn focus(&self, cx: &mut WindowContext) {
12954        cx.focus(&self.focus_handle)
12955    }
12956
12957    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12958        self.focus_handle.is_focused(cx)
12959    }
12960
12961    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12962        cx.emit(EditorEvent::Focused);
12963
12964        if let Some(descendant) = self
12965            .last_focused_descendant
12966            .take()
12967            .and_then(|descendant| descendant.upgrade())
12968        {
12969            cx.focus(&descendant);
12970        } else {
12971            if let Some(blame) = self.blame.as_ref() {
12972                blame.update(cx, GitBlame::focus)
12973            }
12974
12975            self.blink_manager.update(cx, BlinkManager::enable);
12976            self.show_cursor_names(cx);
12977            self.buffer.update(cx, |buffer, cx| {
12978                buffer.finalize_last_transaction(cx);
12979                if self.leader_peer_id.is_none() {
12980                    buffer.set_active_selections(
12981                        &self.selections.disjoint_anchors(),
12982                        self.selections.line_mode,
12983                        self.cursor_shape,
12984                        cx,
12985                    );
12986                }
12987            });
12988        }
12989    }
12990
12991    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12992        cx.emit(EditorEvent::FocusedIn)
12993    }
12994
12995    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12996        if event.blurred != self.focus_handle {
12997            self.last_focused_descendant = Some(event.blurred);
12998        }
12999    }
13000
13001    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13002        self.blink_manager.update(cx, BlinkManager::disable);
13003        self.buffer
13004            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13005
13006        if let Some(blame) = self.blame.as_ref() {
13007            blame.update(cx, GitBlame::blur)
13008        }
13009        if !self.hover_state.focused(cx) {
13010            hide_hover(self, cx);
13011        }
13012
13013        self.hide_context_menu(cx);
13014        cx.emit(EditorEvent::Blurred);
13015        cx.notify();
13016    }
13017
13018    pub fn register_action<A: Action>(
13019        &mut self,
13020        listener: impl Fn(&A, &mut WindowContext) + 'static,
13021    ) -> Subscription {
13022        let id = self.next_editor_action_id.post_inc();
13023        let listener = Arc::new(listener);
13024        self.editor_actions.borrow_mut().insert(
13025            id,
13026            Box::new(move |cx| {
13027                let cx = cx.window_context();
13028                let listener = listener.clone();
13029                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13030                    let action = action.downcast_ref().unwrap();
13031                    if phase == DispatchPhase::Bubble {
13032                        listener(action, cx)
13033                    }
13034                })
13035            }),
13036        );
13037
13038        let editor_actions = self.editor_actions.clone();
13039        Subscription::new(move || {
13040            editor_actions.borrow_mut().remove(&id);
13041        })
13042    }
13043
13044    pub fn file_header_size(&self) -> u32 {
13045        FILE_HEADER_HEIGHT
13046    }
13047
13048    pub fn revert(
13049        &mut self,
13050        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13051        cx: &mut ViewContext<Self>,
13052    ) {
13053        self.buffer().update(cx, |multi_buffer, cx| {
13054            for (buffer_id, changes) in revert_changes {
13055                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13056                    buffer.update(cx, |buffer, cx| {
13057                        buffer.edit(
13058                            changes.into_iter().map(|(range, text)| {
13059                                (range, text.to_string().map(Arc::<str>::from))
13060                            }),
13061                            None,
13062                            cx,
13063                        );
13064                    });
13065                }
13066            }
13067        });
13068        self.change_selections(None, cx, |selections| selections.refresh());
13069    }
13070
13071    pub fn to_pixel_point(
13072        &mut self,
13073        source: multi_buffer::Anchor,
13074        editor_snapshot: &EditorSnapshot,
13075        cx: &mut ViewContext<Self>,
13076    ) -> Option<gpui::Point<Pixels>> {
13077        let source_point = source.to_display_point(editor_snapshot);
13078        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13079    }
13080
13081    pub fn display_to_pixel_point(
13082        &mut self,
13083        source: DisplayPoint,
13084        editor_snapshot: &EditorSnapshot,
13085        cx: &mut ViewContext<Self>,
13086    ) -> Option<gpui::Point<Pixels>> {
13087        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13088        let text_layout_details = self.text_layout_details(cx);
13089        let scroll_top = text_layout_details
13090            .scroll_anchor
13091            .scroll_position(editor_snapshot)
13092            .y;
13093
13094        if source.row().as_f32() < scroll_top.floor() {
13095            return None;
13096        }
13097        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13098        let source_y = line_height * (source.row().as_f32() - scroll_top);
13099        Some(gpui::Point::new(source_x, source_y))
13100    }
13101
13102    pub fn has_active_completions_menu(&self) -> bool {
13103        self.context_menu.read().as_ref().map_or(false, |menu| {
13104            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13105        })
13106    }
13107
13108    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13109        self.addons
13110            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13111    }
13112
13113    pub fn unregister_addon<T: Addon>(&mut self) {
13114        self.addons.remove(&std::any::TypeId::of::<T>());
13115    }
13116
13117    pub fn addon<T: Addon>(&self) -> Option<&T> {
13118        let type_id = std::any::TypeId::of::<T>();
13119        self.addons
13120            .get(&type_id)
13121            .and_then(|item| item.to_any().downcast_ref::<T>())
13122    }
13123}
13124
13125fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13126    let tab_size = tab_size.get() as usize;
13127    let mut width = offset;
13128
13129    for ch in text.chars() {
13130        width += if ch == '\t' {
13131            tab_size - (width % tab_size)
13132        } else {
13133            1
13134        };
13135    }
13136
13137    width - offset
13138}
13139
13140#[cfg(test)]
13141mod tests {
13142    use super::*;
13143
13144    #[test]
13145    fn test_string_size_with_expanded_tabs() {
13146        let nz = |val| NonZeroU32::new(val).unwrap();
13147        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13148        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13149        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13150        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13151        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13152        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13153        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13154        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13155    }
13156}
13157
13158/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13159struct WordBreakingTokenizer<'a> {
13160    input: &'a str,
13161}
13162
13163impl<'a> WordBreakingTokenizer<'a> {
13164    fn new(input: &'a str) -> Self {
13165        Self { input }
13166    }
13167}
13168
13169fn is_char_ideographic(ch: char) -> bool {
13170    use unicode_script::Script::*;
13171    use unicode_script::UnicodeScript;
13172    matches!(ch.script(), Han | Tangut | Yi)
13173}
13174
13175fn is_grapheme_ideographic(text: &str) -> bool {
13176    text.chars().any(is_char_ideographic)
13177}
13178
13179fn is_grapheme_whitespace(text: &str) -> bool {
13180    text.chars().any(|x| x.is_whitespace())
13181}
13182
13183fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13184    text.chars().next().map_or(false, |ch| {
13185        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13186    })
13187}
13188
13189#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13190struct WordBreakToken<'a> {
13191    token: &'a str,
13192    grapheme_len: usize,
13193    is_whitespace: bool,
13194}
13195
13196impl<'a> Iterator for WordBreakingTokenizer<'a> {
13197    /// Yields a span, the count of graphemes in the token, and whether it was
13198    /// whitespace. Note that it also breaks at word boundaries.
13199    type Item = WordBreakToken<'a>;
13200
13201    fn next(&mut self) -> Option<Self::Item> {
13202        use unicode_segmentation::UnicodeSegmentation;
13203        if self.input.is_empty() {
13204            return None;
13205        }
13206
13207        let mut iter = self.input.graphemes(true).peekable();
13208        let mut offset = 0;
13209        let mut graphemes = 0;
13210        if let Some(first_grapheme) = iter.next() {
13211            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13212            offset += first_grapheme.len();
13213            graphemes += 1;
13214            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13215                if let Some(grapheme) = iter.peek().copied() {
13216                    if should_stay_with_preceding_ideograph(grapheme) {
13217                        offset += grapheme.len();
13218                        graphemes += 1;
13219                    }
13220                }
13221            } else {
13222                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13223                let mut next_word_bound = words.peek().copied();
13224                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13225                    next_word_bound = words.next();
13226                }
13227                while let Some(grapheme) = iter.peek().copied() {
13228                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13229                        break;
13230                    };
13231                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13232                        break;
13233                    };
13234                    offset += grapheme.len();
13235                    graphemes += 1;
13236                    iter.next();
13237                }
13238            }
13239            let token = &self.input[..offset];
13240            self.input = &self.input[offset..];
13241            if is_whitespace {
13242                Some(WordBreakToken {
13243                    token: " ",
13244                    grapheme_len: 1,
13245                    is_whitespace: true,
13246                })
13247            } else {
13248                Some(WordBreakToken {
13249                    token,
13250                    grapheme_len: graphemes,
13251                    is_whitespace: false,
13252                })
13253            }
13254        } else {
13255            None
13256        }
13257    }
13258}
13259
13260#[test]
13261fn test_word_breaking_tokenizer() {
13262    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13263        ("", &[]),
13264        ("  ", &[(" ", 1, true)]),
13265        ("Ʒ", &[("Ʒ", 1, false)]),
13266        ("Ǽ", &[("Ǽ", 1, false)]),
13267        ("", &[("", 1, false)]),
13268        ("⋑⋑", &[("⋑⋑", 2, false)]),
13269        (
13270            "原理,进而",
13271            &[
13272                ("", 1, false),
13273                ("理,", 2, false),
13274                ("", 1, false),
13275                ("", 1, false),
13276            ],
13277        ),
13278        (
13279            "hello world",
13280            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13281        ),
13282        (
13283            "hello, world",
13284            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13285        ),
13286        (
13287            "  hello world",
13288            &[
13289                (" ", 1, true),
13290                ("hello", 5, false),
13291                (" ", 1, true),
13292                ("world", 5, false),
13293            ],
13294        ),
13295        (
13296            "这是什么 \n 钢笔",
13297            &[
13298                ("", 1, false),
13299                ("", 1, false),
13300                ("", 1, false),
13301                ("", 1, false),
13302                (" ", 1, true),
13303                ("", 1, false),
13304                ("", 1, false),
13305            ],
13306        ),
13307        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13308    ];
13309
13310    for (input, result) in tests {
13311        assert_eq!(
13312            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13313            result
13314                .iter()
13315                .copied()
13316                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13317                    token,
13318                    grapheme_len,
13319                    is_whitespace,
13320                })
13321                .collect::<Vec<_>>()
13322        );
13323    }
13324}
13325
13326fn wrap_with_prefix(
13327    line_prefix: String,
13328    unwrapped_text: String,
13329    wrap_column: usize,
13330    tab_size: NonZeroU32,
13331) -> String {
13332    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13333    let mut wrapped_text = String::new();
13334    let mut current_line = line_prefix.clone();
13335
13336    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13337    let mut current_line_len = line_prefix_len;
13338    for WordBreakToken {
13339        token,
13340        grapheme_len,
13341        is_whitespace,
13342    } in tokenizer
13343    {
13344        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13345            wrapped_text.push_str(current_line.trim_end());
13346            wrapped_text.push('\n');
13347            current_line.truncate(line_prefix.len());
13348            current_line_len = line_prefix_len;
13349            if !is_whitespace {
13350                current_line.push_str(token);
13351                current_line_len += grapheme_len;
13352            }
13353        } else if !is_whitespace {
13354            current_line.push_str(token);
13355            current_line_len += grapheme_len;
13356        } else if current_line_len != line_prefix_len {
13357            current_line.push(' ');
13358            current_line_len += 1;
13359        }
13360    }
13361
13362    if !current_line.is_empty() {
13363        wrapped_text.push_str(&current_line);
13364    }
13365    wrapped_text
13366}
13367
13368#[test]
13369fn test_wrap_with_prefix() {
13370    assert_eq!(
13371        wrap_with_prefix(
13372            "# ".to_string(),
13373            "abcdefg".to_string(),
13374            4,
13375            NonZeroU32::new(4).unwrap()
13376        ),
13377        "# abcdefg"
13378    );
13379    assert_eq!(
13380        wrap_with_prefix(
13381            "".to_string(),
13382            "\thello world".to_string(),
13383            8,
13384            NonZeroU32::new(4).unwrap()
13385        ),
13386        "hello\nworld"
13387    );
13388    assert_eq!(
13389        wrap_with_prefix(
13390            "// ".to_string(),
13391            "xx \nyy zz aa bb cc".to_string(),
13392            12,
13393            NonZeroU32::new(4).unwrap()
13394        ),
13395        "// xx yy zz\n// aa bb cc"
13396    );
13397    assert_eq!(
13398        wrap_with_prefix(
13399            String::new(),
13400            "这是什么 \n 钢笔".to_string(),
13401            3,
13402            NonZeroU32::new(4).unwrap()
13403        ),
13404        "这是什\n么 钢\n"
13405    );
13406}
13407
13408fn hunks_for_selections(
13409    multi_buffer_snapshot: &MultiBufferSnapshot,
13410    selections: &[Selection<Anchor>],
13411) -> Vec<MultiBufferDiffHunk> {
13412    let buffer_rows_for_selections = selections.iter().map(|selection| {
13413        let head = selection.head();
13414        let tail = selection.tail();
13415        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13416        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13417        if start > end {
13418            end..start
13419        } else {
13420            start..end
13421        }
13422    });
13423
13424    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13425}
13426
13427pub fn hunks_for_rows(
13428    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13429    multi_buffer_snapshot: &MultiBufferSnapshot,
13430) -> Vec<MultiBufferDiffHunk> {
13431    let mut hunks = Vec::new();
13432    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13433        HashMap::default();
13434    for selected_multi_buffer_rows in rows {
13435        let query_rows =
13436            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13437        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13438            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13439            // when the caret is just above or just below the deleted hunk.
13440            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13441            let related_to_selection = if allow_adjacent {
13442                hunk.row_range.overlaps(&query_rows)
13443                    || hunk.row_range.start == query_rows.end
13444                    || hunk.row_range.end == query_rows.start
13445            } else {
13446                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13447                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13448                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13449                    || selected_multi_buffer_rows.end == hunk.row_range.start
13450            };
13451            if related_to_selection {
13452                if !processed_buffer_rows
13453                    .entry(hunk.buffer_id)
13454                    .or_default()
13455                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13456                {
13457                    continue;
13458                }
13459                hunks.push(hunk);
13460            }
13461        }
13462    }
13463
13464    hunks
13465}
13466
13467pub trait CollaborationHub {
13468    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13469    fn user_participant_indices<'a>(
13470        &self,
13471        cx: &'a AppContext,
13472    ) -> &'a HashMap<u64, ParticipantIndex>;
13473    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13474}
13475
13476impl CollaborationHub for Model<Project> {
13477    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13478        self.read(cx).collaborators()
13479    }
13480
13481    fn user_participant_indices<'a>(
13482        &self,
13483        cx: &'a AppContext,
13484    ) -> &'a HashMap<u64, ParticipantIndex> {
13485        self.read(cx).user_store().read(cx).participant_indices()
13486    }
13487
13488    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13489        let this = self.read(cx);
13490        let user_ids = this.collaborators().values().map(|c| c.user_id);
13491        this.user_store().read_with(cx, |user_store, cx| {
13492            user_store.participant_names(user_ids, cx)
13493        })
13494    }
13495}
13496
13497pub trait SemanticsProvider {
13498    fn hover(
13499        &self,
13500        buffer: &Model<Buffer>,
13501        position: text::Anchor,
13502        cx: &mut AppContext,
13503    ) -> Option<Task<Vec<project::Hover>>>;
13504
13505    fn inlay_hints(
13506        &self,
13507        buffer_handle: Model<Buffer>,
13508        range: Range<text::Anchor>,
13509        cx: &mut AppContext,
13510    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13511
13512    fn resolve_inlay_hint(
13513        &self,
13514        hint: InlayHint,
13515        buffer_handle: Model<Buffer>,
13516        server_id: LanguageServerId,
13517        cx: &mut AppContext,
13518    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13519
13520    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13521
13522    fn document_highlights(
13523        &self,
13524        buffer: &Model<Buffer>,
13525        position: text::Anchor,
13526        cx: &mut AppContext,
13527    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13528
13529    fn definitions(
13530        &self,
13531        buffer: &Model<Buffer>,
13532        position: text::Anchor,
13533        kind: GotoDefinitionKind,
13534        cx: &mut AppContext,
13535    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13536
13537    fn range_for_rename(
13538        &self,
13539        buffer: &Model<Buffer>,
13540        position: text::Anchor,
13541        cx: &mut AppContext,
13542    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13543
13544    fn perform_rename(
13545        &self,
13546        buffer: &Model<Buffer>,
13547        position: text::Anchor,
13548        new_name: String,
13549        cx: &mut AppContext,
13550    ) -> Option<Task<Result<ProjectTransaction>>>;
13551}
13552
13553pub trait CompletionProvider {
13554    fn completions(
13555        &self,
13556        buffer: &Model<Buffer>,
13557        buffer_position: text::Anchor,
13558        trigger: CompletionContext,
13559        cx: &mut ViewContext<Editor>,
13560    ) -> Task<Result<Vec<Completion>>>;
13561
13562    fn resolve_completions(
13563        &self,
13564        buffer: Model<Buffer>,
13565        completion_indices: Vec<usize>,
13566        completions: Arc<RwLock<Box<[Completion]>>>,
13567        cx: &mut ViewContext<Editor>,
13568    ) -> Task<Result<bool>>;
13569
13570    fn apply_additional_edits_for_completion(
13571        &self,
13572        buffer: Model<Buffer>,
13573        completion: Completion,
13574        push_to_history: bool,
13575        cx: &mut ViewContext<Editor>,
13576    ) -> Task<Result<Option<language::Transaction>>>;
13577
13578    fn is_completion_trigger(
13579        &self,
13580        buffer: &Model<Buffer>,
13581        position: language::Anchor,
13582        text: &str,
13583        trigger_in_words: bool,
13584        cx: &mut ViewContext<Editor>,
13585    ) -> bool;
13586
13587    fn sort_completions(&self) -> bool {
13588        true
13589    }
13590}
13591
13592pub trait CodeActionProvider {
13593    fn code_actions(
13594        &self,
13595        buffer: &Model<Buffer>,
13596        range: Range<text::Anchor>,
13597        cx: &mut WindowContext,
13598    ) -> Task<Result<Vec<CodeAction>>>;
13599
13600    fn apply_code_action(
13601        &self,
13602        buffer_handle: Model<Buffer>,
13603        action: CodeAction,
13604        excerpt_id: ExcerptId,
13605        push_to_history: bool,
13606        cx: &mut WindowContext,
13607    ) -> Task<Result<ProjectTransaction>>;
13608}
13609
13610impl CodeActionProvider for Model<Project> {
13611    fn code_actions(
13612        &self,
13613        buffer: &Model<Buffer>,
13614        range: Range<text::Anchor>,
13615        cx: &mut WindowContext,
13616    ) -> Task<Result<Vec<CodeAction>>> {
13617        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13618    }
13619
13620    fn apply_code_action(
13621        &self,
13622        buffer_handle: Model<Buffer>,
13623        action: CodeAction,
13624        _excerpt_id: ExcerptId,
13625        push_to_history: bool,
13626        cx: &mut WindowContext,
13627    ) -> Task<Result<ProjectTransaction>> {
13628        self.update(cx, |project, cx| {
13629            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13630        })
13631    }
13632}
13633
13634fn snippet_completions(
13635    project: &Project,
13636    buffer: &Model<Buffer>,
13637    buffer_position: text::Anchor,
13638    cx: &mut AppContext,
13639) -> Vec<Completion> {
13640    let language = buffer.read(cx).language_at(buffer_position);
13641    let language_name = language.as_ref().map(|language| language.lsp_id());
13642    let snippet_store = project.snippets().read(cx);
13643    let snippets = snippet_store.snippets_for(language_name, cx);
13644
13645    if snippets.is_empty() {
13646        return vec![];
13647    }
13648    let snapshot = buffer.read(cx).text_snapshot();
13649    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13650
13651    let scope = language.map(|language| language.default_scope());
13652    let classifier = CharClassifier::new(scope).for_completion(true);
13653    let mut last_word = chars
13654        .take_while(|c| classifier.is_word(*c))
13655        .collect::<String>();
13656    last_word = last_word.chars().rev().collect();
13657    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13658    let to_lsp = |point: &text::Anchor| {
13659        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13660        point_to_lsp(end)
13661    };
13662    let lsp_end = to_lsp(&buffer_position);
13663    snippets
13664        .into_iter()
13665        .filter_map(|snippet| {
13666            let matching_prefix = snippet
13667                .prefix
13668                .iter()
13669                .find(|prefix| prefix.starts_with(&last_word))?;
13670            let start = as_offset - last_word.len();
13671            let start = snapshot.anchor_before(start);
13672            let range = start..buffer_position;
13673            let lsp_start = to_lsp(&start);
13674            let lsp_range = lsp::Range {
13675                start: lsp_start,
13676                end: lsp_end,
13677            };
13678            Some(Completion {
13679                old_range: range,
13680                new_text: snippet.body.clone(),
13681                label: CodeLabel {
13682                    text: matching_prefix.clone(),
13683                    runs: vec![],
13684                    filter_range: 0..matching_prefix.len(),
13685                },
13686                server_id: LanguageServerId(usize::MAX),
13687                documentation: snippet.description.clone().map(Documentation::SingleLine),
13688                lsp_completion: lsp::CompletionItem {
13689                    label: snippet.prefix.first().unwrap().clone(),
13690                    kind: Some(CompletionItemKind::SNIPPET),
13691                    label_details: snippet.description.as_ref().map(|description| {
13692                        lsp::CompletionItemLabelDetails {
13693                            detail: Some(description.clone()),
13694                            description: None,
13695                        }
13696                    }),
13697                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13698                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13699                        lsp::InsertReplaceEdit {
13700                            new_text: snippet.body.clone(),
13701                            insert: lsp_range,
13702                            replace: lsp_range,
13703                        },
13704                    )),
13705                    filter_text: Some(snippet.body.clone()),
13706                    sort_text: Some(char::MAX.to_string()),
13707                    ..Default::default()
13708                },
13709                confirm: None,
13710            })
13711        })
13712        .collect()
13713}
13714
13715impl CompletionProvider for Model<Project> {
13716    fn completions(
13717        &self,
13718        buffer: &Model<Buffer>,
13719        buffer_position: text::Anchor,
13720        options: CompletionContext,
13721        cx: &mut ViewContext<Editor>,
13722    ) -> Task<Result<Vec<Completion>>> {
13723        self.update(cx, |project, cx| {
13724            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13725            let project_completions = project.completions(buffer, buffer_position, options, cx);
13726            cx.background_executor().spawn(async move {
13727                let mut completions = project_completions.await?;
13728                //let snippets = snippets.into_iter().;
13729                completions.extend(snippets);
13730                Ok(completions)
13731            })
13732        })
13733    }
13734
13735    fn resolve_completions(
13736        &self,
13737        buffer: Model<Buffer>,
13738        completion_indices: Vec<usize>,
13739        completions: Arc<RwLock<Box<[Completion]>>>,
13740        cx: &mut ViewContext<Editor>,
13741    ) -> Task<Result<bool>> {
13742        self.update(cx, |project, cx| {
13743            project.resolve_completions(buffer, completion_indices, completions, cx)
13744        })
13745    }
13746
13747    fn apply_additional_edits_for_completion(
13748        &self,
13749        buffer: Model<Buffer>,
13750        completion: Completion,
13751        push_to_history: bool,
13752        cx: &mut ViewContext<Editor>,
13753    ) -> Task<Result<Option<language::Transaction>>> {
13754        self.update(cx, |project, cx| {
13755            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13756        })
13757    }
13758
13759    fn is_completion_trigger(
13760        &self,
13761        buffer: &Model<Buffer>,
13762        position: language::Anchor,
13763        text: &str,
13764        trigger_in_words: bool,
13765        cx: &mut ViewContext<Editor>,
13766    ) -> bool {
13767        if !EditorSettings::get_global(cx).show_completions_on_input {
13768            return false;
13769        }
13770
13771        let mut chars = text.chars();
13772        let char = if let Some(char) = chars.next() {
13773            char
13774        } else {
13775            return false;
13776        };
13777        if chars.next().is_some() {
13778            return false;
13779        }
13780
13781        let buffer = buffer.read(cx);
13782        let classifier = buffer
13783            .snapshot()
13784            .char_classifier_at(position)
13785            .for_completion(true);
13786        if trigger_in_words && classifier.is_word(char) {
13787            return true;
13788        }
13789
13790        buffer.completion_triggers().contains(text)
13791    }
13792}
13793
13794impl SemanticsProvider for Model<Project> {
13795    fn hover(
13796        &self,
13797        buffer: &Model<Buffer>,
13798        position: text::Anchor,
13799        cx: &mut AppContext,
13800    ) -> Option<Task<Vec<project::Hover>>> {
13801        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13802    }
13803
13804    fn document_highlights(
13805        &self,
13806        buffer: &Model<Buffer>,
13807        position: text::Anchor,
13808        cx: &mut AppContext,
13809    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13810        Some(self.update(cx, |project, cx| {
13811            project.document_highlights(buffer, position, cx)
13812        }))
13813    }
13814
13815    fn definitions(
13816        &self,
13817        buffer: &Model<Buffer>,
13818        position: text::Anchor,
13819        kind: GotoDefinitionKind,
13820        cx: &mut AppContext,
13821    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13822        Some(self.update(cx, |project, cx| match kind {
13823            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13824            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13825            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13826            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13827        }))
13828    }
13829
13830    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13831        // TODO: make this work for remote projects
13832        self.read(cx)
13833            .language_servers_for_buffer(buffer.read(cx), cx)
13834            .any(
13835                |(_, server)| match server.capabilities().inlay_hint_provider {
13836                    Some(lsp::OneOf::Left(enabled)) => enabled,
13837                    Some(lsp::OneOf::Right(_)) => true,
13838                    None => false,
13839                },
13840            )
13841    }
13842
13843    fn inlay_hints(
13844        &self,
13845        buffer_handle: Model<Buffer>,
13846        range: Range<text::Anchor>,
13847        cx: &mut AppContext,
13848    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13849        Some(self.update(cx, |project, cx| {
13850            project.inlay_hints(buffer_handle, range, cx)
13851        }))
13852    }
13853
13854    fn resolve_inlay_hint(
13855        &self,
13856        hint: InlayHint,
13857        buffer_handle: Model<Buffer>,
13858        server_id: LanguageServerId,
13859        cx: &mut AppContext,
13860    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13861        Some(self.update(cx, |project, cx| {
13862            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13863        }))
13864    }
13865
13866    fn range_for_rename(
13867        &self,
13868        buffer: &Model<Buffer>,
13869        position: text::Anchor,
13870        cx: &mut AppContext,
13871    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13872        Some(self.update(cx, |project, cx| {
13873            project.prepare_rename(buffer.clone(), position, cx)
13874        }))
13875    }
13876
13877    fn perform_rename(
13878        &self,
13879        buffer: &Model<Buffer>,
13880        position: text::Anchor,
13881        new_name: String,
13882        cx: &mut AppContext,
13883    ) -> Option<Task<Result<ProjectTransaction>>> {
13884        Some(self.update(cx, |project, cx| {
13885            project.perform_rename(buffer.clone(), position, new_name, cx)
13886        }))
13887    }
13888}
13889
13890fn inlay_hint_settings(
13891    location: Anchor,
13892    snapshot: &MultiBufferSnapshot,
13893    cx: &mut ViewContext<'_, Editor>,
13894) -> InlayHintSettings {
13895    let file = snapshot.file_at(location);
13896    let language = snapshot.language_at(location).map(|l| l.name());
13897    language_settings(language, file, cx).inlay_hints
13898}
13899
13900fn consume_contiguous_rows(
13901    contiguous_row_selections: &mut Vec<Selection<Point>>,
13902    selection: &Selection<Point>,
13903    display_map: &DisplaySnapshot,
13904    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13905) -> (MultiBufferRow, MultiBufferRow) {
13906    contiguous_row_selections.push(selection.clone());
13907    let start_row = MultiBufferRow(selection.start.row);
13908    let mut end_row = ending_row(selection, display_map);
13909
13910    while let Some(next_selection) = selections.peek() {
13911        if next_selection.start.row <= end_row.0 {
13912            end_row = ending_row(next_selection, display_map);
13913            contiguous_row_selections.push(selections.next().unwrap().clone());
13914        } else {
13915            break;
13916        }
13917    }
13918    (start_row, end_row)
13919}
13920
13921fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13922    if next_selection.end.column > 0 || next_selection.is_empty() {
13923        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13924    } else {
13925        MultiBufferRow(next_selection.end.row)
13926    }
13927}
13928
13929impl EditorSnapshot {
13930    pub fn remote_selections_in_range<'a>(
13931        &'a self,
13932        range: &'a Range<Anchor>,
13933        collaboration_hub: &dyn CollaborationHub,
13934        cx: &'a AppContext,
13935    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13936        let participant_names = collaboration_hub.user_names(cx);
13937        let participant_indices = collaboration_hub.user_participant_indices(cx);
13938        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13939        let collaborators_by_replica_id = collaborators_by_peer_id
13940            .iter()
13941            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13942            .collect::<HashMap<_, _>>();
13943        self.buffer_snapshot
13944            .selections_in_range(range, false)
13945            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13946                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13947                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13948                let user_name = participant_names.get(&collaborator.user_id).cloned();
13949                Some(RemoteSelection {
13950                    replica_id,
13951                    selection,
13952                    cursor_shape,
13953                    line_mode,
13954                    participant_index,
13955                    peer_id: collaborator.peer_id,
13956                    user_name,
13957                })
13958            })
13959    }
13960
13961    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13962        self.display_snapshot.buffer_snapshot.language_at(position)
13963    }
13964
13965    pub fn is_focused(&self) -> bool {
13966        self.is_focused
13967    }
13968
13969    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13970        self.placeholder_text.as_ref()
13971    }
13972
13973    pub fn scroll_position(&self) -> gpui::Point<f32> {
13974        self.scroll_anchor.scroll_position(&self.display_snapshot)
13975    }
13976
13977    fn gutter_dimensions(
13978        &self,
13979        font_id: FontId,
13980        font_size: Pixels,
13981        em_width: Pixels,
13982        em_advance: Pixels,
13983        max_line_number_width: Pixels,
13984        cx: &AppContext,
13985    ) -> GutterDimensions {
13986        if !self.show_gutter {
13987            return GutterDimensions::default();
13988        }
13989        let descent = cx.text_system().descent(font_id, font_size);
13990
13991        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13992            matches!(
13993                ProjectSettings::get_global(cx).git.git_gutter,
13994                Some(GitGutterSetting::TrackedFiles)
13995            )
13996        });
13997        let gutter_settings = EditorSettings::get_global(cx).gutter;
13998        let show_line_numbers = self
13999            .show_line_numbers
14000            .unwrap_or(gutter_settings.line_numbers);
14001        let line_gutter_width = if show_line_numbers {
14002            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14003            let min_width_for_number_on_gutter = em_advance * 4.0;
14004            max_line_number_width.max(min_width_for_number_on_gutter)
14005        } else {
14006            0.0.into()
14007        };
14008
14009        let show_code_actions = self
14010            .show_code_actions
14011            .unwrap_or(gutter_settings.code_actions);
14012
14013        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14014
14015        let git_blame_entries_width =
14016            self.git_blame_gutter_max_author_length
14017                .map(|max_author_length| {
14018                    // Length of the author name, but also space for the commit hash,
14019                    // the spacing and the timestamp.
14020                    let max_char_count = max_author_length
14021                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14022                        + 7 // length of commit sha
14023                        + 14 // length of max relative timestamp ("60 minutes ago")
14024                        + 4; // gaps and margins
14025
14026                    em_advance * max_char_count
14027                });
14028
14029        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14030        left_padding += if show_code_actions || show_runnables {
14031            em_width * 3.0
14032        } else if show_git_gutter && show_line_numbers {
14033            em_width * 2.0
14034        } else if show_git_gutter || show_line_numbers {
14035            em_width
14036        } else {
14037            px(0.)
14038        };
14039
14040        let right_padding = if gutter_settings.folds && show_line_numbers {
14041            em_width * 4.0
14042        } else if gutter_settings.folds {
14043            em_width * 3.0
14044        } else if show_line_numbers {
14045            em_width
14046        } else {
14047            px(0.)
14048        };
14049
14050        GutterDimensions {
14051            left_padding,
14052            right_padding,
14053            width: line_gutter_width + left_padding + right_padding,
14054            margin: -descent,
14055            git_blame_entries_width,
14056        }
14057    }
14058
14059    pub fn render_fold_toggle(
14060        &self,
14061        buffer_row: MultiBufferRow,
14062        row_contains_cursor: bool,
14063        editor: View<Editor>,
14064        cx: &mut WindowContext,
14065    ) -> Option<AnyElement> {
14066        let folded = self.is_line_folded(buffer_row);
14067
14068        if let Some(crease) = self
14069            .crease_snapshot
14070            .query_row(buffer_row, &self.buffer_snapshot)
14071        {
14072            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14073                if folded {
14074                    editor.update(cx, |editor, cx| {
14075                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14076                    });
14077                } else {
14078                    editor.update(cx, |editor, cx| {
14079                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14080                    });
14081                }
14082            });
14083
14084            Some((crease.render_toggle)(
14085                buffer_row,
14086                folded,
14087                toggle_callback,
14088                cx,
14089            ))
14090        } else if folded
14091            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
14092        {
14093            Some(
14094                Disclosure::new(("indent-fold-indicator", 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        let crease = self
14117            .crease_snapshot
14118            .query_row(buffer_row, &self.buffer_snapshot)?;
14119        Some((crease.render_trailer)(buffer_row, folded, cx))
14120    }
14121}
14122
14123impl Deref for EditorSnapshot {
14124    type Target = DisplaySnapshot;
14125
14126    fn deref(&self) -> &Self::Target {
14127        &self.display_snapshot
14128    }
14129}
14130
14131#[derive(Clone, Debug, PartialEq, Eq)]
14132pub enum EditorEvent {
14133    InputIgnored {
14134        text: Arc<str>,
14135    },
14136    InputHandled {
14137        utf16_range_to_replace: Option<Range<isize>>,
14138        text: Arc<str>,
14139    },
14140    ExcerptsAdded {
14141        buffer: Model<Buffer>,
14142        predecessor: ExcerptId,
14143        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14144    },
14145    ExcerptsRemoved {
14146        ids: Vec<ExcerptId>,
14147    },
14148    ExcerptsEdited {
14149        ids: Vec<ExcerptId>,
14150    },
14151    ExcerptsExpanded {
14152        ids: Vec<ExcerptId>,
14153    },
14154    BufferEdited,
14155    Edited {
14156        transaction_id: clock::Lamport,
14157    },
14158    Reparsed(BufferId),
14159    Focused,
14160    FocusedIn,
14161    Blurred,
14162    DirtyChanged,
14163    Saved,
14164    TitleChanged,
14165    DiffBaseChanged,
14166    SelectionsChanged {
14167        local: bool,
14168    },
14169    ScrollPositionChanged {
14170        local: bool,
14171        autoscroll: bool,
14172    },
14173    Closed,
14174    TransactionUndone {
14175        transaction_id: clock::Lamport,
14176    },
14177    TransactionBegun {
14178        transaction_id: clock::Lamport,
14179    },
14180    Reloaded,
14181    CursorShapeChanged,
14182}
14183
14184impl EventEmitter<EditorEvent> for Editor {}
14185
14186impl FocusableView for Editor {
14187    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14188        self.focus_handle.clone()
14189    }
14190}
14191
14192impl Render for Editor {
14193    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14194        let settings = ThemeSettings::get_global(cx);
14195
14196        let mut text_style = match self.mode {
14197            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14198                color: cx.theme().colors().editor_foreground,
14199                font_family: settings.ui_font.family.clone(),
14200                font_features: settings.ui_font.features.clone(),
14201                font_fallbacks: settings.ui_font.fallbacks.clone(),
14202                font_size: rems(0.875).into(),
14203                font_weight: settings.ui_font.weight,
14204                line_height: relative(settings.buffer_line_height.value()),
14205                ..Default::default()
14206            },
14207            EditorMode::Full => TextStyle {
14208                color: cx.theme().colors().editor_foreground,
14209                font_family: settings.buffer_font.family.clone(),
14210                font_features: settings.buffer_font.features.clone(),
14211                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14212                font_size: settings.buffer_font_size(cx).into(),
14213                font_weight: settings.buffer_font.weight,
14214                line_height: relative(settings.buffer_line_height.value()),
14215                ..Default::default()
14216            },
14217        };
14218        if let Some(text_style_refinement) = &self.text_style_refinement {
14219            text_style.refine(text_style_refinement)
14220        }
14221
14222        let background = match self.mode {
14223            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14224            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14225            EditorMode::Full => cx.theme().colors().editor_background,
14226        };
14227
14228        EditorElement::new(
14229            cx.view(),
14230            EditorStyle {
14231                background,
14232                local_player: cx.theme().players().local(),
14233                text: text_style,
14234                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14235                syntax: cx.theme().syntax().clone(),
14236                status: cx.theme().status().clone(),
14237                inlay_hints_style: make_inlay_hints_style(cx),
14238                suggestions_style: HighlightStyle {
14239                    color: Some(cx.theme().status().predictive),
14240                    ..HighlightStyle::default()
14241                },
14242                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14243            },
14244        )
14245    }
14246}
14247
14248impl ViewInputHandler for Editor {
14249    fn text_for_range(
14250        &mut self,
14251        range_utf16: Range<usize>,
14252        cx: &mut ViewContext<Self>,
14253    ) -> Option<String> {
14254        Some(
14255            self.buffer
14256                .read(cx)
14257                .read(cx)
14258                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14259                .collect(),
14260        )
14261    }
14262
14263    fn selected_text_range(
14264        &mut self,
14265        ignore_disabled_input: bool,
14266        cx: &mut ViewContext<Self>,
14267    ) -> Option<UTF16Selection> {
14268        // Prevent the IME menu from appearing when holding down an alphabetic key
14269        // while input is disabled.
14270        if !ignore_disabled_input && !self.input_enabled {
14271            return None;
14272        }
14273
14274        let selection = self.selections.newest::<OffsetUtf16>(cx);
14275        let range = selection.range();
14276
14277        Some(UTF16Selection {
14278            range: range.start.0..range.end.0,
14279            reversed: selection.reversed,
14280        })
14281    }
14282
14283    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14284        let snapshot = self.buffer.read(cx).read(cx);
14285        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14286        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14287    }
14288
14289    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14290        self.clear_highlights::<InputComposition>(cx);
14291        self.ime_transaction.take();
14292    }
14293
14294    fn replace_text_in_range(
14295        &mut self,
14296        range_utf16: Option<Range<usize>>,
14297        text: &str,
14298        cx: &mut ViewContext<Self>,
14299    ) {
14300        if !self.input_enabled {
14301            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14302            return;
14303        }
14304
14305        self.transact(cx, |this, cx| {
14306            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14307                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14308                Some(this.selection_replacement_ranges(range_utf16, cx))
14309            } else {
14310                this.marked_text_ranges(cx)
14311            };
14312
14313            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14314                let newest_selection_id = this.selections.newest_anchor().id;
14315                this.selections
14316                    .all::<OffsetUtf16>(cx)
14317                    .iter()
14318                    .zip(ranges_to_replace.iter())
14319                    .find_map(|(selection, range)| {
14320                        if selection.id == newest_selection_id {
14321                            Some(
14322                                (range.start.0 as isize - selection.head().0 as isize)
14323                                    ..(range.end.0 as isize - selection.head().0 as isize),
14324                            )
14325                        } else {
14326                            None
14327                        }
14328                    })
14329            });
14330
14331            cx.emit(EditorEvent::InputHandled {
14332                utf16_range_to_replace: range_to_replace,
14333                text: text.into(),
14334            });
14335
14336            if let Some(new_selected_ranges) = new_selected_ranges {
14337                this.change_selections(None, cx, |selections| {
14338                    selections.select_ranges(new_selected_ranges)
14339                });
14340                this.backspace(&Default::default(), cx);
14341            }
14342
14343            this.handle_input(text, cx);
14344        });
14345
14346        if let Some(transaction) = self.ime_transaction {
14347            self.buffer.update(cx, |buffer, cx| {
14348                buffer.group_until_transaction(transaction, cx);
14349            });
14350        }
14351
14352        self.unmark_text(cx);
14353    }
14354
14355    fn replace_and_mark_text_in_range(
14356        &mut self,
14357        range_utf16: Option<Range<usize>>,
14358        text: &str,
14359        new_selected_range_utf16: Option<Range<usize>>,
14360        cx: &mut ViewContext<Self>,
14361    ) {
14362        if !self.input_enabled {
14363            return;
14364        }
14365
14366        let transaction = self.transact(cx, |this, cx| {
14367            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14368                let snapshot = this.buffer.read(cx).read(cx);
14369                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14370                    for marked_range in &mut marked_ranges {
14371                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14372                        marked_range.start.0 += relative_range_utf16.start;
14373                        marked_range.start =
14374                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14375                        marked_range.end =
14376                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14377                    }
14378                }
14379                Some(marked_ranges)
14380            } else if let Some(range_utf16) = range_utf16 {
14381                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14382                Some(this.selection_replacement_ranges(range_utf16, cx))
14383            } else {
14384                None
14385            };
14386
14387            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14388                let newest_selection_id = this.selections.newest_anchor().id;
14389                this.selections
14390                    .all::<OffsetUtf16>(cx)
14391                    .iter()
14392                    .zip(ranges_to_replace.iter())
14393                    .find_map(|(selection, range)| {
14394                        if selection.id == newest_selection_id {
14395                            Some(
14396                                (range.start.0 as isize - selection.head().0 as isize)
14397                                    ..(range.end.0 as isize - selection.head().0 as isize),
14398                            )
14399                        } else {
14400                            None
14401                        }
14402                    })
14403            });
14404
14405            cx.emit(EditorEvent::InputHandled {
14406                utf16_range_to_replace: range_to_replace,
14407                text: text.into(),
14408            });
14409
14410            if let Some(ranges) = ranges_to_replace {
14411                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14412            }
14413
14414            let marked_ranges = {
14415                let snapshot = this.buffer.read(cx).read(cx);
14416                this.selections
14417                    .disjoint_anchors()
14418                    .iter()
14419                    .map(|selection| {
14420                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14421                    })
14422                    .collect::<Vec<_>>()
14423            };
14424
14425            if text.is_empty() {
14426                this.unmark_text(cx);
14427            } else {
14428                this.highlight_text::<InputComposition>(
14429                    marked_ranges.clone(),
14430                    HighlightStyle {
14431                        underline: Some(UnderlineStyle {
14432                            thickness: px(1.),
14433                            color: None,
14434                            wavy: false,
14435                        }),
14436                        ..Default::default()
14437                    },
14438                    cx,
14439                );
14440            }
14441
14442            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14443            let use_autoclose = this.use_autoclose;
14444            let use_auto_surround = this.use_auto_surround;
14445            this.set_use_autoclose(false);
14446            this.set_use_auto_surround(false);
14447            this.handle_input(text, cx);
14448            this.set_use_autoclose(use_autoclose);
14449            this.set_use_auto_surround(use_auto_surround);
14450
14451            if let Some(new_selected_range) = new_selected_range_utf16 {
14452                let snapshot = this.buffer.read(cx).read(cx);
14453                let new_selected_ranges = marked_ranges
14454                    .into_iter()
14455                    .map(|marked_range| {
14456                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14457                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14458                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14459                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14460                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14461                    })
14462                    .collect::<Vec<_>>();
14463
14464                drop(snapshot);
14465                this.change_selections(None, cx, |selections| {
14466                    selections.select_ranges(new_selected_ranges)
14467                });
14468            }
14469        });
14470
14471        self.ime_transaction = self.ime_transaction.or(transaction);
14472        if let Some(transaction) = self.ime_transaction {
14473            self.buffer.update(cx, |buffer, cx| {
14474                buffer.group_until_transaction(transaction, cx);
14475            });
14476        }
14477
14478        if self.text_highlights::<InputComposition>(cx).is_none() {
14479            self.ime_transaction.take();
14480        }
14481    }
14482
14483    fn bounds_for_range(
14484        &mut self,
14485        range_utf16: Range<usize>,
14486        element_bounds: gpui::Bounds<Pixels>,
14487        cx: &mut ViewContext<Self>,
14488    ) -> Option<gpui::Bounds<Pixels>> {
14489        let text_layout_details = self.text_layout_details(cx);
14490        let style = &text_layout_details.editor_style;
14491        let font_id = cx.text_system().resolve_font(&style.text.font());
14492        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14493        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14494
14495        let em_width = cx
14496            .text_system()
14497            .typographic_bounds(font_id, font_size, 'm')
14498            .unwrap()
14499            .size
14500            .width;
14501
14502        let snapshot = self.snapshot(cx);
14503        let scroll_position = snapshot.scroll_position();
14504        let scroll_left = scroll_position.x * em_width;
14505
14506        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14507        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14508            + self.gutter_dimensions.width;
14509        let y = line_height * (start.row().as_f32() - scroll_position.y);
14510
14511        Some(Bounds {
14512            origin: element_bounds.origin + point(x, y),
14513            size: size(em_width, line_height),
14514        })
14515    }
14516}
14517
14518trait SelectionExt {
14519    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14520    fn spanned_rows(
14521        &self,
14522        include_end_if_at_line_start: bool,
14523        map: &DisplaySnapshot,
14524    ) -> Range<MultiBufferRow>;
14525}
14526
14527impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14528    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14529        let start = self
14530            .start
14531            .to_point(&map.buffer_snapshot)
14532            .to_display_point(map);
14533        let end = self
14534            .end
14535            .to_point(&map.buffer_snapshot)
14536            .to_display_point(map);
14537        if self.reversed {
14538            end..start
14539        } else {
14540            start..end
14541        }
14542    }
14543
14544    fn spanned_rows(
14545        &self,
14546        include_end_if_at_line_start: bool,
14547        map: &DisplaySnapshot,
14548    ) -> Range<MultiBufferRow> {
14549        let start = self.start.to_point(&map.buffer_snapshot);
14550        let mut end = self.end.to_point(&map.buffer_snapshot);
14551        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14552            end.row -= 1;
14553        }
14554
14555        let buffer_start = map.prev_line_boundary(start).0;
14556        let buffer_end = map.next_line_boundary(end).0;
14557        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14558    }
14559}
14560
14561impl<T: InvalidationRegion> InvalidationStack<T> {
14562    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14563    where
14564        S: Clone + ToOffset,
14565    {
14566        while let Some(region) = self.last() {
14567            let all_selections_inside_invalidation_ranges =
14568                if selections.len() == region.ranges().len() {
14569                    selections
14570                        .iter()
14571                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14572                        .all(|(selection, invalidation_range)| {
14573                            let head = selection.head().to_offset(buffer);
14574                            invalidation_range.start <= head && invalidation_range.end >= head
14575                        })
14576                } else {
14577                    false
14578                };
14579
14580            if all_selections_inside_invalidation_ranges {
14581                break;
14582            } else {
14583                self.pop();
14584            }
14585        }
14586    }
14587}
14588
14589impl<T> Default for InvalidationStack<T> {
14590    fn default() -> Self {
14591        Self(Default::default())
14592    }
14593}
14594
14595impl<T> Deref for InvalidationStack<T> {
14596    type Target = Vec<T>;
14597
14598    fn deref(&self) -> &Self::Target {
14599        &self.0
14600    }
14601}
14602
14603impl<T> DerefMut for InvalidationStack<T> {
14604    fn deref_mut(&mut self) -> &mut Self::Target {
14605        &mut self.0
14606    }
14607}
14608
14609impl InvalidationRegion for SnippetState {
14610    fn ranges(&self) -> &[Range<Anchor>] {
14611        &self.ranges[self.active_index]
14612    }
14613}
14614
14615pub fn diagnostic_block_renderer(
14616    diagnostic: Diagnostic,
14617    max_message_rows: Option<u8>,
14618    allow_closing: bool,
14619    _is_valid: bool,
14620) -> RenderBlock {
14621    let (text_without_backticks, code_ranges) =
14622        highlight_diagnostic_message(&diagnostic, max_message_rows);
14623
14624    Box::new(move |cx: &mut BlockContext| {
14625        let group_id: SharedString = cx.block_id.to_string().into();
14626
14627        let mut text_style = cx.text_style().clone();
14628        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14629        let theme_settings = ThemeSettings::get_global(cx);
14630        text_style.font_family = theme_settings.buffer_font.family.clone();
14631        text_style.font_style = theme_settings.buffer_font.style;
14632        text_style.font_features = theme_settings.buffer_font.features.clone();
14633        text_style.font_weight = theme_settings.buffer_font.weight;
14634
14635        let multi_line_diagnostic = diagnostic.message.contains('\n');
14636
14637        let buttons = |diagnostic: &Diagnostic| {
14638            if multi_line_diagnostic {
14639                v_flex()
14640            } else {
14641                h_flex()
14642            }
14643            .when(allow_closing, |div| {
14644                div.children(diagnostic.is_primary.then(|| {
14645                    IconButton::new("close-block", IconName::XCircle)
14646                        .icon_color(Color::Muted)
14647                        .size(ButtonSize::Compact)
14648                        .style(ButtonStyle::Transparent)
14649                        .visible_on_hover(group_id.clone())
14650                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14651                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14652                }))
14653            })
14654            .child(
14655                IconButton::new("copy-block", IconName::Copy)
14656                    .icon_color(Color::Muted)
14657                    .size(ButtonSize::Compact)
14658                    .style(ButtonStyle::Transparent)
14659                    .visible_on_hover(group_id.clone())
14660                    .on_click({
14661                        let message = diagnostic.message.clone();
14662                        move |_click, cx| {
14663                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14664                        }
14665                    })
14666                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14667            )
14668        };
14669
14670        let icon_size = buttons(&diagnostic)
14671            .into_any_element()
14672            .layout_as_root(AvailableSpace::min_size(), cx);
14673
14674        h_flex()
14675            .id(cx.block_id)
14676            .group(group_id.clone())
14677            .relative()
14678            .size_full()
14679            .pl(cx.gutter_dimensions.width)
14680            .w(cx.max_width - cx.gutter_dimensions.full_width())
14681            .child(
14682                div()
14683                    .flex()
14684                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14685                    .flex_shrink(),
14686            )
14687            .child(buttons(&diagnostic))
14688            .child(div().flex().flex_shrink_0().child(
14689                StyledText::new(text_without_backticks.clone()).with_highlights(
14690                    &text_style,
14691                    code_ranges.iter().map(|range| {
14692                        (
14693                            range.clone(),
14694                            HighlightStyle {
14695                                font_weight: Some(FontWeight::BOLD),
14696                                ..Default::default()
14697                            },
14698                        )
14699                    }),
14700                ),
14701            ))
14702            .into_any_element()
14703    })
14704}
14705
14706pub fn highlight_diagnostic_message(
14707    diagnostic: &Diagnostic,
14708    mut max_message_rows: Option<u8>,
14709) -> (SharedString, Vec<Range<usize>>) {
14710    let mut text_without_backticks = String::new();
14711    let mut code_ranges = Vec::new();
14712
14713    if let Some(source) = &diagnostic.source {
14714        text_without_backticks.push_str(source);
14715        code_ranges.push(0..source.len());
14716        text_without_backticks.push_str(": ");
14717    }
14718
14719    let mut prev_offset = 0;
14720    let mut in_code_block = false;
14721    let has_row_limit = max_message_rows.is_some();
14722    let mut newline_indices = diagnostic
14723        .message
14724        .match_indices('\n')
14725        .filter(|_| has_row_limit)
14726        .map(|(ix, _)| ix)
14727        .fuse()
14728        .peekable();
14729
14730    for (quote_ix, _) in diagnostic
14731        .message
14732        .match_indices('`')
14733        .chain([(diagnostic.message.len(), "")])
14734    {
14735        let mut first_newline_ix = None;
14736        let mut last_newline_ix = None;
14737        while let Some(newline_ix) = newline_indices.peek() {
14738            if *newline_ix < quote_ix {
14739                if first_newline_ix.is_none() {
14740                    first_newline_ix = Some(*newline_ix);
14741                }
14742                last_newline_ix = Some(*newline_ix);
14743
14744                if let Some(rows_left) = &mut max_message_rows {
14745                    if *rows_left == 0 {
14746                        break;
14747                    } else {
14748                        *rows_left -= 1;
14749                    }
14750                }
14751                let _ = newline_indices.next();
14752            } else {
14753                break;
14754            }
14755        }
14756        let prev_len = text_without_backticks.len();
14757        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14758        text_without_backticks.push_str(new_text);
14759        if in_code_block {
14760            code_ranges.push(prev_len..text_without_backticks.len());
14761        }
14762        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14763        in_code_block = !in_code_block;
14764        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14765            text_without_backticks.push_str("...");
14766            break;
14767        }
14768    }
14769
14770    (text_without_backticks.into(), code_ranges)
14771}
14772
14773fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14774    match severity {
14775        DiagnosticSeverity::ERROR => colors.error,
14776        DiagnosticSeverity::WARNING => colors.warning,
14777        DiagnosticSeverity::INFORMATION => colors.info,
14778        DiagnosticSeverity::HINT => colors.info,
14779        _ => colors.ignored,
14780    }
14781}
14782
14783pub fn styled_runs_for_code_label<'a>(
14784    label: &'a CodeLabel,
14785    syntax_theme: &'a theme::SyntaxTheme,
14786) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14787    let fade_out = HighlightStyle {
14788        fade_out: Some(0.35),
14789        ..Default::default()
14790    };
14791
14792    let mut prev_end = label.filter_range.end;
14793    label
14794        .runs
14795        .iter()
14796        .enumerate()
14797        .flat_map(move |(ix, (range, highlight_id))| {
14798            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14799                style
14800            } else {
14801                return Default::default();
14802            };
14803            let mut muted_style = style;
14804            muted_style.highlight(fade_out);
14805
14806            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14807            if range.start >= label.filter_range.end {
14808                if range.start > prev_end {
14809                    runs.push((prev_end..range.start, fade_out));
14810                }
14811                runs.push((range.clone(), muted_style));
14812            } else if range.end <= label.filter_range.end {
14813                runs.push((range.clone(), style));
14814            } else {
14815                runs.push((range.start..label.filter_range.end, style));
14816                runs.push((label.filter_range.end..range.end, muted_style));
14817            }
14818            prev_end = cmp::max(prev_end, range.end);
14819
14820            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14821                runs.push((prev_end..label.text.len(), fade_out));
14822            }
14823
14824            runs
14825        })
14826}
14827
14828pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14829    let mut prev_index = 0;
14830    let mut prev_codepoint: Option<char> = None;
14831    text.char_indices()
14832        .chain([(text.len(), '\0')])
14833        .filter_map(move |(index, codepoint)| {
14834            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14835            let is_boundary = index == text.len()
14836                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14837                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14838            if is_boundary {
14839                let chunk = &text[prev_index..index];
14840                prev_index = index;
14841                Some(chunk)
14842            } else {
14843                None
14844            }
14845        })
14846}
14847
14848pub trait RangeToAnchorExt: Sized {
14849    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14850
14851    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14852        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14853        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14854    }
14855}
14856
14857impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14858    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14859        let start_offset = self.start.to_offset(snapshot);
14860        let end_offset = self.end.to_offset(snapshot);
14861        if start_offset == end_offset {
14862            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14863        } else {
14864            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14865        }
14866    }
14867}
14868
14869pub trait RowExt {
14870    fn as_f32(&self) -> f32;
14871
14872    fn next_row(&self) -> Self;
14873
14874    fn previous_row(&self) -> Self;
14875
14876    fn minus(&self, other: Self) -> u32;
14877}
14878
14879impl RowExt for DisplayRow {
14880    fn as_f32(&self) -> f32 {
14881        self.0 as f32
14882    }
14883
14884    fn next_row(&self) -> Self {
14885        Self(self.0 + 1)
14886    }
14887
14888    fn previous_row(&self) -> Self {
14889        Self(self.0.saturating_sub(1))
14890    }
14891
14892    fn minus(&self, other: Self) -> u32 {
14893        self.0 - other.0
14894    }
14895}
14896
14897impl RowExt for MultiBufferRow {
14898    fn as_f32(&self) -> f32 {
14899        self.0 as f32
14900    }
14901
14902    fn next_row(&self) -> Self {
14903        Self(self.0 + 1)
14904    }
14905
14906    fn previous_row(&self) -> Self {
14907        Self(self.0.saturating_sub(1))
14908    }
14909
14910    fn minus(&self, other: Self) -> u32 {
14911        self.0 - other.0
14912    }
14913}
14914
14915trait RowRangeExt {
14916    type Row;
14917
14918    fn len(&self) -> usize;
14919
14920    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14921}
14922
14923impl RowRangeExt for Range<MultiBufferRow> {
14924    type Row = MultiBufferRow;
14925
14926    fn len(&self) -> usize {
14927        (self.end.0 - self.start.0) as usize
14928    }
14929
14930    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14931        (self.start.0..self.end.0).map(MultiBufferRow)
14932    }
14933}
14934
14935impl RowRangeExt for Range<DisplayRow> {
14936    type Row = DisplayRow;
14937
14938    fn len(&self) -> usize {
14939        (self.end.0 - self.start.0) as usize
14940    }
14941
14942    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14943        (self.start.0..self.end.0).map(DisplayRow)
14944    }
14945}
14946
14947fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14948    if hunk.diff_base_byte_range.is_empty() {
14949        DiffHunkStatus::Added
14950    } else if hunk.row_range.is_empty() {
14951        DiffHunkStatus::Removed
14952    } else {
14953        DiffHunkStatus::Modified
14954    }
14955}
14956
14957/// If select range has more than one line, we
14958/// just point the cursor to range.start.
14959fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14960    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14961        range
14962    } else {
14963        range.start..range.start
14964    }
14965}
14966
14967const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);