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/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  538///
  539/// See the [module level documentation](self) for more information.
  540pub struct Editor {
  541    focus_handle: FocusHandle,
  542    last_focused_descendant: Option<WeakFocusHandle>,
  543    /// The text buffer being edited
  544    buffer: Model<MultiBuffer>,
  545    /// Map of how text in the buffer should be displayed.
  546    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  547    pub display_map: Model<DisplayMap>,
  548    pub selections: SelectionsCollection,
  549    pub scroll_manager: ScrollManager,
  550    /// When inline assist editors are linked, they all render cursors because
  551    /// typing enters text into each of them, even the ones that aren't focused.
  552    pub(crate) show_cursor_when_unfocused: bool,
  553    columnar_selection_tail: Option<Anchor>,
  554    add_selections_state: Option<AddSelectionsState>,
  555    select_next_state: Option<SelectNextState>,
  556    select_prev_state: Option<SelectNextState>,
  557    selection_history: SelectionHistory,
  558    autoclose_regions: Vec<AutocloseRegion>,
  559    snippet_stack: InvalidationStack<SnippetState>,
  560    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  561    ime_transaction: Option<TransactionId>,
  562    active_diagnostics: Option<ActiveDiagnosticGroup>,
  563    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  564
  565    project: Option<Model<Project>>,
  566    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  567    completion_provider: Option<Box<dyn CompletionProvider>>,
  568    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  569    blink_manager: Model<BlinkManager>,
  570    show_cursor_names: bool,
  571    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  572    pub show_local_selections: bool,
  573    mode: EditorMode,
  574    show_breadcrumbs: bool,
  575    show_gutter: bool,
  576    show_line_numbers: Option<bool>,
  577    use_relative_line_numbers: Option<bool>,
  578    show_git_diff_gutter: Option<bool>,
  579    show_code_actions: Option<bool>,
  580    show_runnables: Option<bool>,
  581    show_wrap_guides: Option<bool>,
  582    show_indent_guides: Option<bool>,
  583    placeholder_text: Option<Arc<str>>,
  584    highlight_order: usize,
  585    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  586    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  587    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  588    scrollbar_marker_state: ScrollbarMarkerState,
  589    active_indent_guides_state: ActiveIndentGuidesState,
  590    nav_history: Option<ItemNavHistory>,
  591    context_menu: RwLock<Option<ContextMenu>>,
  592    mouse_context_menu: Option<MouseContextMenu>,
  593    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  594    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  595    signature_help_state: SignatureHelpState,
  596    auto_signature_help: Option<bool>,
  597    find_all_references_task_sources: Vec<Anchor>,
  598    next_completion_id: CompletionId,
  599    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  600    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  601    code_actions_task: Option<Task<Result<()>>>,
  602    document_highlights_task: Option<Task<()>>,
  603    linked_editing_range_task: Option<Task<Option<()>>>,
  604    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  605    pending_rename: Option<RenameState>,
  606    searchable: bool,
  607    cursor_shape: CursorShape,
  608    current_line_highlight: Option<CurrentLineHighlight>,
  609    collapse_matches: bool,
  610    autoindent_mode: Option<AutoindentMode>,
  611    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  612    input_enabled: bool,
  613    use_modal_editing: bool,
  614    read_only: bool,
  615    leader_peer_id: Option<PeerId>,
  616    remote_id: Option<ViewId>,
  617    hover_state: HoverState,
  618    gutter_hovered: bool,
  619    hovered_link_state: Option<HoveredLinkState>,
  620    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  621    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  622    active_inline_completion: Option<CompletionState>,
  623    // enable_inline_completions is a switch that Vim can use to disable
  624    // inline completions based on its mode.
  625    enable_inline_completions: bool,
  626    show_inline_completions_override: Option<bool>,
  627    inlay_hint_cache: InlayHintCache,
  628    expanded_hunks: ExpandedHunks,
  629    next_inlay_id: usize,
  630    _subscriptions: Vec<Subscription>,
  631    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  632    gutter_dimensions: GutterDimensions,
  633    style: Option<EditorStyle>,
  634    text_style_refinement: Option<TextStyleRefinement>,
  635    next_editor_action_id: EditorActionId,
  636    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  637    use_autoclose: bool,
  638    use_auto_surround: bool,
  639    auto_replace_emoji_shortcode: bool,
  640    show_git_blame_gutter: bool,
  641    show_git_blame_inline: bool,
  642    show_git_blame_inline_delay_task: Option<Task<()>>,
  643    git_blame_inline_enabled: bool,
  644    serialize_dirty_buffers: bool,
  645    show_selection_menu: Option<bool>,
  646    blame: Option<Model<GitBlame>>,
  647    blame_subscription: Option<Subscription>,
  648    custom_context_menu: Option<
  649        Box<
  650            dyn 'static
  651                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  652        >,
  653    >,
  654    last_bounds: Option<Bounds<Pixels>>,
  655    expect_bounds_change: Option<Bounds<Pixels>>,
  656    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  657    tasks_update_task: Option<Task<()>>,
  658    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  659    breadcrumb_header: Option<String>,
  660    focused_block: Option<FocusedBlock>,
  661    next_scroll_position: NextScrollCursorCenterTopBottom,
  662    addons: HashMap<TypeId, Box<dyn Addon>>,
  663    _scroll_cursor_center_top_bottom_task: Task<()>,
  664}
  665
  666#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  667enum NextScrollCursorCenterTopBottom {
  668    #[default]
  669    Center,
  670    Top,
  671    Bottom,
  672}
  673
  674impl NextScrollCursorCenterTopBottom {
  675    fn next(&self) -> Self {
  676        match self {
  677            Self::Center => Self::Top,
  678            Self::Top => Self::Bottom,
  679            Self::Bottom => Self::Center,
  680        }
  681    }
  682}
  683
  684#[derive(Clone)]
  685pub struct EditorSnapshot {
  686    pub mode: EditorMode,
  687    show_gutter: bool,
  688    show_line_numbers: Option<bool>,
  689    show_git_diff_gutter: Option<bool>,
  690    show_code_actions: Option<bool>,
  691    show_runnables: Option<bool>,
  692    git_blame_gutter_max_author_length: Option<usize>,
  693    pub display_snapshot: DisplaySnapshot,
  694    pub placeholder_text: Option<Arc<str>>,
  695    is_focused: bool,
  696    scroll_anchor: ScrollAnchor,
  697    ongoing_scroll: OngoingScroll,
  698    current_line_highlight: CurrentLineHighlight,
  699    gutter_hovered: bool,
  700}
  701
  702const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  703
  704#[derive(Default, Debug, Clone, Copy)]
  705pub struct GutterDimensions {
  706    pub left_padding: Pixels,
  707    pub right_padding: Pixels,
  708    pub width: Pixels,
  709    pub margin: Pixels,
  710    pub git_blame_entries_width: Option<Pixels>,
  711}
  712
  713impl GutterDimensions {
  714    /// The full width of the space taken up by the gutter.
  715    pub fn full_width(&self) -> Pixels {
  716        self.margin + self.width
  717    }
  718
  719    /// The width of the space reserved for the fold indicators,
  720    /// use alongside 'justify_end' and `gutter_width` to
  721    /// right align content with the line numbers
  722    pub fn fold_area_width(&self) -> Pixels {
  723        self.margin + self.right_padding
  724    }
  725}
  726
  727#[derive(Debug)]
  728pub struct RemoteSelection {
  729    pub replica_id: ReplicaId,
  730    pub selection: Selection<Anchor>,
  731    pub cursor_shape: CursorShape,
  732    pub peer_id: PeerId,
  733    pub line_mode: bool,
  734    pub participant_index: Option<ParticipantIndex>,
  735    pub user_name: Option<SharedString>,
  736}
  737
  738#[derive(Clone, Debug)]
  739struct SelectionHistoryEntry {
  740    selections: Arc<[Selection<Anchor>]>,
  741    select_next_state: Option<SelectNextState>,
  742    select_prev_state: Option<SelectNextState>,
  743    add_selections_state: Option<AddSelectionsState>,
  744}
  745
  746enum SelectionHistoryMode {
  747    Normal,
  748    Undoing,
  749    Redoing,
  750}
  751
  752#[derive(Clone, PartialEq, Eq, Hash)]
  753struct HoveredCursor {
  754    replica_id: u16,
  755    selection_id: usize,
  756}
  757
  758impl Default for SelectionHistoryMode {
  759    fn default() -> Self {
  760        Self::Normal
  761    }
  762}
  763
  764#[derive(Default)]
  765struct SelectionHistory {
  766    #[allow(clippy::type_complexity)]
  767    selections_by_transaction:
  768        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  769    mode: SelectionHistoryMode,
  770    undo_stack: VecDeque<SelectionHistoryEntry>,
  771    redo_stack: VecDeque<SelectionHistoryEntry>,
  772}
  773
  774impl SelectionHistory {
  775    fn insert_transaction(
  776        &mut self,
  777        transaction_id: TransactionId,
  778        selections: Arc<[Selection<Anchor>]>,
  779    ) {
  780        self.selections_by_transaction
  781            .insert(transaction_id, (selections, None));
  782    }
  783
  784    #[allow(clippy::type_complexity)]
  785    fn transaction(
  786        &self,
  787        transaction_id: TransactionId,
  788    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  789        self.selections_by_transaction.get(&transaction_id)
  790    }
  791
  792    #[allow(clippy::type_complexity)]
  793    fn transaction_mut(
  794        &mut self,
  795        transaction_id: TransactionId,
  796    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  797        self.selections_by_transaction.get_mut(&transaction_id)
  798    }
  799
  800    fn push(&mut self, entry: SelectionHistoryEntry) {
  801        if !entry.selections.is_empty() {
  802            match self.mode {
  803                SelectionHistoryMode::Normal => {
  804                    self.push_undo(entry);
  805                    self.redo_stack.clear();
  806                }
  807                SelectionHistoryMode::Undoing => self.push_redo(entry),
  808                SelectionHistoryMode::Redoing => self.push_undo(entry),
  809            }
  810        }
  811    }
  812
  813    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  814        if self
  815            .undo_stack
  816            .back()
  817            .map_or(true, |e| e.selections != entry.selections)
  818        {
  819            self.undo_stack.push_back(entry);
  820            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  821                self.undo_stack.pop_front();
  822            }
  823        }
  824    }
  825
  826    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  827        if self
  828            .redo_stack
  829            .back()
  830            .map_or(true, |e| e.selections != entry.selections)
  831        {
  832            self.redo_stack.push_back(entry);
  833            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  834                self.redo_stack.pop_front();
  835            }
  836        }
  837    }
  838}
  839
  840struct RowHighlight {
  841    index: usize,
  842    range: Range<Anchor>,
  843    color: Hsla,
  844    should_autoscroll: bool,
  845}
  846
  847#[derive(Clone, Debug)]
  848struct AddSelectionsState {
  849    above: bool,
  850    stack: Vec<usize>,
  851}
  852
  853#[derive(Clone)]
  854struct SelectNextState {
  855    query: AhoCorasick,
  856    wordwise: bool,
  857    done: bool,
  858}
  859
  860impl std::fmt::Debug for SelectNextState {
  861    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  862        f.debug_struct(std::any::type_name::<Self>())
  863            .field("wordwise", &self.wordwise)
  864            .field("done", &self.done)
  865            .finish()
  866    }
  867}
  868
  869#[derive(Debug)]
  870struct AutocloseRegion {
  871    selection_id: usize,
  872    range: Range<Anchor>,
  873    pair: BracketPair,
  874}
  875
  876#[derive(Debug)]
  877struct SnippetState {
  878    ranges: Vec<Vec<Range<Anchor>>>,
  879    active_index: usize,
  880}
  881
  882#[doc(hidden)]
  883pub struct RenameState {
  884    pub range: Range<Anchor>,
  885    pub old_name: Arc<str>,
  886    pub editor: View<Editor>,
  887    block_id: CustomBlockId,
  888}
  889
  890struct InvalidationStack<T>(Vec<T>);
  891
  892struct RegisteredInlineCompletionProvider {
  893    provider: Arc<dyn InlineCompletionProviderHandle>,
  894    _subscription: Subscription,
  895}
  896
  897enum ContextMenu {
  898    Completions(CompletionsMenu),
  899    CodeActions(CodeActionsMenu),
  900}
  901
  902impl ContextMenu {
  903    fn select_first(
  904        &mut self,
  905        provider: Option<&dyn CompletionProvider>,
  906        cx: &mut ViewContext<Editor>,
  907    ) -> bool {
  908        if self.visible() {
  909            match self {
  910                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  911                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  912            }
  913            true
  914        } else {
  915            false
  916        }
  917    }
  918
  919    fn select_prev(
  920        &mut self,
  921        provider: Option<&dyn CompletionProvider>,
  922        cx: &mut ViewContext<Editor>,
  923    ) -> bool {
  924        if self.visible() {
  925            match self {
  926                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  927                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  928            }
  929            true
  930        } else {
  931            false
  932        }
  933    }
  934
  935    fn select_next(
  936        &mut self,
  937        provider: Option<&dyn CompletionProvider>,
  938        cx: &mut ViewContext<Editor>,
  939    ) -> bool {
  940        if self.visible() {
  941            match self {
  942                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  943                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  944            }
  945            true
  946        } else {
  947            false
  948        }
  949    }
  950
  951    fn select_last(
  952        &mut self,
  953        provider: Option<&dyn CompletionProvider>,
  954        cx: &mut ViewContext<Editor>,
  955    ) -> bool {
  956        if self.visible() {
  957            match self {
  958                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  959                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  960            }
  961            true
  962        } else {
  963            false
  964        }
  965    }
  966
  967    fn visible(&self) -> bool {
  968        match self {
  969            ContextMenu::Completions(menu) => menu.visible(),
  970            ContextMenu::CodeActions(menu) => menu.visible(),
  971        }
  972    }
  973
  974    fn render(
  975        &self,
  976        cursor_position: DisplayPoint,
  977        style: &EditorStyle,
  978        max_height: Pixels,
  979        workspace: Option<WeakView<Workspace>>,
  980        cx: &mut ViewContext<Editor>,
  981    ) -> (ContextMenuOrigin, AnyElement) {
  982        match self {
  983            ContextMenu::Completions(menu) => (
  984                ContextMenuOrigin::EditorPoint(cursor_position),
  985                menu.render(style, max_height, workspace, cx),
  986            ),
  987            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  988        }
  989    }
  990}
  991
  992enum ContextMenuOrigin {
  993    EditorPoint(DisplayPoint),
  994    GutterIndicator(DisplayRow),
  995}
  996
  997#[derive(Clone)]
  998struct CompletionsMenu {
  999    id: CompletionId,
 1000    sort_completions: bool,
 1001    initial_position: Anchor,
 1002    buffer: Model<Buffer>,
 1003    completions: Arc<RwLock<Box<[Completion]>>>,
 1004    match_candidates: Arc<[StringMatchCandidate]>,
 1005    matches: Arc<[StringMatch]>,
 1006    selected_item: usize,
 1007    scroll_handle: UniformListScrollHandle,
 1008    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
 1009}
 1010
 1011impl CompletionsMenu {
 1012    fn select_first(
 1013        &mut self,
 1014        provider: Option<&dyn CompletionProvider>,
 1015        cx: &mut ViewContext<Editor>,
 1016    ) {
 1017        self.selected_item = 0;
 1018        self.scroll_handle
 1019            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1020        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1021        cx.notify();
 1022    }
 1023
 1024    fn select_prev(
 1025        &mut self,
 1026        provider: Option<&dyn CompletionProvider>,
 1027        cx: &mut ViewContext<Editor>,
 1028    ) {
 1029        if self.selected_item > 0 {
 1030            self.selected_item -= 1;
 1031        } else {
 1032            self.selected_item = self.matches.len() - 1;
 1033        }
 1034        self.scroll_handle
 1035            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1036        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1037        cx.notify();
 1038    }
 1039
 1040    fn select_next(
 1041        &mut self,
 1042        provider: Option<&dyn CompletionProvider>,
 1043        cx: &mut ViewContext<Editor>,
 1044    ) {
 1045        if self.selected_item + 1 < self.matches.len() {
 1046            self.selected_item += 1;
 1047        } else {
 1048            self.selected_item = 0;
 1049        }
 1050        self.scroll_handle
 1051            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1052        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1053        cx.notify();
 1054    }
 1055
 1056    fn select_last(
 1057        &mut self,
 1058        provider: Option<&dyn CompletionProvider>,
 1059        cx: &mut ViewContext<Editor>,
 1060    ) {
 1061        self.selected_item = self.matches.len() - 1;
 1062        self.scroll_handle
 1063            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1064        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1065        cx.notify();
 1066    }
 1067
 1068    fn pre_resolve_completion_documentation(
 1069        buffer: Model<Buffer>,
 1070        completions: Arc<RwLock<Box<[Completion]>>>,
 1071        matches: Arc<[StringMatch]>,
 1072        editor: &Editor,
 1073        cx: &mut ViewContext<Editor>,
 1074    ) -> Task<()> {
 1075        let settings = EditorSettings::get_global(cx);
 1076        if !settings.show_completion_documentation {
 1077            return Task::ready(());
 1078        }
 1079
 1080        let Some(provider) = editor.completion_provider.as_ref() else {
 1081            return Task::ready(());
 1082        };
 1083
 1084        let resolve_task = provider.resolve_completions(
 1085            buffer,
 1086            matches.iter().map(|m| m.candidate_id).collect(),
 1087            completions.clone(),
 1088            cx,
 1089        );
 1090
 1091        cx.spawn(move |this, mut cx| async move {
 1092            if let Some(true) = resolve_task.await.log_err() {
 1093                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1094            }
 1095        })
 1096    }
 1097
 1098    fn attempt_resolve_selected_completion_documentation(
 1099        &mut self,
 1100        provider: Option<&dyn CompletionProvider>,
 1101        cx: &mut ViewContext<Editor>,
 1102    ) {
 1103        let settings = EditorSettings::get_global(cx);
 1104        if !settings.show_completion_documentation {
 1105            return;
 1106        }
 1107
 1108        let completion_index = self.matches[self.selected_item].candidate_id;
 1109        let Some(provider) = provider else {
 1110            return;
 1111        };
 1112
 1113        let resolve_task = provider.resolve_completions(
 1114            self.buffer.clone(),
 1115            vec![completion_index],
 1116            self.completions.clone(),
 1117            cx,
 1118        );
 1119
 1120        let delay_ms =
 1121            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1122        let delay = Duration::from_millis(delay_ms);
 1123
 1124        self.selected_completion_documentation_resolve_debounce
 1125            .lock()
 1126            .fire_new(delay, cx, |_, cx| {
 1127                cx.spawn(move |this, mut cx| async move {
 1128                    if let Some(true) = resolve_task.await.log_err() {
 1129                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1130                    }
 1131                })
 1132            });
 1133    }
 1134
 1135    fn visible(&self) -> bool {
 1136        !self.matches.is_empty()
 1137    }
 1138
 1139    fn render(
 1140        &self,
 1141        style: &EditorStyle,
 1142        max_height: Pixels,
 1143        workspace: Option<WeakView<Workspace>>,
 1144        cx: &mut ViewContext<Editor>,
 1145    ) -> AnyElement {
 1146        let settings = EditorSettings::get_global(cx);
 1147        let show_completion_documentation = settings.show_completion_documentation;
 1148
 1149        let widest_completion_ix = self
 1150            .matches
 1151            .iter()
 1152            .enumerate()
 1153            .max_by_key(|(_, mat)| {
 1154                let completions = self.completions.read();
 1155                let completion = &completions[mat.candidate_id];
 1156                let documentation = &completion.documentation;
 1157
 1158                let mut len = completion.label.text.chars().count();
 1159                if let Some(Documentation::SingleLine(text)) = documentation {
 1160                    if show_completion_documentation {
 1161                        len += text.chars().count();
 1162                    }
 1163                }
 1164
 1165                len
 1166            })
 1167            .map(|(ix, _)| ix);
 1168
 1169        let completions = self.completions.clone();
 1170        let matches = self.matches.clone();
 1171        let selected_item = self.selected_item;
 1172        let style = style.clone();
 1173
 1174        let multiline_docs = if show_completion_documentation {
 1175            let mat = &self.matches[selected_item];
 1176            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1177                Some(Documentation::MultiLinePlainText(text)) => {
 1178                    Some(div().child(SharedString::from(text.clone())))
 1179                }
 1180                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1181                    Some(div().child(render_parsed_markdown(
 1182                        "completions_markdown",
 1183                        parsed,
 1184                        &style,
 1185                        workspace,
 1186                        cx,
 1187                    )))
 1188                }
 1189                _ => None,
 1190            };
 1191            multiline_docs.map(|div| {
 1192                div.id("multiline_docs")
 1193                    .max_h(max_height)
 1194                    .flex_1()
 1195                    .px_1p5()
 1196                    .py_1()
 1197                    .min_w(px(260.))
 1198                    .max_w(px(640.))
 1199                    .w(px(500.))
 1200                    .overflow_y_scroll()
 1201                    .occlude()
 1202            })
 1203        } else {
 1204            None
 1205        };
 1206
 1207        let list = uniform_list(
 1208            cx.view().clone(),
 1209            "completions",
 1210            matches.len(),
 1211            move |_editor, range, cx| {
 1212                let start_ix = range.start;
 1213                let completions_guard = completions.read();
 1214
 1215                matches[range]
 1216                    .iter()
 1217                    .enumerate()
 1218                    .map(|(ix, mat)| {
 1219                        let item_ix = start_ix + ix;
 1220                        let candidate_id = mat.candidate_id;
 1221                        let completion = &completions_guard[candidate_id];
 1222
 1223                        let documentation = if show_completion_documentation {
 1224                            &completion.documentation
 1225                        } else {
 1226                            &None
 1227                        };
 1228
 1229                        let highlights = gpui::combine_highlights(
 1230                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1231                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1232                                |(range, mut highlight)| {
 1233                                    // Ignore font weight for syntax highlighting, as we'll use it
 1234                                    // for fuzzy matches.
 1235                                    highlight.font_weight = None;
 1236
 1237                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1238                                        highlight.strikethrough = Some(StrikethroughStyle {
 1239                                            thickness: 1.0.into(),
 1240                                            ..Default::default()
 1241                                        });
 1242                                        highlight.color = Some(cx.theme().colors().text_muted);
 1243                                    }
 1244
 1245                                    (range, highlight)
 1246                                },
 1247                            ),
 1248                        );
 1249                        let completion_label = StyledText::new(completion.label.text.clone())
 1250                            .with_highlights(&style.text, highlights);
 1251                        let documentation_label =
 1252                            if let Some(Documentation::SingleLine(text)) = documentation {
 1253                                if text.trim().is_empty() {
 1254                                    None
 1255                                } else {
 1256                                    Some(
 1257                                        Label::new(text.clone())
 1258                                            .ml_4()
 1259                                            .size(LabelSize::Small)
 1260                                            .color(Color::Muted),
 1261                                    )
 1262                                }
 1263                            } else {
 1264                                None
 1265                            };
 1266
 1267                        let color_swatch = completion
 1268                            .color()
 1269                            .map(|color| div().size_4().bg(color).rounded_sm());
 1270
 1271                        div().min_w(px(220.)).max_w(px(540.)).child(
 1272                            ListItem::new(mat.candidate_id)
 1273                                .inset(true)
 1274                                .selected(item_ix == selected_item)
 1275                                .on_click(cx.listener(move |editor, _event, cx| {
 1276                                    cx.stop_propagation();
 1277                                    if let Some(task) = editor.confirm_completion(
 1278                                        &ConfirmCompletion {
 1279                                            item_ix: Some(item_ix),
 1280                                        },
 1281                                        cx,
 1282                                    ) {
 1283                                        task.detach_and_log_err(cx)
 1284                                    }
 1285                                }))
 1286                                .start_slot::<Div>(color_swatch)
 1287                                .child(h_flex().overflow_hidden().child(completion_label))
 1288                                .end_slot::<Label>(documentation_label),
 1289                        )
 1290                    })
 1291                    .collect()
 1292            },
 1293        )
 1294        .occlude()
 1295        .max_h(max_height)
 1296        .track_scroll(self.scroll_handle.clone())
 1297        .with_width_from_item(widest_completion_ix)
 1298        .with_sizing_behavior(ListSizingBehavior::Infer);
 1299
 1300        Popover::new()
 1301            .child(list)
 1302            .when_some(multiline_docs, |popover, multiline_docs| {
 1303                popover.aside(multiline_docs)
 1304            })
 1305            .into_any_element()
 1306    }
 1307
 1308    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1309        let mut matches = if let Some(query) = query {
 1310            fuzzy::match_strings(
 1311                &self.match_candidates,
 1312                query,
 1313                query.chars().any(|c| c.is_uppercase()),
 1314                100,
 1315                &Default::default(),
 1316                executor,
 1317            )
 1318            .await
 1319        } else {
 1320            self.match_candidates
 1321                .iter()
 1322                .enumerate()
 1323                .map(|(candidate_id, candidate)| StringMatch {
 1324                    candidate_id,
 1325                    score: Default::default(),
 1326                    positions: Default::default(),
 1327                    string: candidate.string.clone(),
 1328                })
 1329                .collect()
 1330        };
 1331
 1332        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1333        if let Some(query) = query {
 1334            if let Some(query_start) = query.chars().next() {
 1335                matches.retain(|string_match| {
 1336                    split_words(&string_match.string).any(|word| {
 1337                        // Check that the first codepoint of the word as lowercase matches the first
 1338                        // codepoint of the query as lowercase
 1339                        word.chars()
 1340                            .flat_map(|codepoint| codepoint.to_lowercase())
 1341                            .zip(query_start.to_lowercase())
 1342                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1343                    })
 1344                });
 1345            }
 1346        }
 1347
 1348        let completions = self.completions.read();
 1349        if self.sort_completions {
 1350            matches.sort_unstable_by_key(|mat| {
 1351                // We do want to strike a balance here between what the language server tells us
 1352                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1353                // `Creat` and there is a local variable called `CreateComponent`).
 1354                // So what we do is: we bucket all matches into two buckets
 1355                // - Strong matches
 1356                // - Weak matches
 1357                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1358                // and the Weak matches are the rest.
 1359                //
 1360                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1361                // matches, we prefer language-server sort_text first.
 1362                //
 1363                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1364                // Rest of the matches(weak) can be sorted as language-server expects.
 1365
 1366                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1367                enum MatchScore<'a> {
 1368                    Strong {
 1369                        score: Reverse<OrderedFloat<f64>>,
 1370                        sort_text: Option<&'a str>,
 1371                        sort_key: (usize, &'a str),
 1372                    },
 1373                    Weak {
 1374                        sort_text: Option<&'a str>,
 1375                        score: Reverse<OrderedFloat<f64>>,
 1376                        sort_key: (usize, &'a str),
 1377                    },
 1378                }
 1379
 1380                let completion = &completions[mat.candidate_id];
 1381                let sort_key = completion.sort_key();
 1382                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1383                let score = Reverse(OrderedFloat(mat.score));
 1384
 1385                if mat.score >= 0.2 {
 1386                    MatchScore::Strong {
 1387                        score,
 1388                        sort_text,
 1389                        sort_key,
 1390                    }
 1391                } else {
 1392                    MatchScore::Weak {
 1393                        sort_text,
 1394                        score,
 1395                        sort_key,
 1396                    }
 1397                }
 1398            });
 1399        }
 1400
 1401        for mat in &mut matches {
 1402            let completion = &completions[mat.candidate_id];
 1403            mat.string.clone_from(&completion.label.text);
 1404            for position in &mut mat.positions {
 1405                *position += completion.label.filter_range.start;
 1406            }
 1407        }
 1408        drop(completions);
 1409
 1410        self.matches = matches.into();
 1411        self.selected_item = 0;
 1412    }
 1413}
 1414
 1415struct AvailableCodeAction {
 1416    excerpt_id: ExcerptId,
 1417    action: CodeAction,
 1418    provider: Arc<dyn CodeActionProvider>,
 1419}
 1420
 1421#[derive(Clone)]
 1422struct CodeActionContents {
 1423    tasks: Option<Arc<ResolvedTasks>>,
 1424    actions: Option<Arc<[AvailableCodeAction]>>,
 1425}
 1426
 1427impl CodeActionContents {
 1428    fn len(&self) -> usize {
 1429        match (&self.tasks, &self.actions) {
 1430            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1431            (Some(tasks), None) => tasks.templates.len(),
 1432            (None, Some(actions)) => actions.len(),
 1433            (None, None) => 0,
 1434        }
 1435    }
 1436
 1437    fn is_empty(&self) -> bool {
 1438        match (&self.tasks, &self.actions) {
 1439            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1440            (Some(tasks), None) => tasks.templates.is_empty(),
 1441            (None, Some(actions)) => actions.is_empty(),
 1442            (None, None) => true,
 1443        }
 1444    }
 1445
 1446    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1447        self.tasks
 1448            .iter()
 1449            .flat_map(|tasks| {
 1450                tasks
 1451                    .templates
 1452                    .iter()
 1453                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1454            })
 1455            .chain(self.actions.iter().flat_map(|actions| {
 1456                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1457                    excerpt_id: available.excerpt_id,
 1458                    action: available.action.clone(),
 1459                    provider: available.provider.clone(),
 1460                })
 1461            }))
 1462    }
 1463    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1464        match (&self.tasks, &self.actions) {
 1465            (Some(tasks), Some(actions)) => {
 1466                if index < tasks.templates.len() {
 1467                    tasks
 1468                        .templates
 1469                        .get(index)
 1470                        .cloned()
 1471                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1472                } else {
 1473                    actions.get(index - tasks.templates.len()).map(|available| {
 1474                        CodeActionsItem::CodeAction {
 1475                            excerpt_id: available.excerpt_id,
 1476                            action: available.action.clone(),
 1477                            provider: available.provider.clone(),
 1478                        }
 1479                    })
 1480                }
 1481            }
 1482            (Some(tasks), None) => tasks
 1483                .templates
 1484                .get(index)
 1485                .cloned()
 1486                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1487            (None, Some(actions)) => {
 1488                actions
 1489                    .get(index)
 1490                    .map(|available| CodeActionsItem::CodeAction {
 1491                        excerpt_id: available.excerpt_id,
 1492                        action: available.action.clone(),
 1493                        provider: available.provider.clone(),
 1494                    })
 1495            }
 1496            (None, None) => None,
 1497        }
 1498    }
 1499}
 1500
 1501#[allow(clippy::large_enum_variant)]
 1502#[derive(Clone)]
 1503enum CodeActionsItem {
 1504    Task(TaskSourceKind, ResolvedTask),
 1505    CodeAction {
 1506        excerpt_id: ExcerptId,
 1507        action: CodeAction,
 1508        provider: Arc<dyn CodeActionProvider>,
 1509    },
 1510}
 1511
 1512impl CodeActionsItem {
 1513    fn as_task(&self) -> Option<&ResolvedTask> {
 1514        let Self::Task(_, task) = self else {
 1515            return None;
 1516        };
 1517        Some(task)
 1518    }
 1519    fn as_code_action(&self) -> Option<&CodeAction> {
 1520        let Self::CodeAction { action, .. } = self else {
 1521            return None;
 1522        };
 1523        Some(action)
 1524    }
 1525    fn label(&self) -> String {
 1526        match self {
 1527            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1528            Self::Task(_, task) => task.resolved_label.clone(),
 1529        }
 1530    }
 1531}
 1532
 1533struct CodeActionsMenu {
 1534    actions: CodeActionContents,
 1535    buffer: Model<Buffer>,
 1536    selected_item: usize,
 1537    scroll_handle: UniformListScrollHandle,
 1538    deployed_from_indicator: Option<DisplayRow>,
 1539}
 1540
 1541impl CodeActionsMenu {
 1542    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1543        self.selected_item = 0;
 1544        self.scroll_handle
 1545            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1546        cx.notify()
 1547    }
 1548
 1549    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1550        if self.selected_item > 0 {
 1551            self.selected_item -= 1;
 1552        } else {
 1553            self.selected_item = self.actions.len() - 1;
 1554        }
 1555        self.scroll_handle
 1556            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1557        cx.notify();
 1558    }
 1559
 1560    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1561        if self.selected_item + 1 < self.actions.len() {
 1562            self.selected_item += 1;
 1563        } else {
 1564            self.selected_item = 0;
 1565        }
 1566        self.scroll_handle
 1567            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1568        cx.notify();
 1569    }
 1570
 1571    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1572        self.selected_item = self.actions.len() - 1;
 1573        self.scroll_handle
 1574            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1575        cx.notify()
 1576    }
 1577
 1578    fn visible(&self) -> bool {
 1579        !self.actions.is_empty()
 1580    }
 1581
 1582    fn render(
 1583        &self,
 1584        cursor_position: DisplayPoint,
 1585        _style: &EditorStyle,
 1586        max_height: Pixels,
 1587        cx: &mut ViewContext<Editor>,
 1588    ) -> (ContextMenuOrigin, AnyElement) {
 1589        let actions = self.actions.clone();
 1590        let selected_item = self.selected_item;
 1591        let element = uniform_list(
 1592            cx.view().clone(),
 1593            "code_actions_menu",
 1594            self.actions.len(),
 1595            move |_this, range, cx| {
 1596                actions
 1597                    .iter()
 1598                    .skip(range.start)
 1599                    .take(range.end - range.start)
 1600                    .enumerate()
 1601                    .map(|(ix, action)| {
 1602                        let item_ix = range.start + ix;
 1603                        let selected = selected_item == item_ix;
 1604                        let colors = cx.theme().colors();
 1605                        div()
 1606                            .px_1()
 1607                            .rounded_md()
 1608                            .text_color(colors.text)
 1609                            .when(selected, |style| {
 1610                                style
 1611                                    .bg(colors.element_active)
 1612                                    .text_color(colors.text_accent)
 1613                            })
 1614                            .hover(|style| {
 1615                                style
 1616                                    .bg(colors.element_hover)
 1617                                    .text_color(colors.text_accent)
 1618                            })
 1619                            .whitespace_nowrap()
 1620                            .when_some(action.as_code_action(), |this, action| {
 1621                                this.on_mouse_down(
 1622                                    MouseButton::Left,
 1623                                    cx.listener(move |editor, _, cx| {
 1624                                        cx.stop_propagation();
 1625                                        if let Some(task) = editor.confirm_code_action(
 1626                                            &ConfirmCodeAction {
 1627                                                item_ix: Some(item_ix),
 1628                                            },
 1629                                            cx,
 1630                                        ) {
 1631                                            task.detach_and_log_err(cx)
 1632                                        }
 1633                                    }),
 1634                                )
 1635                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1636                                .child(SharedString::from(action.lsp_action.title.clone()))
 1637                            })
 1638                            .when_some(action.as_task(), |this, task| {
 1639                                this.on_mouse_down(
 1640                                    MouseButton::Left,
 1641                                    cx.listener(move |editor, _, cx| {
 1642                                        cx.stop_propagation();
 1643                                        if let Some(task) = editor.confirm_code_action(
 1644                                            &ConfirmCodeAction {
 1645                                                item_ix: Some(item_ix),
 1646                                            },
 1647                                            cx,
 1648                                        ) {
 1649                                            task.detach_and_log_err(cx)
 1650                                        }
 1651                                    }),
 1652                                )
 1653                                .child(SharedString::from(task.resolved_label.clone()))
 1654                            })
 1655                    })
 1656                    .collect()
 1657            },
 1658        )
 1659        .elevation_1(cx)
 1660        .p_1()
 1661        .max_h(max_height)
 1662        .occlude()
 1663        .track_scroll(self.scroll_handle.clone())
 1664        .with_width_from_item(
 1665            self.actions
 1666                .iter()
 1667                .enumerate()
 1668                .max_by_key(|(_, action)| match action {
 1669                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1670                    CodeActionsItem::CodeAction { action, .. } => {
 1671                        action.lsp_action.title.chars().count()
 1672                    }
 1673                })
 1674                .map(|(ix, _)| ix),
 1675        )
 1676        .with_sizing_behavior(ListSizingBehavior::Infer)
 1677        .into_any_element();
 1678
 1679        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1680            ContextMenuOrigin::GutterIndicator(row)
 1681        } else {
 1682            ContextMenuOrigin::EditorPoint(cursor_position)
 1683        };
 1684
 1685        (cursor_position, element)
 1686    }
 1687}
 1688
 1689#[derive(Debug)]
 1690struct ActiveDiagnosticGroup {
 1691    primary_range: Range<Anchor>,
 1692    primary_message: String,
 1693    group_id: usize,
 1694    blocks: HashMap<CustomBlockId, Diagnostic>,
 1695    is_valid: bool,
 1696}
 1697
 1698#[derive(Serialize, Deserialize, Clone, Debug)]
 1699pub struct ClipboardSelection {
 1700    pub len: usize,
 1701    pub is_entire_line: bool,
 1702    pub first_line_indent: u32,
 1703}
 1704
 1705#[derive(Debug)]
 1706pub(crate) struct NavigationData {
 1707    cursor_anchor: Anchor,
 1708    cursor_position: Point,
 1709    scroll_anchor: ScrollAnchor,
 1710    scroll_top_row: u32,
 1711}
 1712
 1713#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1714pub enum GotoDefinitionKind {
 1715    Symbol,
 1716    Declaration,
 1717    Type,
 1718    Implementation,
 1719}
 1720
 1721#[derive(Debug, Clone)]
 1722enum InlayHintRefreshReason {
 1723    Toggle(bool),
 1724    SettingsChange(InlayHintSettings),
 1725    NewLinesShown,
 1726    BufferEdited(HashSet<Arc<Language>>),
 1727    RefreshRequested,
 1728    ExcerptsRemoved(Vec<ExcerptId>),
 1729}
 1730
 1731impl InlayHintRefreshReason {
 1732    fn description(&self) -> &'static str {
 1733        match self {
 1734            Self::Toggle(_) => "toggle",
 1735            Self::SettingsChange(_) => "settings change",
 1736            Self::NewLinesShown => "new lines shown",
 1737            Self::BufferEdited(_) => "buffer edited",
 1738            Self::RefreshRequested => "refresh requested",
 1739            Self::ExcerptsRemoved(_) => "excerpts removed",
 1740        }
 1741    }
 1742}
 1743
 1744pub(crate) struct FocusedBlock {
 1745    id: BlockId,
 1746    focus_handle: WeakFocusHandle,
 1747}
 1748
 1749#[derive(Clone)]
 1750struct JumpData {
 1751    excerpt_id: ExcerptId,
 1752    position: Point,
 1753    anchor: text::Anchor,
 1754    path: Option<project::ProjectPath>,
 1755    line_offset_from_top: u32,
 1756}
 1757
 1758impl Editor {
 1759    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1760        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1761        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1762        Self::new(
 1763            EditorMode::SingleLine { auto_width: false },
 1764            buffer,
 1765            None,
 1766            false,
 1767            cx,
 1768        )
 1769    }
 1770
 1771    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1772        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1773        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1774        Self::new(EditorMode::Full, buffer, None, false, cx)
 1775    }
 1776
 1777    pub fn auto_width(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(
 1781            EditorMode::SingleLine { auto_width: true },
 1782            buffer,
 1783            None,
 1784            false,
 1785            cx,
 1786        )
 1787    }
 1788
 1789    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1790        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1791        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1792        Self::new(
 1793            EditorMode::AutoHeight { max_lines },
 1794            buffer,
 1795            None,
 1796            false,
 1797            cx,
 1798        )
 1799    }
 1800
 1801    pub fn for_buffer(
 1802        buffer: Model<Buffer>,
 1803        project: Option<Model<Project>>,
 1804        cx: &mut ViewContext<Self>,
 1805    ) -> Self {
 1806        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1807        Self::new(EditorMode::Full, buffer, project, false, cx)
 1808    }
 1809
 1810    pub fn for_multibuffer(
 1811        buffer: Model<MultiBuffer>,
 1812        project: Option<Model<Project>>,
 1813        show_excerpt_controls: bool,
 1814        cx: &mut ViewContext<Self>,
 1815    ) -> Self {
 1816        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1817    }
 1818
 1819    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1820        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1821        let mut clone = Self::new(
 1822            self.mode,
 1823            self.buffer.clone(),
 1824            self.project.clone(),
 1825            show_excerpt_controls,
 1826            cx,
 1827        );
 1828        self.display_map.update(cx, |display_map, cx| {
 1829            let snapshot = display_map.snapshot(cx);
 1830            clone.display_map.update(cx, |display_map, cx| {
 1831                display_map.set_state(&snapshot, cx);
 1832            });
 1833        });
 1834        clone.selections.clone_state(&self.selections);
 1835        clone.scroll_manager.clone_state(&self.scroll_manager);
 1836        clone.searchable = self.searchable;
 1837        clone
 1838    }
 1839
 1840    pub fn new(
 1841        mode: EditorMode,
 1842        buffer: Model<MultiBuffer>,
 1843        project: Option<Model<Project>>,
 1844        show_excerpt_controls: bool,
 1845        cx: &mut ViewContext<Self>,
 1846    ) -> Self {
 1847        let style = cx.text_style();
 1848        let font_size = style.font_size.to_pixels(cx.rem_size());
 1849        let editor = cx.view().downgrade();
 1850        let fold_placeholder = FoldPlaceholder {
 1851            constrain_width: true,
 1852            render: Arc::new(move |fold_id, fold_range, cx| {
 1853                let editor = editor.clone();
 1854                div()
 1855                    .id(fold_id)
 1856                    .bg(cx.theme().colors().ghost_element_background)
 1857                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1858                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1859                    .rounded_sm()
 1860                    .size_full()
 1861                    .cursor_pointer()
 1862                    .child("")
 1863                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1864                    .on_click(move |_, cx| {
 1865                        editor
 1866                            .update(cx, |editor, cx| {
 1867                                editor.unfold_ranges(
 1868                                    &[fold_range.start..fold_range.end],
 1869                                    true,
 1870                                    false,
 1871                                    cx,
 1872                                );
 1873                                cx.stop_propagation();
 1874                            })
 1875                            .ok();
 1876                    })
 1877                    .into_any()
 1878            }),
 1879            merge_adjacent: true,
 1880            ..Default::default()
 1881        };
 1882        let display_map = cx.new_model(|cx| {
 1883            DisplayMap::new(
 1884                buffer.clone(),
 1885                style.font(),
 1886                font_size,
 1887                None,
 1888                show_excerpt_controls,
 1889                FILE_HEADER_HEIGHT,
 1890                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1891                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1892                fold_placeholder,
 1893                cx,
 1894            )
 1895        });
 1896
 1897        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1898
 1899        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1900
 1901        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1902            .then(|| language_settings::SoftWrap::None);
 1903
 1904        let mut project_subscriptions = Vec::new();
 1905        if mode == EditorMode::Full {
 1906            if let Some(project) = project.as_ref() {
 1907                if buffer.read(cx).is_singleton() {
 1908                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1909                        cx.emit(EditorEvent::TitleChanged);
 1910                    }));
 1911                }
 1912                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1913                    if let project::Event::RefreshInlayHints = event {
 1914                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1915                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1916                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1917                            let focus_handle = editor.focus_handle(cx);
 1918                            if focus_handle.is_focused(cx) {
 1919                                let snapshot = buffer.read(cx).snapshot();
 1920                                for (range, snippet) in snippet_edits {
 1921                                    let editor_range =
 1922                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1923                                    editor
 1924                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1925                                        .ok();
 1926                                }
 1927                            }
 1928                        }
 1929                    }
 1930                }));
 1931                if let Some(task_inventory) = project
 1932                    .read(cx)
 1933                    .task_store()
 1934                    .read(cx)
 1935                    .task_inventory()
 1936                    .cloned()
 1937                {
 1938                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1939                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1940                    }));
 1941                }
 1942            }
 1943        }
 1944
 1945        let inlay_hint_settings = inlay_hint_settings(
 1946            selections.newest_anchor().head(),
 1947            &buffer.read(cx).snapshot(cx),
 1948            cx,
 1949        );
 1950        let focus_handle = cx.focus_handle();
 1951        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1952        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1953            .detach();
 1954        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1955            .detach();
 1956        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1957
 1958        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1959            Some(false)
 1960        } else {
 1961            None
 1962        };
 1963
 1964        let mut code_action_providers = Vec::new();
 1965        if let Some(project) = project.clone() {
 1966            code_action_providers.push(Arc::new(project) as Arc<_>);
 1967        }
 1968
 1969        let mut this = Self {
 1970            focus_handle,
 1971            show_cursor_when_unfocused: false,
 1972            last_focused_descendant: None,
 1973            buffer: buffer.clone(),
 1974            display_map: display_map.clone(),
 1975            selections,
 1976            scroll_manager: ScrollManager::new(cx),
 1977            columnar_selection_tail: None,
 1978            add_selections_state: None,
 1979            select_next_state: None,
 1980            select_prev_state: None,
 1981            selection_history: Default::default(),
 1982            autoclose_regions: Default::default(),
 1983            snippet_stack: Default::default(),
 1984            select_larger_syntax_node_stack: Vec::new(),
 1985            ime_transaction: Default::default(),
 1986            active_diagnostics: None,
 1987            soft_wrap_mode_override,
 1988            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1989            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1990            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1991            project,
 1992            blink_manager: blink_manager.clone(),
 1993            show_local_selections: true,
 1994            mode,
 1995            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1996            show_gutter: mode == EditorMode::Full,
 1997            show_line_numbers: None,
 1998            use_relative_line_numbers: None,
 1999            show_git_diff_gutter: None,
 2000            show_code_actions: None,
 2001            show_runnables: None,
 2002            show_wrap_guides: None,
 2003            show_indent_guides,
 2004            placeholder_text: None,
 2005            highlight_order: 0,
 2006            highlighted_rows: HashMap::default(),
 2007            background_highlights: Default::default(),
 2008            gutter_highlights: TreeMap::default(),
 2009            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2010            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2011            nav_history: None,
 2012            context_menu: RwLock::new(None),
 2013            mouse_context_menu: None,
 2014            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2015            completion_tasks: Default::default(),
 2016            signature_help_state: SignatureHelpState::default(),
 2017            auto_signature_help: None,
 2018            find_all_references_task_sources: Vec::new(),
 2019            next_completion_id: 0,
 2020            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2021            next_inlay_id: 0,
 2022            code_action_providers,
 2023            available_code_actions: Default::default(),
 2024            code_actions_task: Default::default(),
 2025            document_highlights_task: Default::default(),
 2026            linked_editing_range_task: Default::default(),
 2027            pending_rename: Default::default(),
 2028            searchable: true,
 2029            cursor_shape: EditorSettings::get_global(cx)
 2030                .cursor_shape
 2031                .unwrap_or_default(),
 2032            current_line_highlight: None,
 2033            autoindent_mode: Some(AutoindentMode::EachLine),
 2034            collapse_matches: false,
 2035            workspace: None,
 2036            input_enabled: true,
 2037            use_modal_editing: mode == EditorMode::Full,
 2038            read_only: false,
 2039            use_autoclose: true,
 2040            use_auto_surround: true,
 2041            auto_replace_emoji_shortcode: false,
 2042            leader_peer_id: None,
 2043            remote_id: None,
 2044            hover_state: Default::default(),
 2045            hovered_link_state: Default::default(),
 2046            inline_completion_provider: None,
 2047            active_inline_completion: None,
 2048            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2049            expanded_hunks: ExpandedHunks::default(),
 2050            gutter_hovered: false,
 2051            pixel_position_of_newest_cursor: None,
 2052            last_bounds: None,
 2053            expect_bounds_change: None,
 2054            gutter_dimensions: GutterDimensions::default(),
 2055            style: None,
 2056            show_cursor_names: false,
 2057            hovered_cursors: Default::default(),
 2058            next_editor_action_id: EditorActionId::default(),
 2059            editor_actions: Rc::default(),
 2060            show_inline_completions_override: None,
 2061            enable_inline_completions: true,
 2062            custom_context_menu: None,
 2063            show_git_blame_gutter: false,
 2064            show_git_blame_inline: false,
 2065            show_selection_menu: None,
 2066            show_git_blame_inline_delay_task: None,
 2067            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2068            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2069                .session
 2070                .restore_unsaved_buffers,
 2071            blame: None,
 2072            blame_subscription: None,
 2073            tasks: Default::default(),
 2074            _subscriptions: vec![
 2075                cx.observe(&buffer, Self::on_buffer_changed),
 2076                cx.subscribe(&buffer, Self::on_buffer_event),
 2077                cx.observe(&display_map, Self::on_display_map_changed),
 2078                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2079                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2080                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2081                cx.observe_window_activation(|editor, cx| {
 2082                    let active = cx.is_window_active();
 2083                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2084                        if active {
 2085                            blink_manager.enable(cx);
 2086                        } else {
 2087                            blink_manager.disable(cx);
 2088                        }
 2089                    });
 2090                }),
 2091            ],
 2092            tasks_update_task: None,
 2093            linked_edit_ranges: Default::default(),
 2094            previous_search_ranges: None,
 2095            breadcrumb_header: None,
 2096            focused_block: None,
 2097            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2098            addons: HashMap::default(),
 2099            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2100            text_style_refinement: None,
 2101        };
 2102        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2103        this._subscriptions.extend(project_subscriptions);
 2104
 2105        this.end_selection(cx);
 2106        this.scroll_manager.show_scrollbar(cx);
 2107
 2108        if mode == EditorMode::Full {
 2109            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2110            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2111
 2112            if this.git_blame_inline_enabled {
 2113                this.git_blame_inline_enabled = true;
 2114                this.start_git_blame_inline(false, cx);
 2115            }
 2116        }
 2117
 2118        this.report_editor_event("open", None, cx);
 2119        this
 2120    }
 2121
 2122    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2123        self.mouse_context_menu
 2124            .as_ref()
 2125            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2126    }
 2127
 2128    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2129        let mut key_context = KeyContext::new_with_defaults();
 2130        key_context.add("Editor");
 2131        let mode = match self.mode {
 2132            EditorMode::SingleLine { .. } => "single_line",
 2133            EditorMode::AutoHeight { .. } => "auto_height",
 2134            EditorMode::Full => "full",
 2135        };
 2136
 2137        if EditorSettings::jupyter_enabled(cx) {
 2138            key_context.add("jupyter");
 2139        }
 2140
 2141        key_context.set("mode", mode);
 2142        if self.pending_rename.is_some() {
 2143            key_context.add("renaming");
 2144        }
 2145        if self.context_menu_visible() {
 2146            match self.context_menu.read().as_ref() {
 2147                Some(ContextMenu::Completions(_)) => {
 2148                    key_context.add("menu");
 2149                    key_context.add("showing_completions")
 2150                }
 2151                Some(ContextMenu::CodeActions(_)) => {
 2152                    key_context.add("menu");
 2153                    key_context.add("showing_code_actions")
 2154                }
 2155                None => {}
 2156            }
 2157        }
 2158
 2159        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2160        if !self.focus_handle(cx).contains_focused(cx)
 2161            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2162        {
 2163            for addon in self.addons.values() {
 2164                addon.extend_key_context(&mut key_context, cx)
 2165            }
 2166        }
 2167
 2168        if let Some(extension) = self
 2169            .buffer
 2170            .read(cx)
 2171            .as_singleton()
 2172            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2173        {
 2174            key_context.set("extension", extension.to_string());
 2175        }
 2176
 2177        if self.has_active_inline_completion(cx) {
 2178            key_context.add("copilot_suggestion");
 2179            key_context.add("inline_completion");
 2180        }
 2181
 2182        key_context
 2183    }
 2184
 2185    pub fn new_file(
 2186        workspace: &mut Workspace,
 2187        _: &workspace::NewFile,
 2188        cx: &mut ViewContext<Workspace>,
 2189    ) {
 2190        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2191            "Failed to create buffer",
 2192            cx,
 2193            |e, _| match e.error_code() {
 2194                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2195                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2196                e.error_tag("required").unwrap_or("the latest version")
 2197            )),
 2198                _ => None,
 2199            },
 2200        );
 2201    }
 2202
 2203    pub fn new_in_workspace(
 2204        workspace: &mut Workspace,
 2205        cx: &mut ViewContext<Workspace>,
 2206    ) -> Task<Result<View<Editor>>> {
 2207        let project = workspace.project().clone();
 2208        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2209
 2210        cx.spawn(|workspace, mut cx| async move {
 2211            let buffer = create.await?;
 2212            workspace.update(&mut cx, |workspace, cx| {
 2213                let editor =
 2214                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2215                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2216                editor
 2217            })
 2218        })
 2219    }
 2220
 2221    fn new_file_vertical(
 2222        workspace: &mut Workspace,
 2223        _: &workspace::NewFileSplitVertical,
 2224        cx: &mut ViewContext<Workspace>,
 2225    ) {
 2226        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2227    }
 2228
 2229    fn new_file_horizontal(
 2230        workspace: &mut Workspace,
 2231        _: &workspace::NewFileSplitHorizontal,
 2232        cx: &mut ViewContext<Workspace>,
 2233    ) {
 2234        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2235    }
 2236
 2237    fn new_file_in_direction(
 2238        workspace: &mut Workspace,
 2239        direction: SplitDirection,
 2240        cx: &mut ViewContext<Workspace>,
 2241    ) {
 2242        let project = workspace.project().clone();
 2243        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2244
 2245        cx.spawn(|workspace, mut cx| async move {
 2246            let buffer = create.await?;
 2247            workspace.update(&mut cx, move |workspace, cx| {
 2248                workspace.split_item(
 2249                    direction,
 2250                    Box::new(
 2251                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2252                    ),
 2253                    cx,
 2254                )
 2255            })?;
 2256            anyhow::Ok(())
 2257        })
 2258        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2259            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2260                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2261                e.error_tag("required").unwrap_or("the latest version")
 2262            )),
 2263            _ => None,
 2264        });
 2265    }
 2266
 2267    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2268        self.leader_peer_id
 2269    }
 2270
 2271    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2272        &self.buffer
 2273    }
 2274
 2275    pub fn workspace(&self) -> Option<View<Workspace>> {
 2276        self.workspace.as_ref()?.0.upgrade()
 2277    }
 2278
 2279    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2280        self.buffer().read(cx).title(cx)
 2281    }
 2282
 2283    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2284        let git_blame_gutter_max_author_length = self
 2285            .render_git_blame_gutter(cx)
 2286            .then(|| {
 2287                if let Some(blame) = self.blame.as_ref() {
 2288                    let max_author_length =
 2289                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2290                    Some(max_author_length)
 2291                } else {
 2292                    None
 2293                }
 2294            })
 2295            .flatten();
 2296
 2297        EditorSnapshot {
 2298            mode: self.mode,
 2299            show_gutter: self.show_gutter,
 2300            show_line_numbers: self.show_line_numbers,
 2301            show_git_diff_gutter: self.show_git_diff_gutter,
 2302            show_code_actions: self.show_code_actions,
 2303            show_runnables: self.show_runnables,
 2304            git_blame_gutter_max_author_length,
 2305            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2306            scroll_anchor: self.scroll_manager.anchor(),
 2307            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2308            placeholder_text: self.placeholder_text.clone(),
 2309            is_focused: self.focus_handle.is_focused(cx),
 2310            current_line_highlight: self
 2311                .current_line_highlight
 2312                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2313            gutter_hovered: self.gutter_hovered,
 2314        }
 2315    }
 2316
 2317    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2318        self.buffer.read(cx).language_at(point, cx)
 2319    }
 2320
 2321    pub fn file_at<T: ToOffset>(
 2322        &self,
 2323        point: T,
 2324        cx: &AppContext,
 2325    ) -> Option<Arc<dyn language::File>> {
 2326        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2327    }
 2328
 2329    pub fn active_excerpt(
 2330        &self,
 2331        cx: &AppContext,
 2332    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2333        self.buffer
 2334            .read(cx)
 2335            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2336    }
 2337
 2338    pub fn mode(&self) -> EditorMode {
 2339        self.mode
 2340    }
 2341
 2342    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2343        self.collaboration_hub.as_deref()
 2344    }
 2345
 2346    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2347        self.collaboration_hub = Some(hub);
 2348    }
 2349
 2350    pub fn set_custom_context_menu(
 2351        &mut self,
 2352        f: impl 'static
 2353            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2354    ) {
 2355        self.custom_context_menu = Some(Box::new(f))
 2356    }
 2357
 2358    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2359        self.completion_provider = provider;
 2360    }
 2361
 2362    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2363        self.semantics_provider.clone()
 2364    }
 2365
 2366    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2367        self.semantics_provider = provider;
 2368    }
 2369
 2370    pub fn set_inline_completion_provider<T>(
 2371        &mut self,
 2372        provider: Option<Model<T>>,
 2373        cx: &mut ViewContext<Self>,
 2374    ) where
 2375        T: InlineCompletionProvider,
 2376    {
 2377        self.inline_completion_provider =
 2378            provider.map(|provider| RegisteredInlineCompletionProvider {
 2379                _subscription: cx.observe(&provider, |this, _, cx| {
 2380                    if this.focus_handle.is_focused(cx) {
 2381                        this.update_visible_inline_completion(cx);
 2382                    }
 2383                }),
 2384                provider: Arc::new(provider),
 2385            });
 2386        self.refresh_inline_completion(false, false, cx);
 2387    }
 2388
 2389    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2390        self.placeholder_text.as_deref()
 2391    }
 2392
 2393    pub fn set_placeholder_text(
 2394        &mut self,
 2395        placeholder_text: impl Into<Arc<str>>,
 2396        cx: &mut ViewContext<Self>,
 2397    ) {
 2398        let placeholder_text = Some(placeholder_text.into());
 2399        if self.placeholder_text != placeholder_text {
 2400            self.placeholder_text = placeholder_text;
 2401            cx.notify();
 2402        }
 2403    }
 2404
 2405    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2406        self.cursor_shape = cursor_shape;
 2407
 2408        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2409        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2410
 2411        cx.notify();
 2412    }
 2413
 2414    pub fn set_current_line_highlight(
 2415        &mut self,
 2416        current_line_highlight: Option<CurrentLineHighlight>,
 2417    ) {
 2418        self.current_line_highlight = current_line_highlight;
 2419    }
 2420
 2421    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2422        self.collapse_matches = collapse_matches;
 2423    }
 2424
 2425    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2426        if self.collapse_matches {
 2427            return range.start..range.start;
 2428        }
 2429        range.clone()
 2430    }
 2431
 2432    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2433        if self.display_map.read(cx).clip_at_line_ends != clip {
 2434            self.display_map
 2435                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2436        }
 2437    }
 2438
 2439    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2440        self.input_enabled = input_enabled;
 2441    }
 2442
 2443    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2444        self.enable_inline_completions = enabled;
 2445    }
 2446
 2447    pub fn set_autoindent(&mut self, autoindent: bool) {
 2448        if autoindent {
 2449            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2450        } else {
 2451            self.autoindent_mode = None;
 2452        }
 2453    }
 2454
 2455    pub fn read_only(&self, cx: &AppContext) -> bool {
 2456        self.read_only || self.buffer.read(cx).read_only()
 2457    }
 2458
 2459    pub fn set_read_only(&mut self, read_only: bool) {
 2460        self.read_only = read_only;
 2461    }
 2462
 2463    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2464        self.use_autoclose = autoclose;
 2465    }
 2466
 2467    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2468        self.use_auto_surround = auto_surround;
 2469    }
 2470
 2471    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2472        self.auto_replace_emoji_shortcode = auto_replace;
 2473    }
 2474
 2475    pub fn toggle_inline_completions(
 2476        &mut self,
 2477        _: &ToggleInlineCompletions,
 2478        cx: &mut ViewContext<Self>,
 2479    ) {
 2480        if self.show_inline_completions_override.is_some() {
 2481            self.set_show_inline_completions(None, cx);
 2482        } else {
 2483            let cursor = self.selections.newest_anchor().head();
 2484            if let Some((buffer, cursor_buffer_position)) =
 2485                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2486            {
 2487                let show_inline_completions =
 2488                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2489                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2490            }
 2491        }
 2492    }
 2493
 2494    pub fn set_show_inline_completions(
 2495        &mut self,
 2496        show_inline_completions: Option<bool>,
 2497        cx: &mut ViewContext<Self>,
 2498    ) {
 2499        self.show_inline_completions_override = show_inline_completions;
 2500        self.refresh_inline_completion(false, true, cx);
 2501    }
 2502
 2503    fn should_show_inline_completions(
 2504        &self,
 2505        buffer: &Model<Buffer>,
 2506        buffer_position: language::Anchor,
 2507        cx: &AppContext,
 2508    ) -> bool {
 2509        if !self.snippet_stack.is_empty() {
 2510            return false;
 2511        }
 2512
 2513        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2514            return false;
 2515        }
 2516
 2517        if let Some(provider) = self.inline_completion_provider() {
 2518            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2519                show_inline_completions
 2520            } else {
 2521                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2522            }
 2523        } else {
 2524            false
 2525        }
 2526    }
 2527
 2528    fn inline_completions_disabled_in_scope(
 2529        &self,
 2530        buffer: &Model<Buffer>,
 2531        buffer_position: language::Anchor,
 2532        cx: &AppContext,
 2533    ) -> bool {
 2534        let snapshot = buffer.read(cx).snapshot();
 2535        let settings = snapshot.settings_at(buffer_position, cx);
 2536
 2537        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2538            return false;
 2539        };
 2540
 2541        scope.override_name().map_or(false, |scope_name| {
 2542            settings
 2543                .inline_completions_disabled_in
 2544                .iter()
 2545                .any(|s| s == scope_name)
 2546        })
 2547    }
 2548
 2549    pub fn set_use_modal_editing(&mut self, to: bool) {
 2550        self.use_modal_editing = to;
 2551    }
 2552
 2553    pub fn use_modal_editing(&self) -> bool {
 2554        self.use_modal_editing
 2555    }
 2556
 2557    fn selections_did_change(
 2558        &mut self,
 2559        local: bool,
 2560        old_cursor_position: &Anchor,
 2561        show_completions: bool,
 2562        cx: &mut ViewContext<Self>,
 2563    ) {
 2564        cx.invalidate_character_coordinates();
 2565
 2566        // Copy selections to primary selection buffer
 2567        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2568        if local {
 2569            let selections = self.selections.all::<usize>(cx);
 2570            let buffer_handle = self.buffer.read(cx).read(cx);
 2571
 2572            let mut text = String::new();
 2573            for (index, selection) in selections.iter().enumerate() {
 2574                let text_for_selection = buffer_handle
 2575                    .text_for_range(selection.start..selection.end)
 2576                    .collect::<String>();
 2577
 2578                text.push_str(&text_for_selection);
 2579                if index != selections.len() - 1 {
 2580                    text.push('\n');
 2581                }
 2582            }
 2583
 2584            if !text.is_empty() {
 2585                cx.write_to_primary(ClipboardItem::new_string(text));
 2586            }
 2587        }
 2588
 2589        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2590            self.buffer.update(cx, |buffer, cx| {
 2591                buffer.set_active_selections(
 2592                    &self.selections.disjoint_anchors(),
 2593                    self.selections.line_mode,
 2594                    self.cursor_shape,
 2595                    cx,
 2596                )
 2597            });
 2598        }
 2599        let display_map = self
 2600            .display_map
 2601            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2602        let buffer = &display_map.buffer_snapshot;
 2603        self.add_selections_state = None;
 2604        self.select_next_state = None;
 2605        self.select_prev_state = None;
 2606        self.select_larger_syntax_node_stack.clear();
 2607        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2608        self.snippet_stack
 2609            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2610        self.take_rename(false, cx);
 2611
 2612        let new_cursor_position = self.selections.newest_anchor().head();
 2613
 2614        self.push_to_nav_history(
 2615            *old_cursor_position,
 2616            Some(new_cursor_position.to_point(buffer)),
 2617            cx,
 2618        );
 2619
 2620        if local {
 2621            let new_cursor_position = self.selections.newest_anchor().head();
 2622            let mut context_menu = self.context_menu.write();
 2623            let completion_menu = match context_menu.as_ref() {
 2624                Some(ContextMenu::Completions(menu)) => Some(menu),
 2625
 2626                _ => {
 2627                    *context_menu = None;
 2628                    None
 2629                }
 2630            };
 2631
 2632            if let Some(completion_menu) = completion_menu {
 2633                let cursor_position = new_cursor_position.to_offset(buffer);
 2634                let (word_range, kind) =
 2635                    buffer.surrounding_word(completion_menu.initial_position, true);
 2636                if kind == Some(CharKind::Word)
 2637                    && word_range.to_inclusive().contains(&cursor_position)
 2638                {
 2639                    let mut completion_menu = completion_menu.clone();
 2640                    drop(context_menu);
 2641
 2642                    let query = Self::completion_query(buffer, cursor_position);
 2643                    cx.spawn(move |this, mut cx| async move {
 2644                        completion_menu
 2645                            .filter(query.as_deref(), cx.background_executor().clone())
 2646                            .await;
 2647
 2648                        this.update(&mut cx, |this, cx| {
 2649                            let mut context_menu = this.context_menu.write();
 2650                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2651                                return;
 2652                            };
 2653
 2654                            if menu.id > completion_menu.id {
 2655                                return;
 2656                            }
 2657
 2658                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2659                            drop(context_menu);
 2660                            cx.notify();
 2661                        })
 2662                    })
 2663                    .detach();
 2664
 2665                    if show_completions {
 2666                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2667                    }
 2668                } else {
 2669                    drop(context_menu);
 2670                    self.hide_context_menu(cx);
 2671                }
 2672            } else {
 2673                drop(context_menu);
 2674            }
 2675
 2676            hide_hover(self, cx);
 2677
 2678            if old_cursor_position.to_display_point(&display_map).row()
 2679                != new_cursor_position.to_display_point(&display_map).row()
 2680            {
 2681                self.available_code_actions.take();
 2682            }
 2683            self.refresh_code_actions(cx);
 2684            self.refresh_document_highlights(cx);
 2685            refresh_matching_bracket_highlights(self, cx);
 2686            self.discard_inline_completion(false, cx);
 2687            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2688            if self.git_blame_inline_enabled {
 2689                self.start_inline_blame_timer(cx);
 2690            }
 2691        }
 2692
 2693        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2694        cx.emit(EditorEvent::SelectionsChanged { local });
 2695
 2696        if self.selections.disjoint_anchors().len() == 1 {
 2697            cx.emit(SearchEvent::ActiveMatchChanged)
 2698        }
 2699        cx.notify();
 2700    }
 2701
 2702    pub fn change_selections<R>(
 2703        &mut self,
 2704        autoscroll: Option<Autoscroll>,
 2705        cx: &mut ViewContext<Self>,
 2706        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2707    ) -> R {
 2708        self.change_selections_inner(autoscroll, true, cx, change)
 2709    }
 2710
 2711    pub fn change_selections_inner<R>(
 2712        &mut self,
 2713        autoscroll: Option<Autoscroll>,
 2714        request_completions: bool,
 2715        cx: &mut ViewContext<Self>,
 2716        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2717    ) -> R {
 2718        let old_cursor_position = self.selections.newest_anchor().head();
 2719        self.push_to_selection_history();
 2720
 2721        let (changed, result) = self.selections.change_with(cx, change);
 2722
 2723        if changed {
 2724            if let Some(autoscroll) = autoscroll {
 2725                self.request_autoscroll(autoscroll, cx);
 2726            }
 2727            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2728
 2729            if self.should_open_signature_help_automatically(
 2730                &old_cursor_position,
 2731                self.signature_help_state.backspace_pressed(),
 2732                cx,
 2733            ) {
 2734                self.show_signature_help(&ShowSignatureHelp, cx);
 2735            }
 2736            self.signature_help_state.set_backspace_pressed(false);
 2737        }
 2738
 2739        result
 2740    }
 2741
 2742    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2743    where
 2744        I: IntoIterator<Item = (Range<S>, T)>,
 2745        S: ToOffset,
 2746        T: Into<Arc<str>>,
 2747    {
 2748        if self.read_only(cx) {
 2749            return;
 2750        }
 2751
 2752        self.buffer
 2753            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2754    }
 2755
 2756    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2757    where
 2758        I: IntoIterator<Item = (Range<S>, T)>,
 2759        S: ToOffset,
 2760        T: Into<Arc<str>>,
 2761    {
 2762        if self.read_only(cx) {
 2763            return;
 2764        }
 2765
 2766        self.buffer.update(cx, |buffer, cx| {
 2767            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2768        });
 2769    }
 2770
 2771    pub fn edit_with_block_indent<I, S, T>(
 2772        &mut self,
 2773        edits: I,
 2774        original_indent_columns: Vec<u32>,
 2775        cx: &mut ViewContext<Self>,
 2776    ) where
 2777        I: IntoIterator<Item = (Range<S>, T)>,
 2778        S: ToOffset,
 2779        T: Into<Arc<str>>,
 2780    {
 2781        if self.read_only(cx) {
 2782            return;
 2783        }
 2784
 2785        self.buffer.update(cx, |buffer, cx| {
 2786            buffer.edit(
 2787                edits,
 2788                Some(AutoindentMode::Block {
 2789                    original_indent_columns,
 2790                }),
 2791                cx,
 2792            )
 2793        });
 2794    }
 2795
 2796    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2797        self.hide_context_menu(cx);
 2798
 2799        match phase {
 2800            SelectPhase::Begin {
 2801                position,
 2802                add,
 2803                click_count,
 2804            } => self.begin_selection(position, add, click_count, cx),
 2805            SelectPhase::BeginColumnar {
 2806                position,
 2807                goal_column,
 2808                reset,
 2809            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2810            SelectPhase::Extend {
 2811                position,
 2812                click_count,
 2813            } => self.extend_selection(position, click_count, cx),
 2814            SelectPhase::Update {
 2815                position,
 2816                goal_column,
 2817                scroll_delta,
 2818            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2819            SelectPhase::End => self.end_selection(cx),
 2820        }
 2821    }
 2822
 2823    fn extend_selection(
 2824        &mut self,
 2825        position: DisplayPoint,
 2826        click_count: usize,
 2827        cx: &mut ViewContext<Self>,
 2828    ) {
 2829        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2830        let tail = self.selections.newest::<usize>(cx).tail();
 2831        self.begin_selection(position, false, click_count, cx);
 2832
 2833        let position = position.to_offset(&display_map, Bias::Left);
 2834        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2835
 2836        let mut pending_selection = self
 2837            .selections
 2838            .pending_anchor()
 2839            .expect("extend_selection not called with pending selection");
 2840        if position >= tail {
 2841            pending_selection.start = tail_anchor;
 2842        } else {
 2843            pending_selection.end = tail_anchor;
 2844            pending_selection.reversed = true;
 2845        }
 2846
 2847        let mut pending_mode = self.selections.pending_mode().unwrap();
 2848        match &mut pending_mode {
 2849            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2850            _ => {}
 2851        }
 2852
 2853        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2854            s.set_pending(pending_selection, pending_mode)
 2855        });
 2856    }
 2857
 2858    fn begin_selection(
 2859        &mut self,
 2860        position: DisplayPoint,
 2861        add: bool,
 2862        click_count: usize,
 2863        cx: &mut ViewContext<Self>,
 2864    ) {
 2865        if !self.focus_handle.is_focused(cx) {
 2866            self.last_focused_descendant = None;
 2867            cx.focus(&self.focus_handle);
 2868        }
 2869
 2870        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2871        let buffer = &display_map.buffer_snapshot;
 2872        let newest_selection = self.selections.newest_anchor().clone();
 2873        let position = display_map.clip_point(position, Bias::Left);
 2874
 2875        let start;
 2876        let end;
 2877        let mode;
 2878        let auto_scroll;
 2879        match click_count {
 2880            1 => {
 2881                start = buffer.anchor_before(position.to_point(&display_map));
 2882                end = start;
 2883                mode = SelectMode::Character;
 2884                auto_scroll = true;
 2885            }
 2886            2 => {
 2887                let range = movement::surrounding_word(&display_map, position);
 2888                start = buffer.anchor_before(range.start.to_point(&display_map));
 2889                end = buffer.anchor_before(range.end.to_point(&display_map));
 2890                mode = SelectMode::Word(start..end);
 2891                auto_scroll = true;
 2892            }
 2893            3 => {
 2894                let position = display_map
 2895                    .clip_point(position, Bias::Left)
 2896                    .to_point(&display_map);
 2897                let line_start = display_map.prev_line_boundary(position).0;
 2898                let next_line_start = buffer.clip_point(
 2899                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2900                    Bias::Left,
 2901                );
 2902                start = buffer.anchor_before(line_start);
 2903                end = buffer.anchor_before(next_line_start);
 2904                mode = SelectMode::Line(start..end);
 2905                auto_scroll = true;
 2906            }
 2907            _ => {
 2908                start = buffer.anchor_before(0);
 2909                end = buffer.anchor_before(buffer.len());
 2910                mode = SelectMode::All;
 2911                auto_scroll = false;
 2912            }
 2913        }
 2914
 2915        let point_to_delete: Option<usize> = {
 2916            let selected_points: Vec<Selection<Point>> =
 2917                self.selections.disjoint_in_range(start..end, cx);
 2918
 2919            if !add || click_count > 1 {
 2920                None
 2921            } else if !selected_points.is_empty() {
 2922                Some(selected_points[0].id)
 2923            } else {
 2924                let clicked_point_already_selected =
 2925                    self.selections.disjoint.iter().find(|selection| {
 2926                        selection.start.to_point(buffer) == start.to_point(buffer)
 2927                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2928                    });
 2929
 2930                clicked_point_already_selected.map(|selection| selection.id)
 2931            }
 2932        };
 2933
 2934        let selections_count = self.selections.count();
 2935
 2936        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2937            if let Some(point_to_delete) = point_to_delete {
 2938                s.delete(point_to_delete);
 2939
 2940                if selections_count == 1 {
 2941                    s.set_pending_anchor_range(start..end, mode);
 2942                }
 2943            } else {
 2944                if !add {
 2945                    s.clear_disjoint();
 2946                } else if click_count > 1 {
 2947                    s.delete(newest_selection.id)
 2948                }
 2949
 2950                s.set_pending_anchor_range(start..end, mode);
 2951            }
 2952        });
 2953    }
 2954
 2955    fn begin_columnar_selection(
 2956        &mut self,
 2957        position: DisplayPoint,
 2958        goal_column: u32,
 2959        reset: bool,
 2960        cx: &mut ViewContext<Self>,
 2961    ) {
 2962        if !self.focus_handle.is_focused(cx) {
 2963            self.last_focused_descendant = None;
 2964            cx.focus(&self.focus_handle);
 2965        }
 2966
 2967        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2968
 2969        if reset {
 2970            let pointer_position = display_map
 2971                .buffer_snapshot
 2972                .anchor_before(position.to_point(&display_map));
 2973
 2974            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2975                s.clear_disjoint();
 2976                s.set_pending_anchor_range(
 2977                    pointer_position..pointer_position,
 2978                    SelectMode::Character,
 2979                );
 2980            });
 2981        }
 2982
 2983        let tail = self.selections.newest::<Point>(cx).tail();
 2984        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2985
 2986        if !reset {
 2987            self.select_columns(
 2988                tail.to_display_point(&display_map),
 2989                position,
 2990                goal_column,
 2991                &display_map,
 2992                cx,
 2993            );
 2994        }
 2995    }
 2996
 2997    fn update_selection(
 2998        &mut self,
 2999        position: DisplayPoint,
 3000        goal_column: u32,
 3001        scroll_delta: gpui::Point<f32>,
 3002        cx: &mut ViewContext<Self>,
 3003    ) {
 3004        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3005
 3006        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3007            let tail = tail.to_display_point(&display_map);
 3008            self.select_columns(tail, position, goal_column, &display_map, cx);
 3009        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3010            let buffer = self.buffer.read(cx).snapshot(cx);
 3011            let head;
 3012            let tail;
 3013            let mode = self.selections.pending_mode().unwrap();
 3014            match &mode {
 3015                SelectMode::Character => {
 3016                    head = position.to_point(&display_map);
 3017                    tail = pending.tail().to_point(&buffer);
 3018                }
 3019                SelectMode::Word(original_range) => {
 3020                    let original_display_range = original_range.start.to_display_point(&display_map)
 3021                        ..original_range.end.to_display_point(&display_map);
 3022                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3023                        ..original_display_range.end.to_point(&display_map);
 3024                    if movement::is_inside_word(&display_map, position)
 3025                        || original_display_range.contains(&position)
 3026                    {
 3027                        let word_range = movement::surrounding_word(&display_map, position);
 3028                        if word_range.start < original_display_range.start {
 3029                            head = word_range.start.to_point(&display_map);
 3030                        } else {
 3031                            head = word_range.end.to_point(&display_map);
 3032                        }
 3033                    } else {
 3034                        head = position.to_point(&display_map);
 3035                    }
 3036
 3037                    if head <= original_buffer_range.start {
 3038                        tail = original_buffer_range.end;
 3039                    } else {
 3040                        tail = original_buffer_range.start;
 3041                    }
 3042                }
 3043                SelectMode::Line(original_range) => {
 3044                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3045
 3046                    let position = display_map
 3047                        .clip_point(position, Bias::Left)
 3048                        .to_point(&display_map);
 3049                    let line_start = display_map.prev_line_boundary(position).0;
 3050                    let next_line_start = buffer.clip_point(
 3051                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3052                        Bias::Left,
 3053                    );
 3054
 3055                    if line_start < original_range.start {
 3056                        head = line_start
 3057                    } else {
 3058                        head = next_line_start
 3059                    }
 3060
 3061                    if head <= original_range.start {
 3062                        tail = original_range.end;
 3063                    } else {
 3064                        tail = original_range.start;
 3065                    }
 3066                }
 3067                SelectMode::All => {
 3068                    return;
 3069                }
 3070            };
 3071
 3072            if head < tail {
 3073                pending.start = buffer.anchor_before(head);
 3074                pending.end = buffer.anchor_before(tail);
 3075                pending.reversed = true;
 3076            } else {
 3077                pending.start = buffer.anchor_before(tail);
 3078                pending.end = buffer.anchor_before(head);
 3079                pending.reversed = false;
 3080            }
 3081
 3082            self.change_selections(None, cx, |s| {
 3083                s.set_pending(pending, mode);
 3084            });
 3085        } else {
 3086            log::error!("update_selection dispatched with no pending selection");
 3087            return;
 3088        }
 3089
 3090        self.apply_scroll_delta(scroll_delta, cx);
 3091        cx.notify();
 3092    }
 3093
 3094    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3095        self.columnar_selection_tail.take();
 3096        if self.selections.pending_anchor().is_some() {
 3097            let selections = self.selections.all::<usize>(cx);
 3098            self.change_selections(None, cx, |s| {
 3099                s.select(selections);
 3100                s.clear_pending();
 3101            });
 3102        }
 3103    }
 3104
 3105    fn select_columns(
 3106        &mut self,
 3107        tail: DisplayPoint,
 3108        head: DisplayPoint,
 3109        goal_column: u32,
 3110        display_map: &DisplaySnapshot,
 3111        cx: &mut ViewContext<Self>,
 3112    ) {
 3113        let start_row = cmp::min(tail.row(), head.row());
 3114        let end_row = cmp::max(tail.row(), head.row());
 3115        let start_column = cmp::min(tail.column(), goal_column);
 3116        let end_column = cmp::max(tail.column(), goal_column);
 3117        let reversed = start_column < tail.column();
 3118
 3119        let selection_ranges = (start_row.0..=end_row.0)
 3120            .map(DisplayRow)
 3121            .filter_map(|row| {
 3122                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3123                    let start = display_map
 3124                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3125                        .to_point(display_map);
 3126                    let end = display_map
 3127                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3128                        .to_point(display_map);
 3129                    if reversed {
 3130                        Some(end..start)
 3131                    } else {
 3132                        Some(start..end)
 3133                    }
 3134                } else {
 3135                    None
 3136                }
 3137            })
 3138            .collect::<Vec<_>>();
 3139
 3140        self.change_selections(None, cx, |s| {
 3141            s.select_ranges(selection_ranges);
 3142        });
 3143        cx.notify();
 3144    }
 3145
 3146    pub fn has_pending_nonempty_selection(&self) -> bool {
 3147        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3148            Some(Selection { start, end, .. }) => start != end,
 3149            None => false,
 3150        };
 3151
 3152        pending_nonempty_selection
 3153            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3154    }
 3155
 3156    pub fn has_pending_selection(&self) -> bool {
 3157        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3158    }
 3159
 3160    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3161        if self.clear_expanded_diff_hunks(cx) {
 3162            cx.notify();
 3163            return;
 3164        }
 3165        if self.dismiss_menus_and_popups(true, cx) {
 3166            return;
 3167        }
 3168
 3169        if self.mode == EditorMode::Full
 3170            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3171        {
 3172            return;
 3173        }
 3174
 3175        cx.propagate();
 3176    }
 3177
 3178    pub fn dismiss_menus_and_popups(
 3179        &mut self,
 3180        should_report_inline_completion_event: bool,
 3181        cx: &mut ViewContext<Self>,
 3182    ) -> bool {
 3183        if self.take_rename(false, cx).is_some() {
 3184            return true;
 3185        }
 3186
 3187        if hide_hover(self, cx) {
 3188            return true;
 3189        }
 3190
 3191        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3192            return true;
 3193        }
 3194
 3195        if self.hide_context_menu(cx).is_some() {
 3196            return true;
 3197        }
 3198
 3199        if self.mouse_context_menu.take().is_some() {
 3200            return true;
 3201        }
 3202
 3203        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3204            return true;
 3205        }
 3206
 3207        if self.snippet_stack.pop().is_some() {
 3208            return true;
 3209        }
 3210
 3211        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3212            self.dismiss_diagnostics(cx);
 3213            return true;
 3214        }
 3215
 3216        false
 3217    }
 3218
 3219    fn linked_editing_ranges_for(
 3220        &self,
 3221        selection: Range<text::Anchor>,
 3222        cx: &AppContext,
 3223    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3224        if self.linked_edit_ranges.is_empty() {
 3225            return None;
 3226        }
 3227        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3228            selection.end.buffer_id.and_then(|end_buffer_id| {
 3229                if selection.start.buffer_id != Some(end_buffer_id) {
 3230                    return None;
 3231                }
 3232                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3233                let snapshot = buffer.read(cx).snapshot();
 3234                self.linked_edit_ranges
 3235                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3236                    .map(|ranges| (ranges, snapshot, buffer))
 3237            })?;
 3238        use text::ToOffset as TO;
 3239        // find offset from the start of current range to current cursor position
 3240        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3241
 3242        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3243        let start_difference = start_offset - start_byte_offset;
 3244        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3245        let end_difference = end_offset - start_byte_offset;
 3246        // Current range has associated linked ranges.
 3247        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3248        for range in linked_ranges.iter() {
 3249            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3250            let end_offset = start_offset + end_difference;
 3251            let start_offset = start_offset + start_difference;
 3252            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3253                continue;
 3254            }
 3255            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3256                if s.start.buffer_id != selection.start.buffer_id
 3257                    || s.end.buffer_id != selection.end.buffer_id
 3258                {
 3259                    return false;
 3260                }
 3261                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3262                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3263            }) {
 3264                continue;
 3265            }
 3266            let start = buffer_snapshot.anchor_after(start_offset);
 3267            let end = buffer_snapshot.anchor_after(end_offset);
 3268            linked_edits
 3269                .entry(buffer.clone())
 3270                .or_default()
 3271                .push(start..end);
 3272        }
 3273        Some(linked_edits)
 3274    }
 3275
 3276    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3277        let text: Arc<str> = text.into();
 3278
 3279        if self.read_only(cx) {
 3280            return;
 3281        }
 3282
 3283        let selections = self.selections.all_adjusted(cx);
 3284        let mut bracket_inserted = false;
 3285        let mut edits = Vec::new();
 3286        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3287        let mut new_selections = Vec::with_capacity(selections.len());
 3288        let mut new_autoclose_regions = Vec::new();
 3289        let snapshot = self.buffer.read(cx).read(cx);
 3290
 3291        for (selection, autoclose_region) in
 3292            self.selections_with_autoclose_regions(selections, &snapshot)
 3293        {
 3294            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3295                // Determine if the inserted text matches the opening or closing
 3296                // bracket of any of this language's bracket pairs.
 3297                let mut bracket_pair = None;
 3298                let mut is_bracket_pair_start = false;
 3299                let mut is_bracket_pair_end = false;
 3300                if !text.is_empty() {
 3301                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3302                    //  and they are removing the character that triggered IME popup.
 3303                    for (pair, enabled) in scope.brackets() {
 3304                        if !pair.close && !pair.surround {
 3305                            continue;
 3306                        }
 3307
 3308                        if enabled && pair.start.ends_with(text.as_ref()) {
 3309                            let prefix_len = pair.start.len() - text.len();
 3310                            let preceding_text_matches_prefix = prefix_len == 0
 3311                                || (selection.start.column >= (prefix_len as u32)
 3312                                    && snapshot.contains_str_at(
 3313                                        Point::new(
 3314                                            selection.start.row,
 3315                                            selection.start.column - (prefix_len as u32),
 3316                                        ),
 3317                                        &pair.start[..prefix_len],
 3318                                    ));
 3319                            if preceding_text_matches_prefix {
 3320                                bracket_pair = Some(pair.clone());
 3321                                is_bracket_pair_start = true;
 3322                                break;
 3323                            }
 3324                        }
 3325                        if pair.end.as_str() == text.as_ref() {
 3326                            bracket_pair = Some(pair.clone());
 3327                            is_bracket_pair_end = true;
 3328                            break;
 3329                        }
 3330                    }
 3331                }
 3332
 3333                if let Some(bracket_pair) = bracket_pair {
 3334                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3335                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3336                    let auto_surround =
 3337                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3338                    if selection.is_empty() {
 3339                        if is_bracket_pair_start {
 3340                            // If the inserted text is a suffix of an opening bracket and the
 3341                            // selection is preceded by the rest of the opening bracket, then
 3342                            // insert the closing bracket.
 3343                            let following_text_allows_autoclose = snapshot
 3344                                .chars_at(selection.start)
 3345                                .next()
 3346                                .map_or(true, |c| scope.should_autoclose_before(c));
 3347
 3348                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3349                                && bracket_pair.start.len() == 1
 3350                            {
 3351                                let target = bracket_pair.start.chars().next().unwrap();
 3352                                let current_line_count = snapshot
 3353                                    .reversed_chars_at(selection.start)
 3354                                    .take_while(|&c| c != '\n')
 3355                                    .filter(|&c| c == target)
 3356                                    .count();
 3357                                current_line_count % 2 == 1
 3358                            } else {
 3359                                false
 3360                            };
 3361
 3362                            if autoclose
 3363                                && bracket_pair.close
 3364                                && following_text_allows_autoclose
 3365                                && !is_closing_quote
 3366                            {
 3367                                let anchor = snapshot.anchor_before(selection.end);
 3368                                new_selections.push((selection.map(|_| anchor), text.len()));
 3369                                new_autoclose_regions.push((
 3370                                    anchor,
 3371                                    text.len(),
 3372                                    selection.id,
 3373                                    bracket_pair.clone(),
 3374                                ));
 3375                                edits.push((
 3376                                    selection.range(),
 3377                                    format!("{}{}", text, bracket_pair.end).into(),
 3378                                ));
 3379                                bracket_inserted = true;
 3380                                continue;
 3381                            }
 3382                        }
 3383
 3384                        if let Some(region) = autoclose_region {
 3385                            // If the selection is followed by an auto-inserted closing bracket,
 3386                            // then don't insert that closing bracket again; just move the selection
 3387                            // past the closing bracket.
 3388                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3389                                && text.as_ref() == region.pair.end.as_str();
 3390                            if should_skip {
 3391                                let anchor = snapshot.anchor_after(selection.end);
 3392                                new_selections
 3393                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3394                                continue;
 3395                            }
 3396                        }
 3397
 3398                        let always_treat_brackets_as_autoclosed = snapshot
 3399                            .settings_at(selection.start, cx)
 3400                            .always_treat_brackets_as_autoclosed;
 3401                        if always_treat_brackets_as_autoclosed
 3402                            && is_bracket_pair_end
 3403                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3404                        {
 3405                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3406                            // and the inserted text is a closing bracket and the selection is followed
 3407                            // by the closing bracket then move the selection past the closing bracket.
 3408                            let anchor = snapshot.anchor_after(selection.end);
 3409                            new_selections.push((selection.map(|_| anchor), text.len()));
 3410                            continue;
 3411                        }
 3412                    }
 3413                    // If an opening bracket is 1 character long and is typed while
 3414                    // text is selected, then surround that text with the bracket pair.
 3415                    else if auto_surround
 3416                        && bracket_pair.surround
 3417                        && is_bracket_pair_start
 3418                        && bracket_pair.start.chars().count() == 1
 3419                    {
 3420                        edits.push((selection.start..selection.start, text.clone()));
 3421                        edits.push((
 3422                            selection.end..selection.end,
 3423                            bracket_pair.end.as_str().into(),
 3424                        ));
 3425                        bracket_inserted = true;
 3426                        new_selections.push((
 3427                            Selection {
 3428                                id: selection.id,
 3429                                start: snapshot.anchor_after(selection.start),
 3430                                end: snapshot.anchor_before(selection.end),
 3431                                reversed: selection.reversed,
 3432                                goal: selection.goal,
 3433                            },
 3434                            0,
 3435                        ));
 3436                        continue;
 3437                    }
 3438                }
 3439            }
 3440
 3441            if self.auto_replace_emoji_shortcode
 3442                && selection.is_empty()
 3443                && text.as_ref().ends_with(':')
 3444            {
 3445                if let Some(possible_emoji_short_code) =
 3446                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3447                {
 3448                    if !possible_emoji_short_code.is_empty() {
 3449                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3450                            let emoji_shortcode_start = Point::new(
 3451                                selection.start.row,
 3452                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3453                            );
 3454
 3455                            // Remove shortcode from buffer
 3456                            edits.push((
 3457                                emoji_shortcode_start..selection.start,
 3458                                "".to_string().into(),
 3459                            ));
 3460                            new_selections.push((
 3461                                Selection {
 3462                                    id: selection.id,
 3463                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3464                                    end: snapshot.anchor_before(selection.start),
 3465                                    reversed: selection.reversed,
 3466                                    goal: selection.goal,
 3467                                },
 3468                                0,
 3469                            ));
 3470
 3471                            // Insert emoji
 3472                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3473                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3474                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3475
 3476                            continue;
 3477                        }
 3478                    }
 3479                }
 3480            }
 3481
 3482            // If not handling any auto-close operation, then just replace the selected
 3483            // text with the given input and move the selection to the end of the
 3484            // newly inserted text.
 3485            let anchor = snapshot.anchor_after(selection.end);
 3486            if !self.linked_edit_ranges.is_empty() {
 3487                let start_anchor = snapshot.anchor_before(selection.start);
 3488
 3489                let is_word_char = text.chars().next().map_or(true, |char| {
 3490                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3491                    classifier.is_word(char)
 3492                });
 3493
 3494                if is_word_char {
 3495                    if let Some(ranges) = self
 3496                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3497                    {
 3498                        for (buffer, edits) in ranges {
 3499                            linked_edits
 3500                                .entry(buffer.clone())
 3501                                .or_default()
 3502                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3503                        }
 3504                    }
 3505                }
 3506            }
 3507
 3508            new_selections.push((selection.map(|_| anchor), 0));
 3509            edits.push((selection.start..selection.end, text.clone()));
 3510        }
 3511
 3512        drop(snapshot);
 3513
 3514        self.transact(cx, |this, cx| {
 3515            this.buffer.update(cx, |buffer, cx| {
 3516                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3517            });
 3518            for (buffer, edits) in linked_edits {
 3519                buffer.update(cx, |buffer, cx| {
 3520                    let snapshot = buffer.snapshot();
 3521                    let edits = edits
 3522                        .into_iter()
 3523                        .map(|(range, text)| {
 3524                            use text::ToPoint as TP;
 3525                            let end_point = TP::to_point(&range.end, &snapshot);
 3526                            let start_point = TP::to_point(&range.start, &snapshot);
 3527                            (start_point..end_point, text)
 3528                        })
 3529                        .sorted_by_key(|(range, _)| range.start)
 3530                        .collect::<Vec<_>>();
 3531                    buffer.edit(edits, None, cx);
 3532                })
 3533            }
 3534            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3535            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3536            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3537            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3538                .zip(new_selection_deltas)
 3539                .map(|(selection, delta)| Selection {
 3540                    id: selection.id,
 3541                    start: selection.start + delta,
 3542                    end: selection.end + delta,
 3543                    reversed: selection.reversed,
 3544                    goal: SelectionGoal::None,
 3545                })
 3546                .collect::<Vec<_>>();
 3547
 3548            let mut i = 0;
 3549            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3550                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3551                let start = map.buffer_snapshot.anchor_before(position);
 3552                let end = map.buffer_snapshot.anchor_after(position);
 3553                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3554                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3555                        Ordering::Less => i += 1,
 3556                        Ordering::Greater => break,
 3557                        Ordering::Equal => {
 3558                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3559                                Ordering::Less => i += 1,
 3560                                Ordering::Equal => break,
 3561                                Ordering::Greater => break,
 3562                            }
 3563                        }
 3564                    }
 3565                }
 3566                this.autoclose_regions.insert(
 3567                    i,
 3568                    AutocloseRegion {
 3569                        selection_id,
 3570                        range: start..end,
 3571                        pair,
 3572                    },
 3573                );
 3574            }
 3575
 3576            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3577            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3578                s.select(new_selections)
 3579            });
 3580
 3581            if !bracket_inserted {
 3582                if let Some(on_type_format_task) =
 3583                    this.trigger_on_type_formatting(text.to_string(), cx)
 3584                {
 3585                    on_type_format_task.detach_and_log_err(cx);
 3586                }
 3587            }
 3588
 3589            let editor_settings = EditorSettings::get_global(cx);
 3590            if bracket_inserted
 3591                && (editor_settings.auto_signature_help
 3592                    || editor_settings.show_signature_help_after_edits)
 3593            {
 3594                this.show_signature_help(&ShowSignatureHelp, cx);
 3595            }
 3596
 3597            let trigger_in_words = !had_active_inline_completion;
 3598            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3599            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3600            this.refresh_inline_completion(true, false, cx);
 3601        });
 3602    }
 3603
 3604    fn find_possible_emoji_shortcode_at_position(
 3605        snapshot: &MultiBufferSnapshot,
 3606        position: Point,
 3607    ) -> Option<String> {
 3608        let mut chars = Vec::new();
 3609        let mut found_colon = false;
 3610        for char in snapshot.reversed_chars_at(position).take(100) {
 3611            // Found a possible emoji shortcode in the middle of the buffer
 3612            if found_colon {
 3613                if char.is_whitespace() {
 3614                    chars.reverse();
 3615                    return Some(chars.iter().collect());
 3616                }
 3617                // If the previous character is not a whitespace, we are in the middle of a word
 3618                // and we only want to complete the shortcode if the word is made up of other emojis
 3619                let mut containing_word = String::new();
 3620                for ch in snapshot
 3621                    .reversed_chars_at(position)
 3622                    .skip(chars.len() + 1)
 3623                    .take(100)
 3624                {
 3625                    if ch.is_whitespace() {
 3626                        break;
 3627                    }
 3628                    containing_word.push(ch);
 3629                }
 3630                let containing_word = containing_word.chars().rev().collect::<String>();
 3631                if util::word_consists_of_emojis(containing_word.as_str()) {
 3632                    chars.reverse();
 3633                    return Some(chars.iter().collect());
 3634                }
 3635            }
 3636
 3637            if char.is_whitespace() || !char.is_ascii() {
 3638                return None;
 3639            }
 3640            if char == ':' {
 3641                found_colon = true;
 3642            } else {
 3643                chars.push(char);
 3644            }
 3645        }
 3646        // Found a possible emoji shortcode at the beginning of the buffer
 3647        chars.reverse();
 3648        Some(chars.iter().collect())
 3649    }
 3650
 3651    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3652        self.transact(cx, |this, cx| {
 3653            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3654                let selections = this.selections.all::<usize>(cx);
 3655                let multi_buffer = this.buffer.read(cx);
 3656                let buffer = multi_buffer.snapshot(cx);
 3657                selections
 3658                    .iter()
 3659                    .map(|selection| {
 3660                        let start_point = selection.start.to_point(&buffer);
 3661                        let mut indent =
 3662                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3663                        indent.len = cmp::min(indent.len, start_point.column);
 3664                        let start = selection.start;
 3665                        let end = selection.end;
 3666                        let selection_is_empty = start == end;
 3667                        let language_scope = buffer.language_scope_at(start);
 3668                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3669                            &language_scope
 3670                        {
 3671                            let leading_whitespace_len = buffer
 3672                                .reversed_chars_at(start)
 3673                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3674                                .map(|c| c.len_utf8())
 3675                                .sum::<usize>();
 3676
 3677                            let trailing_whitespace_len = buffer
 3678                                .chars_at(end)
 3679                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3680                                .map(|c| c.len_utf8())
 3681                                .sum::<usize>();
 3682
 3683                            let insert_extra_newline =
 3684                                language.brackets().any(|(pair, enabled)| {
 3685                                    let pair_start = pair.start.trim_end();
 3686                                    let pair_end = pair.end.trim_start();
 3687
 3688                                    enabled
 3689                                        && pair.newline
 3690                                        && buffer.contains_str_at(
 3691                                            end + trailing_whitespace_len,
 3692                                            pair_end,
 3693                                        )
 3694                                        && buffer.contains_str_at(
 3695                                            (start - leading_whitespace_len)
 3696                                                .saturating_sub(pair_start.len()),
 3697                                            pair_start,
 3698                                        )
 3699                                });
 3700
 3701                            // Comment extension on newline is allowed only for cursor selections
 3702                            let comment_delimiter = maybe!({
 3703                                if !selection_is_empty {
 3704                                    return None;
 3705                                }
 3706
 3707                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3708                                    return None;
 3709                                }
 3710
 3711                                let delimiters = language.line_comment_prefixes();
 3712                                let max_len_of_delimiter =
 3713                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3714                                let (snapshot, range) =
 3715                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3716
 3717                                let mut index_of_first_non_whitespace = 0;
 3718                                let comment_candidate = snapshot
 3719                                    .chars_for_range(range)
 3720                                    .skip_while(|c| {
 3721                                        let should_skip = c.is_whitespace();
 3722                                        if should_skip {
 3723                                            index_of_first_non_whitespace += 1;
 3724                                        }
 3725                                        should_skip
 3726                                    })
 3727                                    .take(max_len_of_delimiter)
 3728                                    .collect::<String>();
 3729                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3730                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3731                                })?;
 3732                                let cursor_is_placed_after_comment_marker =
 3733                                    index_of_first_non_whitespace + comment_prefix.len()
 3734                                        <= start_point.column as usize;
 3735                                if cursor_is_placed_after_comment_marker {
 3736                                    Some(comment_prefix.clone())
 3737                                } else {
 3738                                    None
 3739                                }
 3740                            });
 3741                            (comment_delimiter, insert_extra_newline)
 3742                        } else {
 3743                            (None, false)
 3744                        };
 3745
 3746                        let capacity_for_delimiter = comment_delimiter
 3747                            .as_deref()
 3748                            .map(str::len)
 3749                            .unwrap_or_default();
 3750                        let mut new_text =
 3751                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3752                        new_text.push('\n');
 3753                        new_text.extend(indent.chars());
 3754                        if let Some(delimiter) = &comment_delimiter {
 3755                            new_text.push_str(delimiter);
 3756                        }
 3757                        if insert_extra_newline {
 3758                            new_text = new_text.repeat(2);
 3759                        }
 3760
 3761                        let anchor = buffer.anchor_after(end);
 3762                        let new_selection = selection.map(|_| anchor);
 3763                        (
 3764                            (start..end, new_text),
 3765                            (insert_extra_newline, new_selection),
 3766                        )
 3767                    })
 3768                    .unzip()
 3769            };
 3770
 3771            this.edit_with_autoindent(edits, cx);
 3772            let buffer = this.buffer.read(cx).snapshot(cx);
 3773            let new_selections = selection_fixup_info
 3774                .into_iter()
 3775                .map(|(extra_newline_inserted, new_selection)| {
 3776                    let mut cursor = new_selection.end.to_point(&buffer);
 3777                    if extra_newline_inserted {
 3778                        cursor.row -= 1;
 3779                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3780                    }
 3781                    new_selection.map(|_| cursor)
 3782                })
 3783                .collect();
 3784
 3785            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3786            this.refresh_inline_completion(true, false, cx);
 3787        });
 3788    }
 3789
 3790    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3791        let buffer = self.buffer.read(cx);
 3792        let snapshot = buffer.snapshot(cx);
 3793
 3794        let mut edits = Vec::new();
 3795        let mut rows = Vec::new();
 3796
 3797        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3798            let cursor = selection.head();
 3799            let row = cursor.row;
 3800
 3801            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3802
 3803            let newline = "\n".to_string();
 3804            edits.push((start_of_line..start_of_line, newline));
 3805
 3806            rows.push(row + rows_inserted as u32);
 3807        }
 3808
 3809        self.transact(cx, |editor, cx| {
 3810            editor.edit(edits, cx);
 3811
 3812            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3813                let mut index = 0;
 3814                s.move_cursors_with(|map, _, _| {
 3815                    let row = rows[index];
 3816                    index += 1;
 3817
 3818                    let point = Point::new(row, 0);
 3819                    let boundary = map.next_line_boundary(point).1;
 3820                    let clipped = map.clip_point(boundary, Bias::Left);
 3821
 3822                    (clipped, SelectionGoal::None)
 3823                });
 3824            });
 3825
 3826            let mut indent_edits = Vec::new();
 3827            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3828            for row in rows {
 3829                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3830                for (row, indent) in indents {
 3831                    if indent.len == 0 {
 3832                        continue;
 3833                    }
 3834
 3835                    let text = match indent.kind {
 3836                        IndentKind::Space => " ".repeat(indent.len as usize),
 3837                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3838                    };
 3839                    let point = Point::new(row.0, 0);
 3840                    indent_edits.push((point..point, text));
 3841                }
 3842            }
 3843            editor.edit(indent_edits, cx);
 3844        });
 3845    }
 3846
 3847    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3848        let buffer = self.buffer.read(cx);
 3849        let snapshot = buffer.snapshot(cx);
 3850
 3851        let mut edits = Vec::new();
 3852        let mut rows = Vec::new();
 3853        let mut rows_inserted = 0;
 3854
 3855        for selection in self.selections.all_adjusted(cx) {
 3856            let cursor = selection.head();
 3857            let row = cursor.row;
 3858
 3859            let point = Point::new(row + 1, 0);
 3860            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3861
 3862            let newline = "\n".to_string();
 3863            edits.push((start_of_line..start_of_line, newline));
 3864
 3865            rows_inserted += 1;
 3866            rows.push(row + rows_inserted);
 3867        }
 3868
 3869        self.transact(cx, |editor, cx| {
 3870            editor.edit(edits, cx);
 3871
 3872            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3873                let mut index = 0;
 3874                s.move_cursors_with(|map, _, _| {
 3875                    let row = rows[index];
 3876                    index += 1;
 3877
 3878                    let point = Point::new(row, 0);
 3879                    let boundary = map.next_line_boundary(point).1;
 3880                    let clipped = map.clip_point(boundary, Bias::Left);
 3881
 3882                    (clipped, SelectionGoal::None)
 3883                });
 3884            });
 3885
 3886            let mut indent_edits = Vec::new();
 3887            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3888            for row in rows {
 3889                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3890                for (row, indent) in indents {
 3891                    if indent.len == 0 {
 3892                        continue;
 3893                    }
 3894
 3895                    let text = match indent.kind {
 3896                        IndentKind::Space => " ".repeat(indent.len as usize),
 3897                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3898                    };
 3899                    let point = Point::new(row.0, 0);
 3900                    indent_edits.push((point..point, text));
 3901                }
 3902            }
 3903            editor.edit(indent_edits, cx);
 3904        });
 3905    }
 3906
 3907    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3908        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3909            original_indent_columns: Vec::new(),
 3910        });
 3911        self.insert_with_autoindent_mode(text, autoindent, cx);
 3912    }
 3913
 3914    fn insert_with_autoindent_mode(
 3915        &mut self,
 3916        text: &str,
 3917        autoindent_mode: Option<AutoindentMode>,
 3918        cx: &mut ViewContext<Self>,
 3919    ) {
 3920        if self.read_only(cx) {
 3921            return;
 3922        }
 3923
 3924        let text: Arc<str> = text.into();
 3925        self.transact(cx, |this, cx| {
 3926            let old_selections = this.selections.all_adjusted(cx);
 3927            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3928                let anchors = {
 3929                    let snapshot = buffer.read(cx);
 3930                    old_selections
 3931                        .iter()
 3932                        .map(|s| {
 3933                            let anchor = snapshot.anchor_after(s.head());
 3934                            s.map(|_| anchor)
 3935                        })
 3936                        .collect::<Vec<_>>()
 3937                };
 3938                buffer.edit(
 3939                    old_selections
 3940                        .iter()
 3941                        .map(|s| (s.start..s.end, text.clone())),
 3942                    autoindent_mode,
 3943                    cx,
 3944                );
 3945                anchors
 3946            });
 3947
 3948            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3949                s.select_anchors(selection_anchors);
 3950            })
 3951        });
 3952    }
 3953
 3954    fn trigger_completion_on_input(
 3955        &mut self,
 3956        text: &str,
 3957        trigger_in_words: bool,
 3958        cx: &mut ViewContext<Self>,
 3959    ) {
 3960        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3961            self.show_completions(
 3962                &ShowCompletions {
 3963                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3964                },
 3965                cx,
 3966            );
 3967        } else {
 3968            self.hide_context_menu(cx);
 3969        }
 3970    }
 3971
 3972    fn is_completion_trigger(
 3973        &self,
 3974        text: &str,
 3975        trigger_in_words: bool,
 3976        cx: &mut ViewContext<Self>,
 3977    ) -> bool {
 3978        let position = self.selections.newest_anchor().head();
 3979        let multibuffer = self.buffer.read(cx);
 3980        let Some(buffer) = position
 3981            .buffer_id
 3982            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3983        else {
 3984            return false;
 3985        };
 3986
 3987        if let Some(completion_provider) = &self.completion_provider {
 3988            completion_provider.is_completion_trigger(
 3989                &buffer,
 3990                position.text_anchor,
 3991                text,
 3992                trigger_in_words,
 3993                cx,
 3994            )
 3995        } else {
 3996            false
 3997        }
 3998    }
 3999
 4000    /// If any empty selections is touching the start of its innermost containing autoclose
 4001    /// region, expand it to select the brackets.
 4002    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4003        let selections = self.selections.all::<usize>(cx);
 4004        let buffer = self.buffer.read(cx).read(cx);
 4005        let new_selections = self
 4006            .selections_with_autoclose_regions(selections, &buffer)
 4007            .map(|(mut selection, region)| {
 4008                if !selection.is_empty() {
 4009                    return selection;
 4010                }
 4011
 4012                if let Some(region) = region {
 4013                    let mut range = region.range.to_offset(&buffer);
 4014                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4015                        range.start -= region.pair.start.len();
 4016                        if buffer.contains_str_at(range.start, &region.pair.start)
 4017                            && buffer.contains_str_at(range.end, &region.pair.end)
 4018                        {
 4019                            range.end += region.pair.end.len();
 4020                            selection.start = range.start;
 4021                            selection.end = range.end;
 4022
 4023                            return selection;
 4024                        }
 4025                    }
 4026                }
 4027
 4028                let always_treat_brackets_as_autoclosed = buffer
 4029                    .settings_at(selection.start, cx)
 4030                    .always_treat_brackets_as_autoclosed;
 4031
 4032                if !always_treat_brackets_as_autoclosed {
 4033                    return selection;
 4034                }
 4035
 4036                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4037                    for (pair, enabled) in scope.brackets() {
 4038                        if !enabled || !pair.close {
 4039                            continue;
 4040                        }
 4041
 4042                        if buffer.contains_str_at(selection.start, &pair.end) {
 4043                            let pair_start_len = pair.start.len();
 4044                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 4045                            {
 4046                                selection.start -= pair_start_len;
 4047                                selection.end += pair.end.len();
 4048
 4049                                return selection;
 4050                            }
 4051                        }
 4052                    }
 4053                }
 4054
 4055                selection
 4056            })
 4057            .collect();
 4058
 4059        drop(buffer);
 4060        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4061    }
 4062
 4063    /// Iterate the given selections, and for each one, find the smallest surrounding
 4064    /// autoclose region. This uses the ordering of the selections and the autoclose
 4065    /// regions to avoid repeated comparisons.
 4066    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4067        &'a self,
 4068        selections: impl IntoIterator<Item = Selection<D>>,
 4069        buffer: &'a MultiBufferSnapshot,
 4070    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4071        let mut i = 0;
 4072        let mut regions = self.autoclose_regions.as_slice();
 4073        selections.into_iter().map(move |selection| {
 4074            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4075
 4076            let mut enclosing = None;
 4077            while let Some(pair_state) = regions.get(i) {
 4078                if pair_state.range.end.to_offset(buffer) < range.start {
 4079                    regions = &regions[i + 1..];
 4080                    i = 0;
 4081                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4082                    break;
 4083                } else {
 4084                    if pair_state.selection_id == selection.id {
 4085                        enclosing = Some(pair_state);
 4086                    }
 4087                    i += 1;
 4088                }
 4089            }
 4090
 4091            (selection, enclosing)
 4092        })
 4093    }
 4094
 4095    /// Remove any autoclose regions that no longer contain their selection.
 4096    fn invalidate_autoclose_regions(
 4097        &mut self,
 4098        mut selections: &[Selection<Anchor>],
 4099        buffer: &MultiBufferSnapshot,
 4100    ) {
 4101        self.autoclose_regions.retain(|state| {
 4102            let mut i = 0;
 4103            while let Some(selection) = selections.get(i) {
 4104                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4105                    selections = &selections[1..];
 4106                    continue;
 4107                }
 4108                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4109                    break;
 4110                }
 4111                if selection.id == state.selection_id {
 4112                    return true;
 4113                } else {
 4114                    i += 1;
 4115                }
 4116            }
 4117            false
 4118        });
 4119    }
 4120
 4121    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4122        let offset = position.to_offset(buffer);
 4123        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4124        if offset > word_range.start && kind == Some(CharKind::Word) {
 4125            Some(
 4126                buffer
 4127                    .text_for_range(word_range.start..offset)
 4128                    .collect::<String>(),
 4129            )
 4130        } else {
 4131            None
 4132        }
 4133    }
 4134
 4135    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4136        self.refresh_inlay_hints(
 4137            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4138            cx,
 4139        );
 4140    }
 4141
 4142    pub fn inlay_hints_enabled(&self) -> bool {
 4143        self.inlay_hint_cache.enabled
 4144    }
 4145
 4146    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4147        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4148            return;
 4149        }
 4150
 4151        let reason_description = reason.description();
 4152        let ignore_debounce = matches!(
 4153            reason,
 4154            InlayHintRefreshReason::SettingsChange(_)
 4155                | InlayHintRefreshReason::Toggle(_)
 4156                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4157        );
 4158        let (invalidate_cache, required_languages) = match reason {
 4159            InlayHintRefreshReason::Toggle(enabled) => {
 4160                self.inlay_hint_cache.enabled = enabled;
 4161                if enabled {
 4162                    (InvalidationStrategy::RefreshRequested, None)
 4163                } else {
 4164                    self.inlay_hint_cache.clear();
 4165                    self.splice_inlays(
 4166                        self.visible_inlay_hints(cx)
 4167                            .iter()
 4168                            .map(|inlay| inlay.id)
 4169                            .collect(),
 4170                        Vec::new(),
 4171                        cx,
 4172                    );
 4173                    return;
 4174                }
 4175            }
 4176            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4177                match self.inlay_hint_cache.update_settings(
 4178                    &self.buffer,
 4179                    new_settings,
 4180                    self.visible_inlay_hints(cx),
 4181                    cx,
 4182                ) {
 4183                    ControlFlow::Break(Some(InlaySplice {
 4184                        to_remove,
 4185                        to_insert,
 4186                    })) => {
 4187                        self.splice_inlays(to_remove, to_insert, cx);
 4188                        return;
 4189                    }
 4190                    ControlFlow::Break(None) => return,
 4191                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4192                }
 4193            }
 4194            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4195                if let Some(InlaySplice {
 4196                    to_remove,
 4197                    to_insert,
 4198                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4199                {
 4200                    self.splice_inlays(to_remove, to_insert, cx);
 4201                }
 4202                return;
 4203            }
 4204            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4205            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4206                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4207            }
 4208            InlayHintRefreshReason::RefreshRequested => {
 4209                (InvalidationStrategy::RefreshRequested, None)
 4210            }
 4211        };
 4212
 4213        if let Some(InlaySplice {
 4214            to_remove,
 4215            to_insert,
 4216        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4217            reason_description,
 4218            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4219            invalidate_cache,
 4220            ignore_debounce,
 4221            cx,
 4222        ) {
 4223            self.splice_inlays(to_remove, to_insert, cx);
 4224        }
 4225    }
 4226
 4227    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4228        self.display_map
 4229            .read(cx)
 4230            .current_inlays()
 4231            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4232            .cloned()
 4233            .collect()
 4234    }
 4235
 4236    pub fn excerpts_for_inlay_hints_query(
 4237        &self,
 4238        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4239        cx: &mut ViewContext<Editor>,
 4240    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4241        let Some(project) = self.project.as_ref() else {
 4242            return HashMap::default();
 4243        };
 4244        let project = project.read(cx);
 4245        let multi_buffer = self.buffer().read(cx);
 4246        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4247        let multi_buffer_visible_start = self
 4248            .scroll_manager
 4249            .anchor()
 4250            .anchor
 4251            .to_point(&multi_buffer_snapshot);
 4252        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4253            multi_buffer_visible_start
 4254                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4255            Bias::Left,
 4256        );
 4257        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4258        multi_buffer
 4259            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4260            .into_iter()
 4261            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4262            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4263                let buffer = buffer_handle.read(cx);
 4264                let buffer_file = project::File::from_dyn(buffer.file())?;
 4265                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4266                let worktree_entry = buffer_worktree
 4267                    .read(cx)
 4268                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4269                if worktree_entry.is_ignored {
 4270                    return None;
 4271                }
 4272
 4273                let language = buffer.language()?;
 4274                if let Some(restrict_to_languages) = restrict_to_languages {
 4275                    if !restrict_to_languages.contains(language) {
 4276                        return None;
 4277                    }
 4278                }
 4279                Some((
 4280                    excerpt_id,
 4281                    (
 4282                        buffer_handle,
 4283                        buffer.version().clone(),
 4284                        excerpt_visible_range,
 4285                    ),
 4286                ))
 4287            })
 4288            .collect()
 4289    }
 4290
 4291    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4292        TextLayoutDetails {
 4293            text_system: cx.text_system().clone(),
 4294            editor_style: self.style.clone().unwrap(),
 4295            rem_size: cx.rem_size(),
 4296            scroll_anchor: self.scroll_manager.anchor(),
 4297            visible_rows: self.visible_line_count(),
 4298            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4299        }
 4300    }
 4301
 4302    fn splice_inlays(
 4303        &self,
 4304        to_remove: Vec<InlayId>,
 4305        to_insert: Vec<Inlay>,
 4306        cx: &mut ViewContext<Self>,
 4307    ) {
 4308        self.display_map.update(cx, |display_map, cx| {
 4309            display_map.splice_inlays(to_remove, to_insert, cx);
 4310        });
 4311        cx.notify();
 4312    }
 4313
 4314    fn trigger_on_type_formatting(
 4315        &self,
 4316        input: String,
 4317        cx: &mut ViewContext<Self>,
 4318    ) -> Option<Task<Result<()>>> {
 4319        if input.len() != 1 {
 4320            return None;
 4321        }
 4322
 4323        let project = self.project.as_ref()?;
 4324        let position = self.selections.newest_anchor().head();
 4325        let (buffer, buffer_position) = self
 4326            .buffer
 4327            .read(cx)
 4328            .text_anchor_for_position(position, cx)?;
 4329
 4330        let settings = language_settings::language_settings(
 4331            buffer
 4332                .read(cx)
 4333                .language_at(buffer_position)
 4334                .map(|l| l.name()),
 4335            buffer.read(cx).file(),
 4336            cx,
 4337        );
 4338        if !settings.use_on_type_format {
 4339            return None;
 4340        }
 4341
 4342        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4343        // hence we do LSP request & edit on host side only — add formats to host's history.
 4344        let push_to_lsp_host_history = true;
 4345        // If this is not the host, append its history with new edits.
 4346        let push_to_client_history = project.read(cx).is_via_collab();
 4347
 4348        let on_type_formatting = project.update(cx, |project, cx| {
 4349            project.on_type_format(
 4350                buffer.clone(),
 4351                buffer_position,
 4352                input,
 4353                push_to_lsp_host_history,
 4354                cx,
 4355            )
 4356        });
 4357        Some(cx.spawn(|editor, mut cx| async move {
 4358            if let Some(transaction) = on_type_formatting.await? {
 4359                if push_to_client_history {
 4360                    buffer
 4361                        .update(&mut cx, |buffer, _| {
 4362                            buffer.push_transaction(transaction, Instant::now());
 4363                        })
 4364                        .ok();
 4365                }
 4366                editor.update(&mut cx, |editor, cx| {
 4367                    editor.refresh_document_highlights(cx);
 4368                })?;
 4369            }
 4370            Ok(())
 4371        }))
 4372    }
 4373
 4374    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4375        if self.pending_rename.is_some() {
 4376            return;
 4377        }
 4378
 4379        let Some(provider) = self.completion_provider.as_ref() else {
 4380            return;
 4381        };
 4382
 4383        let position = self.selections.newest_anchor().head();
 4384        let (buffer, buffer_position) =
 4385            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4386                output
 4387            } else {
 4388                return;
 4389            };
 4390
 4391        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4392        let is_followup_invoke = {
 4393            let context_menu_state = self.context_menu.read();
 4394            matches!(
 4395                context_menu_state.deref(),
 4396                Some(ContextMenu::Completions(_))
 4397            )
 4398        };
 4399        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4400            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4401            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4402                CompletionTriggerKind::TRIGGER_CHARACTER
 4403            }
 4404
 4405            _ => CompletionTriggerKind::INVOKED,
 4406        };
 4407        let completion_context = CompletionContext {
 4408            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4409                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4410                    Some(String::from(trigger))
 4411                } else {
 4412                    None
 4413                }
 4414            }),
 4415            trigger_kind,
 4416        };
 4417        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4418        let sort_completions = provider.sort_completions();
 4419
 4420        let id = post_inc(&mut self.next_completion_id);
 4421        let task = cx.spawn(|this, mut cx| {
 4422            async move {
 4423                this.update(&mut cx, |this, _| {
 4424                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4425                })?;
 4426                let completions = completions.await.log_err();
 4427                let menu = if let Some(completions) = completions {
 4428                    let mut menu = CompletionsMenu {
 4429                        id,
 4430                        sort_completions,
 4431                        initial_position: position,
 4432                        match_candidates: completions
 4433                            .iter()
 4434                            .enumerate()
 4435                            .map(|(id, completion)| {
 4436                                StringMatchCandidate::new(
 4437                                    id,
 4438                                    completion.label.text[completion.label.filter_range.clone()]
 4439                                        .into(),
 4440                                )
 4441                            })
 4442                            .collect(),
 4443                        buffer: buffer.clone(),
 4444                        completions: Arc::new(RwLock::new(completions.into())),
 4445                        matches: Vec::new().into(),
 4446                        selected_item: 0,
 4447                        scroll_handle: UniformListScrollHandle::new(),
 4448                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4449                            DebouncedDelay::new(),
 4450                        )),
 4451                    };
 4452                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4453                        .await;
 4454
 4455                    if menu.matches.is_empty() {
 4456                        None
 4457                    } else {
 4458                        this.update(&mut cx, |editor, cx| {
 4459                            let completions = menu.completions.clone();
 4460                            let matches = menu.matches.clone();
 4461
 4462                            let delay_ms = EditorSettings::get_global(cx)
 4463                                .completion_documentation_secondary_query_debounce;
 4464                            let delay = Duration::from_millis(delay_ms);
 4465                            editor
 4466                                .completion_documentation_pre_resolve_debounce
 4467                                .fire_new(delay, cx, |editor, cx| {
 4468                                    CompletionsMenu::pre_resolve_completion_documentation(
 4469                                        buffer,
 4470                                        completions,
 4471                                        matches,
 4472                                        editor,
 4473                                        cx,
 4474                                    )
 4475                                });
 4476                        })
 4477                        .ok();
 4478                        Some(menu)
 4479                    }
 4480                } else {
 4481                    None
 4482                };
 4483
 4484                this.update(&mut cx, |this, cx| {
 4485                    let mut context_menu = this.context_menu.write();
 4486                    match context_menu.as_ref() {
 4487                        None => {}
 4488
 4489                        Some(ContextMenu::Completions(prev_menu)) => {
 4490                            if prev_menu.id > id {
 4491                                return;
 4492                            }
 4493                        }
 4494
 4495                        _ => return,
 4496                    }
 4497
 4498                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4499                        let menu = menu.unwrap();
 4500                        *context_menu = Some(ContextMenu::Completions(menu));
 4501                        drop(context_menu);
 4502                        this.discard_inline_completion(false, cx);
 4503                        cx.notify();
 4504                    } else if this.completion_tasks.len() <= 1 {
 4505                        // If there are no more completion tasks and the last menu was
 4506                        // empty, we should hide it. If it was already hidden, we should
 4507                        // also show the copilot completion when available.
 4508                        drop(context_menu);
 4509                        if this.hide_context_menu(cx).is_none() {
 4510                            this.update_visible_inline_completion(cx);
 4511                        }
 4512                    }
 4513                })?;
 4514
 4515                Ok::<_, anyhow::Error>(())
 4516            }
 4517            .log_err()
 4518        });
 4519
 4520        self.completion_tasks.push((id, task));
 4521    }
 4522
 4523    pub fn confirm_completion(
 4524        &mut self,
 4525        action: &ConfirmCompletion,
 4526        cx: &mut ViewContext<Self>,
 4527    ) -> Option<Task<Result<()>>> {
 4528        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4529    }
 4530
 4531    pub fn compose_completion(
 4532        &mut self,
 4533        action: &ComposeCompletion,
 4534        cx: &mut ViewContext<Self>,
 4535    ) -> Option<Task<Result<()>>> {
 4536        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4537    }
 4538
 4539    fn do_completion(
 4540        &mut self,
 4541        item_ix: Option<usize>,
 4542        intent: CompletionIntent,
 4543        cx: &mut ViewContext<Editor>,
 4544    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4545        use language::ToOffset as _;
 4546
 4547        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4548            menu
 4549        } else {
 4550            return None;
 4551        };
 4552
 4553        let mat = completions_menu
 4554            .matches
 4555            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4556        let buffer_handle = completions_menu.buffer;
 4557        let completions = completions_menu.completions.read();
 4558        let completion = completions.get(mat.candidate_id)?;
 4559        cx.stop_propagation();
 4560
 4561        let snippet;
 4562        let text;
 4563
 4564        if completion.is_snippet() {
 4565            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4566            text = snippet.as_ref().unwrap().text.clone();
 4567        } else {
 4568            snippet = None;
 4569            text = completion.new_text.clone();
 4570        };
 4571        let selections = self.selections.all::<usize>(cx);
 4572        let buffer = buffer_handle.read(cx);
 4573        let old_range = completion.old_range.to_offset(buffer);
 4574        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4575
 4576        let newest_selection = self.selections.newest_anchor();
 4577        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4578            return None;
 4579        }
 4580
 4581        let lookbehind = newest_selection
 4582            .start
 4583            .text_anchor
 4584            .to_offset(buffer)
 4585            .saturating_sub(old_range.start);
 4586        let lookahead = old_range
 4587            .end
 4588            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4589        let mut common_prefix_len = old_text
 4590            .bytes()
 4591            .zip(text.bytes())
 4592            .take_while(|(a, b)| a == b)
 4593            .count();
 4594
 4595        let snapshot = self.buffer.read(cx).snapshot(cx);
 4596        let mut range_to_replace: Option<Range<isize>> = None;
 4597        let mut ranges = Vec::new();
 4598        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4599        for selection in &selections {
 4600            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4601                let start = selection.start.saturating_sub(lookbehind);
 4602                let end = selection.end + lookahead;
 4603                if selection.id == newest_selection.id {
 4604                    range_to_replace = Some(
 4605                        ((start + common_prefix_len) as isize - selection.start as isize)
 4606                            ..(end as isize - selection.start as isize),
 4607                    );
 4608                }
 4609                ranges.push(start + common_prefix_len..end);
 4610            } else {
 4611                common_prefix_len = 0;
 4612                ranges.clear();
 4613                ranges.extend(selections.iter().map(|s| {
 4614                    if s.id == newest_selection.id {
 4615                        range_to_replace = Some(
 4616                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4617                                - selection.start as isize
 4618                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4619                                    - selection.start as isize,
 4620                        );
 4621                        old_range.clone()
 4622                    } else {
 4623                        s.start..s.end
 4624                    }
 4625                }));
 4626                break;
 4627            }
 4628            if !self.linked_edit_ranges.is_empty() {
 4629                let start_anchor = snapshot.anchor_before(selection.head());
 4630                let end_anchor = snapshot.anchor_after(selection.tail());
 4631                if let Some(ranges) = self
 4632                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4633                {
 4634                    for (buffer, edits) in ranges {
 4635                        linked_edits.entry(buffer.clone()).or_default().extend(
 4636                            edits
 4637                                .into_iter()
 4638                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4639                        );
 4640                    }
 4641                }
 4642            }
 4643        }
 4644        let text = &text[common_prefix_len..];
 4645
 4646        cx.emit(EditorEvent::InputHandled {
 4647            utf16_range_to_replace: range_to_replace,
 4648            text: text.into(),
 4649        });
 4650
 4651        self.transact(cx, |this, cx| {
 4652            if let Some(mut snippet) = snippet {
 4653                snippet.text = text.to_string();
 4654                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4655                    tabstop.start -= common_prefix_len as isize;
 4656                    tabstop.end -= common_prefix_len as isize;
 4657                }
 4658
 4659                this.insert_snippet(&ranges, snippet, cx).log_err();
 4660            } else {
 4661                this.buffer.update(cx, |buffer, cx| {
 4662                    buffer.edit(
 4663                        ranges.iter().map(|range| (range.clone(), text)),
 4664                        this.autoindent_mode.clone(),
 4665                        cx,
 4666                    );
 4667                });
 4668            }
 4669            for (buffer, edits) in linked_edits {
 4670                buffer.update(cx, |buffer, cx| {
 4671                    let snapshot = buffer.snapshot();
 4672                    let edits = edits
 4673                        .into_iter()
 4674                        .map(|(range, text)| {
 4675                            use text::ToPoint as TP;
 4676                            let end_point = TP::to_point(&range.end, &snapshot);
 4677                            let start_point = TP::to_point(&range.start, &snapshot);
 4678                            (start_point..end_point, text)
 4679                        })
 4680                        .sorted_by_key(|(range, _)| range.start)
 4681                        .collect::<Vec<_>>();
 4682                    buffer.edit(edits, None, cx);
 4683                })
 4684            }
 4685
 4686            this.refresh_inline_completion(true, false, cx);
 4687        });
 4688
 4689        let show_new_completions_on_confirm = completion
 4690            .confirm
 4691            .as_ref()
 4692            .map_or(false, |confirm| confirm(intent, cx));
 4693        if show_new_completions_on_confirm {
 4694            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4695        }
 4696
 4697        let provider = self.completion_provider.as_ref()?;
 4698        let apply_edits = provider.apply_additional_edits_for_completion(
 4699            buffer_handle,
 4700            completion.clone(),
 4701            true,
 4702            cx,
 4703        );
 4704
 4705        let editor_settings = EditorSettings::get_global(cx);
 4706        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4707            // After the code completion is finished, users often want to know what signatures are needed.
 4708            // so we should automatically call signature_help
 4709            self.show_signature_help(&ShowSignatureHelp, cx);
 4710        }
 4711
 4712        Some(cx.foreground_executor().spawn(async move {
 4713            apply_edits.await?;
 4714            Ok(())
 4715        }))
 4716    }
 4717
 4718    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4719        let mut context_menu = self.context_menu.write();
 4720        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4721            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4722                // Toggle if we're selecting the same one
 4723                *context_menu = None;
 4724                cx.notify();
 4725                return;
 4726            } else {
 4727                // Otherwise, clear it and start a new one
 4728                *context_menu = None;
 4729                cx.notify();
 4730            }
 4731        }
 4732        drop(context_menu);
 4733        let snapshot = self.snapshot(cx);
 4734        let deployed_from_indicator = action.deployed_from_indicator;
 4735        let mut task = self.code_actions_task.take();
 4736        let action = action.clone();
 4737        cx.spawn(|editor, mut cx| async move {
 4738            while let Some(prev_task) = task {
 4739                prev_task.await.log_err();
 4740                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4741            }
 4742
 4743            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4744                if editor.focus_handle.is_focused(cx) {
 4745                    let multibuffer_point = action
 4746                        .deployed_from_indicator
 4747                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4748                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4749                    let (buffer, buffer_row) = snapshot
 4750                        .buffer_snapshot
 4751                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4752                        .and_then(|(buffer_snapshot, range)| {
 4753                            editor
 4754                                .buffer
 4755                                .read(cx)
 4756                                .buffer(buffer_snapshot.remote_id())
 4757                                .map(|buffer| (buffer, range.start.row))
 4758                        })?;
 4759                    let (_, code_actions) = editor
 4760                        .available_code_actions
 4761                        .clone()
 4762                        .and_then(|(location, code_actions)| {
 4763                            let snapshot = location.buffer.read(cx).snapshot();
 4764                            let point_range = location.range.to_point(&snapshot);
 4765                            let point_range = point_range.start.row..=point_range.end.row;
 4766                            if point_range.contains(&buffer_row) {
 4767                                Some((location, code_actions))
 4768                            } else {
 4769                                None
 4770                            }
 4771                        })
 4772                        .unzip();
 4773                    let buffer_id = buffer.read(cx).remote_id();
 4774                    let tasks = editor
 4775                        .tasks
 4776                        .get(&(buffer_id, buffer_row))
 4777                        .map(|t| Arc::new(t.to_owned()));
 4778                    if tasks.is_none() && code_actions.is_none() {
 4779                        return None;
 4780                    }
 4781
 4782                    editor.completion_tasks.clear();
 4783                    editor.discard_inline_completion(false, cx);
 4784                    let task_context =
 4785                        tasks
 4786                            .as_ref()
 4787                            .zip(editor.project.clone())
 4788                            .map(|(tasks, project)| {
 4789                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4790                            });
 4791
 4792                    Some(cx.spawn(|editor, mut cx| async move {
 4793                        let task_context = match task_context {
 4794                            Some(task_context) => task_context.await,
 4795                            None => None,
 4796                        };
 4797                        let resolved_tasks =
 4798                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4799                                Arc::new(ResolvedTasks {
 4800                                    templates: tasks.resolve(&task_context).collect(),
 4801                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4802                                        multibuffer_point.row,
 4803                                        tasks.column,
 4804                                    )),
 4805                                })
 4806                            });
 4807                        let spawn_straight_away = resolved_tasks
 4808                            .as_ref()
 4809                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4810                            && code_actions
 4811                                .as_ref()
 4812                                .map_or(true, |actions| actions.is_empty());
 4813                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4814                            *editor.context_menu.write() =
 4815                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4816                                    buffer,
 4817                                    actions: CodeActionContents {
 4818                                        tasks: resolved_tasks,
 4819                                        actions: code_actions,
 4820                                    },
 4821                                    selected_item: Default::default(),
 4822                                    scroll_handle: UniformListScrollHandle::default(),
 4823                                    deployed_from_indicator,
 4824                                }));
 4825                            if spawn_straight_away {
 4826                                if let Some(task) = editor.confirm_code_action(
 4827                                    &ConfirmCodeAction { item_ix: Some(0) },
 4828                                    cx,
 4829                                ) {
 4830                                    cx.notify();
 4831                                    return task;
 4832                                }
 4833                            }
 4834                            cx.notify();
 4835                            Task::ready(Ok(()))
 4836                        }) {
 4837                            task.await
 4838                        } else {
 4839                            Ok(())
 4840                        }
 4841                    }))
 4842                } else {
 4843                    Some(Task::ready(Ok(())))
 4844                }
 4845            })?;
 4846            if let Some(task) = spawned_test_task {
 4847                task.await?;
 4848            }
 4849
 4850            Ok::<_, anyhow::Error>(())
 4851        })
 4852        .detach_and_log_err(cx);
 4853    }
 4854
 4855    pub fn confirm_code_action(
 4856        &mut self,
 4857        action: &ConfirmCodeAction,
 4858        cx: &mut ViewContext<Self>,
 4859    ) -> Option<Task<Result<()>>> {
 4860        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4861            menu
 4862        } else {
 4863            return None;
 4864        };
 4865        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4866        let action = actions_menu.actions.get(action_ix)?;
 4867        let title = action.label();
 4868        let buffer = actions_menu.buffer;
 4869        let workspace = self.workspace()?;
 4870
 4871        match action {
 4872            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4873                workspace.update(cx, |workspace, cx| {
 4874                    workspace::tasks::schedule_resolved_task(
 4875                        workspace,
 4876                        task_source_kind,
 4877                        resolved_task,
 4878                        false,
 4879                        cx,
 4880                    );
 4881
 4882                    Some(Task::ready(Ok(())))
 4883                })
 4884            }
 4885            CodeActionsItem::CodeAction {
 4886                excerpt_id,
 4887                action,
 4888                provider,
 4889            } => {
 4890                let apply_code_action =
 4891                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4892                let workspace = workspace.downgrade();
 4893                Some(cx.spawn(|editor, cx| async move {
 4894                    let project_transaction = apply_code_action.await?;
 4895                    Self::open_project_transaction(
 4896                        &editor,
 4897                        workspace,
 4898                        project_transaction,
 4899                        title,
 4900                        cx,
 4901                    )
 4902                    .await
 4903                }))
 4904            }
 4905        }
 4906    }
 4907
 4908    pub async fn open_project_transaction(
 4909        this: &WeakView<Editor>,
 4910        workspace: WeakView<Workspace>,
 4911        transaction: ProjectTransaction,
 4912        title: String,
 4913        mut cx: AsyncWindowContext,
 4914    ) -> Result<()> {
 4915        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4916        cx.update(|cx| {
 4917            entries.sort_unstable_by_key(|(buffer, _)| {
 4918                buffer.read(cx).file().map(|f| f.path().clone())
 4919            });
 4920        })?;
 4921
 4922        // If the project transaction's edits are all contained within this editor, then
 4923        // avoid opening a new editor to display them.
 4924
 4925        if let Some((buffer, transaction)) = entries.first() {
 4926            if entries.len() == 1 {
 4927                let excerpt = this.update(&mut cx, |editor, cx| {
 4928                    editor
 4929                        .buffer()
 4930                        .read(cx)
 4931                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4932                })?;
 4933                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4934                    if excerpted_buffer == *buffer {
 4935                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4936                            let excerpt_range = excerpt_range.to_offset(buffer);
 4937                            buffer
 4938                                .edited_ranges_for_transaction::<usize>(transaction)
 4939                                .all(|range| {
 4940                                    excerpt_range.start <= range.start
 4941                                        && excerpt_range.end >= range.end
 4942                                })
 4943                        })?;
 4944
 4945                        if all_edits_within_excerpt {
 4946                            return Ok(());
 4947                        }
 4948                    }
 4949                }
 4950            }
 4951        } else {
 4952            return Ok(());
 4953        }
 4954
 4955        let mut ranges_to_highlight = Vec::new();
 4956        let excerpt_buffer = cx.new_model(|cx| {
 4957            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4958            for (buffer_handle, transaction) in &entries {
 4959                let buffer = buffer_handle.read(cx);
 4960                ranges_to_highlight.extend(
 4961                    multibuffer.push_excerpts_with_context_lines(
 4962                        buffer_handle.clone(),
 4963                        buffer
 4964                            .edited_ranges_for_transaction::<usize>(transaction)
 4965                            .collect(),
 4966                        DEFAULT_MULTIBUFFER_CONTEXT,
 4967                        cx,
 4968                    ),
 4969                );
 4970            }
 4971            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4972            multibuffer
 4973        })?;
 4974
 4975        workspace.update(&mut cx, |workspace, cx| {
 4976            let project = workspace.project().clone();
 4977            let editor =
 4978                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4979            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4980            editor.update(cx, |editor, cx| {
 4981                editor.highlight_background::<Self>(
 4982                    &ranges_to_highlight,
 4983                    |theme| theme.editor_highlighted_line_background,
 4984                    cx,
 4985                );
 4986            });
 4987        })?;
 4988
 4989        Ok(())
 4990    }
 4991
 4992    pub fn clear_code_action_providers(&mut self) {
 4993        self.code_action_providers.clear();
 4994        self.available_code_actions.take();
 4995    }
 4996
 4997    pub fn push_code_action_provider(
 4998        &mut self,
 4999        provider: Arc<dyn CodeActionProvider>,
 5000        cx: &mut ViewContext<Self>,
 5001    ) {
 5002        self.code_action_providers.push(provider);
 5003        self.refresh_code_actions(cx);
 5004    }
 5005
 5006    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5007        let buffer = self.buffer.read(cx);
 5008        let newest_selection = self.selections.newest_anchor().clone();
 5009        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5010        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5011        if start_buffer != end_buffer {
 5012            return None;
 5013        }
 5014
 5015        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5016            cx.background_executor()
 5017                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5018                .await;
 5019
 5020            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5021                let providers = this.code_action_providers.clone();
 5022                let tasks = this
 5023                    .code_action_providers
 5024                    .iter()
 5025                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5026                    .collect::<Vec<_>>();
 5027                (providers, tasks)
 5028            })?;
 5029
 5030            let mut actions = Vec::new();
 5031            for (provider, provider_actions) in
 5032                providers.into_iter().zip(future::join_all(tasks).await)
 5033            {
 5034                if let Some(provider_actions) = provider_actions.log_err() {
 5035                    actions.extend(provider_actions.into_iter().map(|action| {
 5036                        AvailableCodeAction {
 5037                            excerpt_id: newest_selection.start.excerpt_id,
 5038                            action,
 5039                            provider: provider.clone(),
 5040                        }
 5041                    }));
 5042                }
 5043            }
 5044
 5045            this.update(&mut cx, |this, cx| {
 5046                this.available_code_actions = if actions.is_empty() {
 5047                    None
 5048                } else {
 5049                    Some((
 5050                        Location {
 5051                            buffer: start_buffer,
 5052                            range: start..end,
 5053                        },
 5054                        actions.into(),
 5055                    ))
 5056                };
 5057                cx.notify();
 5058            })
 5059        }));
 5060        None
 5061    }
 5062
 5063    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5064        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5065            self.show_git_blame_inline = false;
 5066
 5067            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5068                cx.background_executor().timer(delay).await;
 5069
 5070                this.update(&mut cx, |this, cx| {
 5071                    this.show_git_blame_inline = true;
 5072                    cx.notify();
 5073                })
 5074                .log_err();
 5075            }));
 5076        }
 5077    }
 5078
 5079    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5080        if self.pending_rename.is_some() {
 5081            return None;
 5082        }
 5083
 5084        let provider = self.semantics_provider.clone()?;
 5085        let buffer = self.buffer.read(cx);
 5086        let newest_selection = self.selections.newest_anchor().clone();
 5087        let cursor_position = newest_selection.head();
 5088        let (cursor_buffer, cursor_buffer_position) =
 5089            buffer.text_anchor_for_position(cursor_position, cx)?;
 5090        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5091        if cursor_buffer != tail_buffer {
 5092            return None;
 5093        }
 5094
 5095        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5096            cx.background_executor()
 5097                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5098                .await;
 5099
 5100            let highlights = if let Some(highlights) = cx
 5101                .update(|cx| {
 5102                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5103                })
 5104                .ok()
 5105                .flatten()
 5106            {
 5107                highlights.await.log_err()
 5108            } else {
 5109                None
 5110            };
 5111
 5112            if let Some(highlights) = highlights {
 5113                this.update(&mut cx, |this, cx| {
 5114                    if this.pending_rename.is_some() {
 5115                        return;
 5116                    }
 5117
 5118                    let buffer_id = cursor_position.buffer_id;
 5119                    let buffer = this.buffer.read(cx);
 5120                    if !buffer
 5121                        .text_anchor_for_position(cursor_position, cx)
 5122                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5123                    {
 5124                        return;
 5125                    }
 5126
 5127                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5128                    let mut write_ranges = Vec::new();
 5129                    let mut read_ranges = Vec::new();
 5130                    for highlight in highlights {
 5131                        for (excerpt_id, excerpt_range) in
 5132                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5133                        {
 5134                            let start = highlight
 5135                                .range
 5136                                .start
 5137                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5138                            let end = highlight
 5139                                .range
 5140                                .end
 5141                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5142                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5143                                continue;
 5144                            }
 5145
 5146                            let range = Anchor {
 5147                                buffer_id,
 5148                                excerpt_id,
 5149                                text_anchor: start,
 5150                            }..Anchor {
 5151                                buffer_id,
 5152                                excerpt_id,
 5153                                text_anchor: end,
 5154                            };
 5155                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5156                                write_ranges.push(range);
 5157                            } else {
 5158                                read_ranges.push(range);
 5159                            }
 5160                        }
 5161                    }
 5162
 5163                    this.highlight_background::<DocumentHighlightRead>(
 5164                        &read_ranges,
 5165                        |theme| theme.editor_document_highlight_read_background,
 5166                        cx,
 5167                    );
 5168                    this.highlight_background::<DocumentHighlightWrite>(
 5169                        &write_ranges,
 5170                        |theme| theme.editor_document_highlight_write_background,
 5171                        cx,
 5172                    );
 5173                    cx.notify();
 5174                })
 5175                .log_err();
 5176            }
 5177        }));
 5178        None
 5179    }
 5180
 5181    pub fn refresh_inline_completion(
 5182        &mut self,
 5183        debounce: bool,
 5184        user_requested: bool,
 5185        cx: &mut ViewContext<Self>,
 5186    ) -> Option<()> {
 5187        let provider = self.inline_completion_provider()?;
 5188        let cursor = self.selections.newest_anchor().head();
 5189        let (buffer, cursor_buffer_position) =
 5190            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5191
 5192        if !user_requested
 5193            && (!self.enable_inline_completions
 5194                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5195        {
 5196            self.discard_inline_completion(false, cx);
 5197            return None;
 5198        }
 5199
 5200        self.update_visible_inline_completion(cx);
 5201        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5202        Some(())
 5203    }
 5204
 5205    fn cycle_inline_completion(
 5206        &mut self,
 5207        direction: Direction,
 5208        cx: &mut ViewContext<Self>,
 5209    ) -> Option<()> {
 5210        let provider = self.inline_completion_provider()?;
 5211        let cursor = self.selections.newest_anchor().head();
 5212        let (buffer, cursor_buffer_position) =
 5213            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5214        if !self.enable_inline_completions
 5215            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5216        {
 5217            return None;
 5218        }
 5219
 5220        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5221        self.update_visible_inline_completion(cx);
 5222
 5223        Some(())
 5224    }
 5225
 5226    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5227        if !self.has_active_inline_completion(cx) {
 5228            self.refresh_inline_completion(false, true, cx);
 5229            return;
 5230        }
 5231
 5232        self.update_visible_inline_completion(cx);
 5233    }
 5234
 5235    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5236        self.show_cursor_names(cx);
 5237    }
 5238
 5239    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5240        self.show_cursor_names = true;
 5241        cx.notify();
 5242        cx.spawn(|this, mut cx| async move {
 5243            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5244            this.update(&mut cx, |this, cx| {
 5245                this.show_cursor_names = false;
 5246                cx.notify()
 5247            })
 5248            .ok()
 5249        })
 5250        .detach();
 5251    }
 5252
 5253    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5254        if self.has_active_inline_completion(cx) {
 5255            self.cycle_inline_completion(Direction::Next, cx);
 5256        } else {
 5257            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5258            if is_copilot_disabled {
 5259                cx.propagate();
 5260            }
 5261        }
 5262    }
 5263
 5264    pub fn previous_inline_completion(
 5265        &mut self,
 5266        _: &PreviousInlineCompletion,
 5267        cx: &mut ViewContext<Self>,
 5268    ) {
 5269        if self.has_active_inline_completion(cx) {
 5270            self.cycle_inline_completion(Direction::Prev, cx);
 5271        } else {
 5272            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5273            if is_copilot_disabled {
 5274                cx.propagate();
 5275            }
 5276        }
 5277    }
 5278
 5279    pub fn accept_inline_completion(
 5280        &mut self,
 5281        _: &AcceptInlineCompletion,
 5282        cx: &mut ViewContext<Self>,
 5283    ) {
 5284        let Some(completion) = self.take_active_inline_completion(cx) else {
 5285            return;
 5286        };
 5287        if let Some(provider) = self.inline_completion_provider() {
 5288            provider.accept(cx);
 5289        }
 5290
 5291        cx.emit(EditorEvent::InputHandled {
 5292            utf16_range_to_replace: None,
 5293            text: completion.text.to_string().into(),
 5294        });
 5295
 5296        if let Some(range) = completion.delete_range {
 5297            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5298        }
 5299        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5300        self.refresh_inline_completion(true, true, cx);
 5301        cx.notify();
 5302    }
 5303
 5304    pub fn accept_partial_inline_completion(
 5305        &mut self,
 5306        _: &AcceptPartialInlineCompletion,
 5307        cx: &mut ViewContext<Self>,
 5308    ) {
 5309        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5310            if let Some(completion) = self.take_active_inline_completion(cx) {
 5311                let mut partial_completion = completion
 5312                    .text
 5313                    .chars()
 5314                    .by_ref()
 5315                    .take_while(|c| c.is_alphabetic())
 5316                    .collect::<String>();
 5317                if partial_completion.is_empty() {
 5318                    partial_completion = completion
 5319                        .text
 5320                        .chars()
 5321                        .by_ref()
 5322                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5323                        .collect::<String>();
 5324                }
 5325
 5326                cx.emit(EditorEvent::InputHandled {
 5327                    utf16_range_to_replace: None,
 5328                    text: partial_completion.clone().into(),
 5329                });
 5330
 5331                if let Some(range) = completion.delete_range {
 5332                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5333                }
 5334                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5335
 5336                self.refresh_inline_completion(true, true, cx);
 5337                cx.notify();
 5338            }
 5339        }
 5340    }
 5341
 5342    fn discard_inline_completion(
 5343        &mut self,
 5344        should_report_inline_completion_event: bool,
 5345        cx: &mut ViewContext<Self>,
 5346    ) -> bool {
 5347        if let Some(provider) = self.inline_completion_provider() {
 5348            provider.discard(should_report_inline_completion_event, cx);
 5349        }
 5350
 5351        self.take_active_inline_completion(cx).is_some()
 5352    }
 5353
 5354    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5355        if let Some(completion) = self.active_inline_completion.as_ref() {
 5356            let buffer = self.buffer.read(cx).read(cx);
 5357            completion.position.is_valid(&buffer)
 5358        } else {
 5359            false
 5360        }
 5361    }
 5362
 5363    fn take_active_inline_completion(
 5364        &mut self,
 5365        cx: &mut ViewContext<Self>,
 5366    ) -> Option<CompletionState> {
 5367        let completion = self.active_inline_completion.take()?;
 5368        let render_inlay_ids = completion.render_inlay_ids.clone();
 5369        self.display_map.update(cx, |map, cx| {
 5370            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5371        });
 5372        let buffer = self.buffer.read(cx).read(cx);
 5373
 5374        if completion.position.is_valid(&buffer) {
 5375            Some(completion)
 5376        } else {
 5377            None
 5378        }
 5379    }
 5380
 5381    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5382        let selection = self.selections.newest_anchor();
 5383        let cursor = selection.head();
 5384
 5385        let excerpt_id = cursor.excerpt_id;
 5386
 5387        if self.context_menu.read().is_none()
 5388            && self.completion_tasks.is_empty()
 5389            && selection.start == selection.end
 5390        {
 5391            if let Some(provider) = self.inline_completion_provider() {
 5392                if let Some((buffer, cursor_buffer_position)) =
 5393                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5394                {
 5395                    if let Some(proposal) =
 5396                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5397                    {
 5398                        let mut to_remove = Vec::new();
 5399                        if let Some(completion) = self.active_inline_completion.take() {
 5400                            to_remove.extend(completion.render_inlay_ids.iter());
 5401                        }
 5402
 5403                        let to_add = proposal
 5404                            .inlays
 5405                            .iter()
 5406                            .filter_map(|inlay| {
 5407                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5408                                let id = post_inc(&mut self.next_inlay_id);
 5409                                match inlay {
 5410                                    InlayProposal::Hint(position, hint) => {
 5411                                        let position =
 5412                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5413                                        Some(Inlay::hint(id, position, hint))
 5414                                    }
 5415                                    InlayProposal::Suggestion(position, text) => {
 5416                                        let position =
 5417                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5418                                        Some(Inlay::suggestion(id, position, text.clone()))
 5419                                    }
 5420                                }
 5421                            })
 5422                            .collect_vec();
 5423
 5424                        self.active_inline_completion = Some(CompletionState {
 5425                            position: cursor,
 5426                            text: proposal.text,
 5427                            delete_range: proposal.delete_range.and_then(|range| {
 5428                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5429                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5430                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5431                                Some(start?..end?)
 5432                            }),
 5433                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5434                        });
 5435
 5436                        self.display_map
 5437                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5438
 5439                        cx.notify();
 5440                        return;
 5441                    }
 5442                }
 5443            }
 5444        }
 5445
 5446        self.discard_inline_completion(false, cx);
 5447    }
 5448
 5449    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5450        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5451    }
 5452
 5453    fn render_code_actions_indicator(
 5454        &self,
 5455        _style: &EditorStyle,
 5456        row: DisplayRow,
 5457        is_active: bool,
 5458        cx: &mut ViewContext<Self>,
 5459    ) -> Option<IconButton> {
 5460        if self.available_code_actions.is_some() {
 5461            Some(
 5462                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5463                    .shape(ui::IconButtonShape::Square)
 5464                    .icon_size(IconSize::XSmall)
 5465                    .icon_color(Color::Muted)
 5466                    .selected(is_active)
 5467                    .tooltip({
 5468                        let focus_handle = self.focus_handle.clone();
 5469                        move |cx| {
 5470                            Tooltip::for_action_in(
 5471                                "Toggle Code Actions",
 5472                                &ToggleCodeActions {
 5473                                    deployed_from_indicator: None,
 5474                                },
 5475                                &focus_handle,
 5476                                cx,
 5477                            )
 5478                        }
 5479                    })
 5480                    .on_click(cx.listener(move |editor, _e, cx| {
 5481                        editor.focus(cx);
 5482                        editor.toggle_code_actions(
 5483                            &ToggleCodeActions {
 5484                                deployed_from_indicator: Some(row),
 5485                            },
 5486                            cx,
 5487                        );
 5488                    })),
 5489            )
 5490        } else {
 5491            None
 5492        }
 5493    }
 5494
 5495    fn clear_tasks(&mut self) {
 5496        self.tasks.clear()
 5497    }
 5498
 5499    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5500        if self.tasks.insert(key, value).is_some() {
 5501            // This case should hopefully be rare, but just in case...
 5502            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5503        }
 5504    }
 5505
 5506    fn build_tasks_context(
 5507        project: &Model<Project>,
 5508        buffer: &Model<Buffer>,
 5509        buffer_row: u32,
 5510        tasks: &Arc<RunnableTasks>,
 5511        cx: &mut ViewContext<Self>,
 5512    ) -> Task<Option<task::TaskContext>> {
 5513        let position = Point::new(buffer_row, tasks.column);
 5514        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5515        let location = Location {
 5516            buffer: buffer.clone(),
 5517            range: range_start..range_start,
 5518        };
 5519        // Fill in the environmental variables from the tree-sitter captures
 5520        let mut captured_task_variables = TaskVariables::default();
 5521        for (capture_name, value) in tasks.extra_variables.clone() {
 5522            captured_task_variables.insert(
 5523                task::VariableName::Custom(capture_name.into()),
 5524                value.clone(),
 5525            );
 5526        }
 5527        project.update(cx, |project, cx| {
 5528            project.task_store().update(cx, |task_store, cx| {
 5529                task_store.task_context_for_location(captured_task_variables, location, cx)
 5530            })
 5531        })
 5532    }
 5533
 5534    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5535        let Some((workspace, _)) = self.workspace.clone() else {
 5536            return;
 5537        };
 5538        let Some(project) = self.project.clone() else {
 5539            return;
 5540        };
 5541
 5542        // Try to find a closest, enclosing node using tree-sitter that has a
 5543        // task
 5544        let Some((buffer, buffer_row, tasks)) = self
 5545            .find_enclosing_node_task(cx)
 5546            // Or find the task that's closest in row-distance.
 5547            .or_else(|| self.find_closest_task(cx))
 5548        else {
 5549            return;
 5550        };
 5551
 5552        let reveal_strategy = action.reveal;
 5553        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5554        cx.spawn(|_, mut cx| async move {
 5555            let context = task_context.await?;
 5556            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5557
 5558            let resolved = resolved_task.resolved.as_mut()?;
 5559            resolved.reveal = reveal_strategy;
 5560
 5561            workspace
 5562                .update(&mut cx, |workspace, cx| {
 5563                    workspace::tasks::schedule_resolved_task(
 5564                        workspace,
 5565                        task_source_kind,
 5566                        resolved_task,
 5567                        false,
 5568                        cx,
 5569                    );
 5570                })
 5571                .ok()
 5572        })
 5573        .detach();
 5574    }
 5575
 5576    fn find_closest_task(
 5577        &mut self,
 5578        cx: &mut ViewContext<Self>,
 5579    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5580        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5581
 5582        let ((buffer_id, row), tasks) = self
 5583            .tasks
 5584            .iter()
 5585            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5586
 5587        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5588        let tasks = Arc::new(tasks.to_owned());
 5589        Some((buffer, *row, tasks))
 5590    }
 5591
 5592    fn find_enclosing_node_task(
 5593        &mut self,
 5594        cx: &mut ViewContext<Self>,
 5595    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5596        let snapshot = self.buffer.read(cx).snapshot(cx);
 5597        let offset = self.selections.newest::<usize>(cx).head();
 5598        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5599        let buffer_id = excerpt.buffer().remote_id();
 5600
 5601        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5602        let mut cursor = layer.node().walk();
 5603
 5604        while cursor.goto_first_child_for_byte(offset).is_some() {
 5605            if cursor.node().end_byte() == offset {
 5606                cursor.goto_next_sibling();
 5607            }
 5608        }
 5609
 5610        // Ascend to the smallest ancestor that contains the range and has a task.
 5611        loop {
 5612            let node = cursor.node();
 5613            let node_range = node.byte_range();
 5614            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5615
 5616            // Check if this node contains our offset
 5617            if node_range.start <= offset && node_range.end >= offset {
 5618                // If it contains offset, check for task
 5619                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5620                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5621                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5622                }
 5623            }
 5624
 5625            if !cursor.goto_parent() {
 5626                break;
 5627            }
 5628        }
 5629        None
 5630    }
 5631
 5632    fn render_run_indicator(
 5633        &self,
 5634        _style: &EditorStyle,
 5635        is_active: bool,
 5636        row: DisplayRow,
 5637        cx: &mut ViewContext<Self>,
 5638    ) -> IconButton {
 5639        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5640            .shape(ui::IconButtonShape::Square)
 5641            .icon_size(IconSize::XSmall)
 5642            .icon_color(Color::Muted)
 5643            .selected(is_active)
 5644            .on_click(cx.listener(move |editor, _e, cx| {
 5645                editor.focus(cx);
 5646                editor.toggle_code_actions(
 5647                    &ToggleCodeActions {
 5648                        deployed_from_indicator: Some(row),
 5649                    },
 5650                    cx,
 5651                );
 5652            }))
 5653    }
 5654
 5655    pub fn context_menu_visible(&self) -> bool {
 5656        self.context_menu
 5657            .read()
 5658            .as_ref()
 5659            .map_or(false, |menu| menu.visible())
 5660    }
 5661
 5662    fn render_context_menu(
 5663        &self,
 5664        cursor_position: DisplayPoint,
 5665        style: &EditorStyle,
 5666        max_height: Pixels,
 5667        cx: &mut ViewContext<Editor>,
 5668    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5669        self.context_menu.read().as_ref().map(|menu| {
 5670            menu.render(
 5671                cursor_position,
 5672                style,
 5673                max_height,
 5674                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5675                cx,
 5676            )
 5677        })
 5678    }
 5679
 5680    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5681        cx.notify();
 5682        self.completion_tasks.clear();
 5683        let context_menu = self.context_menu.write().take();
 5684        if context_menu.is_some() {
 5685            self.update_visible_inline_completion(cx);
 5686        }
 5687        context_menu
 5688    }
 5689
 5690    pub fn insert_snippet(
 5691        &mut self,
 5692        insertion_ranges: &[Range<usize>],
 5693        snippet: Snippet,
 5694        cx: &mut ViewContext<Self>,
 5695    ) -> Result<()> {
 5696        struct Tabstop<T> {
 5697            is_end_tabstop: bool,
 5698            ranges: Vec<Range<T>>,
 5699        }
 5700
 5701        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5702            let snippet_text: Arc<str> = snippet.text.clone().into();
 5703            buffer.edit(
 5704                insertion_ranges
 5705                    .iter()
 5706                    .cloned()
 5707                    .map(|range| (range, snippet_text.clone())),
 5708                Some(AutoindentMode::EachLine),
 5709                cx,
 5710            );
 5711
 5712            let snapshot = &*buffer.read(cx);
 5713            let snippet = &snippet;
 5714            snippet
 5715                .tabstops
 5716                .iter()
 5717                .map(|tabstop| {
 5718                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5719                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5720                    });
 5721                    let mut tabstop_ranges = tabstop
 5722                        .iter()
 5723                        .flat_map(|tabstop_range| {
 5724                            let mut delta = 0_isize;
 5725                            insertion_ranges.iter().map(move |insertion_range| {
 5726                                let insertion_start = insertion_range.start as isize + delta;
 5727                                delta +=
 5728                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5729
 5730                                let start = ((insertion_start + tabstop_range.start) as usize)
 5731                                    .min(snapshot.len());
 5732                                let end = ((insertion_start + tabstop_range.end) as usize)
 5733                                    .min(snapshot.len());
 5734                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5735                            })
 5736                        })
 5737                        .collect::<Vec<_>>();
 5738                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5739
 5740                    Tabstop {
 5741                        is_end_tabstop,
 5742                        ranges: tabstop_ranges,
 5743                    }
 5744                })
 5745                .collect::<Vec<_>>()
 5746        });
 5747        if let Some(tabstop) = tabstops.first() {
 5748            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5749                s.select_ranges(tabstop.ranges.iter().cloned());
 5750            });
 5751
 5752            // If we're already at the last tabstop and it's at the end of the snippet,
 5753            // we're done, we don't need to keep the state around.
 5754            if !tabstop.is_end_tabstop {
 5755                let ranges = tabstops
 5756                    .into_iter()
 5757                    .map(|tabstop| tabstop.ranges)
 5758                    .collect::<Vec<_>>();
 5759                self.snippet_stack.push(SnippetState {
 5760                    active_index: 0,
 5761                    ranges,
 5762                });
 5763            }
 5764
 5765            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5766            if self.autoclose_regions.is_empty() {
 5767                let snapshot = self.buffer.read(cx).snapshot(cx);
 5768                for selection in &mut self.selections.all::<Point>(cx) {
 5769                    let selection_head = selection.head();
 5770                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5771                        continue;
 5772                    };
 5773
 5774                    let mut bracket_pair = None;
 5775                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5776                    let prev_chars = snapshot
 5777                        .reversed_chars_at(selection_head)
 5778                        .collect::<String>();
 5779                    for (pair, enabled) in scope.brackets() {
 5780                        if enabled
 5781                            && pair.close
 5782                            && prev_chars.starts_with(pair.start.as_str())
 5783                            && next_chars.starts_with(pair.end.as_str())
 5784                        {
 5785                            bracket_pair = Some(pair.clone());
 5786                            break;
 5787                        }
 5788                    }
 5789                    if let Some(pair) = bracket_pair {
 5790                        let start = snapshot.anchor_after(selection_head);
 5791                        let end = snapshot.anchor_after(selection_head);
 5792                        self.autoclose_regions.push(AutocloseRegion {
 5793                            selection_id: selection.id,
 5794                            range: start..end,
 5795                            pair,
 5796                        });
 5797                    }
 5798                }
 5799            }
 5800        }
 5801        Ok(())
 5802    }
 5803
 5804    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5805        self.move_to_snippet_tabstop(Bias::Right, cx)
 5806    }
 5807
 5808    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5809        self.move_to_snippet_tabstop(Bias::Left, cx)
 5810    }
 5811
 5812    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5813        if let Some(mut snippet) = self.snippet_stack.pop() {
 5814            match bias {
 5815                Bias::Left => {
 5816                    if snippet.active_index > 0 {
 5817                        snippet.active_index -= 1;
 5818                    } else {
 5819                        self.snippet_stack.push(snippet);
 5820                        return false;
 5821                    }
 5822                }
 5823                Bias::Right => {
 5824                    if snippet.active_index + 1 < snippet.ranges.len() {
 5825                        snippet.active_index += 1;
 5826                    } else {
 5827                        self.snippet_stack.push(snippet);
 5828                        return false;
 5829                    }
 5830                }
 5831            }
 5832            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5833                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5834                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5835                });
 5836                // If snippet state is not at the last tabstop, push it back on the stack
 5837                if snippet.active_index + 1 < snippet.ranges.len() {
 5838                    self.snippet_stack.push(snippet);
 5839                }
 5840                return true;
 5841            }
 5842        }
 5843
 5844        false
 5845    }
 5846
 5847    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5848        self.transact(cx, |this, cx| {
 5849            this.select_all(&SelectAll, cx);
 5850            this.insert("", cx);
 5851        });
 5852    }
 5853
 5854    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5855        self.transact(cx, |this, cx| {
 5856            this.select_autoclose_pair(cx);
 5857            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5858            if !this.linked_edit_ranges.is_empty() {
 5859                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5860                let snapshot = this.buffer.read(cx).snapshot(cx);
 5861
 5862                for selection in selections.iter() {
 5863                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5864                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5865                    if selection_start.buffer_id != selection_end.buffer_id {
 5866                        continue;
 5867                    }
 5868                    if let Some(ranges) =
 5869                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5870                    {
 5871                        for (buffer, entries) in ranges {
 5872                            linked_ranges.entry(buffer).or_default().extend(entries);
 5873                        }
 5874                    }
 5875                }
 5876            }
 5877
 5878            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5879            if !this.selections.line_mode {
 5880                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5881                for selection in &mut selections {
 5882                    if selection.is_empty() {
 5883                        let old_head = selection.head();
 5884                        let mut new_head =
 5885                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5886                                .to_point(&display_map);
 5887                        if let Some((buffer, line_buffer_range)) = display_map
 5888                            .buffer_snapshot
 5889                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5890                        {
 5891                            let indent_size =
 5892                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5893                            let indent_len = match indent_size.kind {
 5894                                IndentKind::Space => {
 5895                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5896                                }
 5897                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5898                            };
 5899                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5900                                let indent_len = indent_len.get();
 5901                                new_head = cmp::min(
 5902                                    new_head,
 5903                                    MultiBufferPoint::new(
 5904                                        old_head.row,
 5905                                        ((old_head.column - 1) / indent_len) * indent_len,
 5906                                    ),
 5907                                );
 5908                            }
 5909                        }
 5910
 5911                        selection.set_head(new_head, SelectionGoal::None);
 5912                    }
 5913                }
 5914            }
 5915
 5916            this.signature_help_state.set_backspace_pressed(true);
 5917            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5918            this.insert("", cx);
 5919            let empty_str: Arc<str> = Arc::from("");
 5920            for (buffer, edits) in linked_ranges {
 5921                let snapshot = buffer.read(cx).snapshot();
 5922                use text::ToPoint as TP;
 5923
 5924                let edits = edits
 5925                    .into_iter()
 5926                    .map(|range| {
 5927                        let end_point = TP::to_point(&range.end, &snapshot);
 5928                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5929
 5930                        if end_point == start_point {
 5931                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5932                                .saturating_sub(1);
 5933                            start_point = TP::to_point(&offset, &snapshot);
 5934                        };
 5935
 5936                        (start_point..end_point, empty_str.clone())
 5937                    })
 5938                    .sorted_by_key(|(range, _)| range.start)
 5939                    .collect::<Vec<_>>();
 5940                buffer.update(cx, |this, cx| {
 5941                    this.edit(edits, None, cx);
 5942                })
 5943            }
 5944            this.refresh_inline_completion(true, false, cx);
 5945            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5946        });
 5947    }
 5948
 5949    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5950        self.transact(cx, |this, cx| {
 5951            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5952                let line_mode = s.line_mode;
 5953                s.move_with(|map, selection| {
 5954                    if selection.is_empty() && !line_mode {
 5955                        let cursor = movement::right(map, selection.head());
 5956                        selection.end = cursor;
 5957                        selection.reversed = true;
 5958                        selection.goal = SelectionGoal::None;
 5959                    }
 5960                })
 5961            });
 5962            this.insert("", cx);
 5963            this.refresh_inline_completion(true, false, cx);
 5964        });
 5965    }
 5966
 5967    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5968        if self.move_to_prev_snippet_tabstop(cx) {
 5969            return;
 5970        }
 5971
 5972        self.outdent(&Outdent, cx);
 5973    }
 5974
 5975    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5976        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5977            return;
 5978        }
 5979
 5980        let mut selections = self.selections.all_adjusted(cx);
 5981        let buffer = self.buffer.read(cx);
 5982        let snapshot = buffer.snapshot(cx);
 5983        let rows_iter = selections.iter().map(|s| s.head().row);
 5984        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5985
 5986        let mut edits = Vec::new();
 5987        let mut prev_edited_row = 0;
 5988        let mut row_delta = 0;
 5989        for selection in &mut selections {
 5990            if selection.start.row != prev_edited_row {
 5991                row_delta = 0;
 5992            }
 5993            prev_edited_row = selection.end.row;
 5994
 5995            // If the selection is non-empty, then increase the indentation of the selected lines.
 5996            if !selection.is_empty() {
 5997                row_delta =
 5998                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5999                continue;
 6000            }
 6001
 6002            // If the selection is empty and the cursor is in the leading whitespace before the
 6003            // suggested indentation, then auto-indent the line.
 6004            let cursor = selection.head();
 6005            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6006            if let Some(suggested_indent) =
 6007                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6008            {
 6009                if cursor.column < suggested_indent.len
 6010                    && cursor.column <= current_indent.len
 6011                    && current_indent.len <= suggested_indent.len
 6012                {
 6013                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6014                    selection.end = selection.start;
 6015                    if row_delta == 0 {
 6016                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6017                            cursor.row,
 6018                            current_indent,
 6019                            suggested_indent,
 6020                        ));
 6021                        row_delta = suggested_indent.len - current_indent.len;
 6022                    }
 6023                    continue;
 6024                }
 6025            }
 6026
 6027            // Otherwise, insert a hard or soft tab.
 6028            let settings = buffer.settings_at(cursor, cx);
 6029            let tab_size = if settings.hard_tabs {
 6030                IndentSize::tab()
 6031            } else {
 6032                let tab_size = settings.tab_size.get();
 6033                let char_column = snapshot
 6034                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6035                    .flat_map(str::chars)
 6036                    .count()
 6037                    + row_delta as usize;
 6038                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6039                IndentSize::spaces(chars_to_next_tab_stop)
 6040            };
 6041            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6042            selection.end = selection.start;
 6043            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6044            row_delta += tab_size.len;
 6045        }
 6046
 6047        self.transact(cx, |this, cx| {
 6048            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6049            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6050            this.refresh_inline_completion(true, false, cx);
 6051        });
 6052    }
 6053
 6054    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6055        if self.read_only(cx) {
 6056            return;
 6057        }
 6058        let mut selections = self.selections.all::<Point>(cx);
 6059        let mut prev_edited_row = 0;
 6060        let mut row_delta = 0;
 6061        let mut edits = Vec::new();
 6062        let buffer = self.buffer.read(cx);
 6063        let snapshot = buffer.snapshot(cx);
 6064        for selection in &mut selections {
 6065            if selection.start.row != prev_edited_row {
 6066                row_delta = 0;
 6067            }
 6068            prev_edited_row = selection.end.row;
 6069
 6070            row_delta =
 6071                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6072        }
 6073
 6074        self.transact(cx, |this, cx| {
 6075            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6076            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6077        });
 6078    }
 6079
 6080    fn indent_selection(
 6081        buffer: &MultiBuffer,
 6082        snapshot: &MultiBufferSnapshot,
 6083        selection: &mut Selection<Point>,
 6084        edits: &mut Vec<(Range<Point>, String)>,
 6085        delta_for_start_row: u32,
 6086        cx: &AppContext,
 6087    ) -> u32 {
 6088        let settings = buffer.settings_at(selection.start, cx);
 6089        let tab_size = settings.tab_size.get();
 6090        let indent_kind = if settings.hard_tabs {
 6091            IndentKind::Tab
 6092        } else {
 6093            IndentKind::Space
 6094        };
 6095        let mut start_row = selection.start.row;
 6096        let mut end_row = selection.end.row + 1;
 6097
 6098        // If a selection ends at the beginning of a line, don't indent
 6099        // that last line.
 6100        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6101            end_row -= 1;
 6102        }
 6103
 6104        // Avoid re-indenting a row that has already been indented by a
 6105        // previous selection, but still update this selection's column
 6106        // to reflect that indentation.
 6107        if delta_for_start_row > 0 {
 6108            start_row += 1;
 6109            selection.start.column += delta_for_start_row;
 6110            if selection.end.row == selection.start.row {
 6111                selection.end.column += delta_for_start_row;
 6112            }
 6113        }
 6114
 6115        let mut delta_for_end_row = 0;
 6116        let has_multiple_rows = start_row + 1 != end_row;
 6117        for row in start_row..end_row {
 6118            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6119            let indent_delta = match (current_indent.kind, indent_kind) {
 6120                (IndentKind::Space, IndentKind::Space) => {
 6121                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6122                    IndentSize::spaces(columns_to_next_tab_stop)
 6123                }
 6124                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6125                (_, IndentKind::Tab) => IndentSize::tab(),
 6126            };
 6127
 6128            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6129                0
 6130            } else {
 6131                selection.start.column
 6132            };
 6133            let row_start = Point::new(row, start);
 6134            edits.push((
 6135                row_start..row_start,
 6136                indent_delta.chars().collect::<String>(),
 6137            ));
 6138
 6139            // Update this selection's endpoints to reflect the indentation.
 6140            if row == selection.start.row {
 6141                selection.start.column += indent_delta.len;
 6142            }
 6143            if row == selection.end.row {
 6144                selection.end.column += indent_delta.len;
 6145                delta_for_end_row = indent_delta.len;
 6146            }
 6147        }
 6148
 6149        if selection.start.row == selection.end.row {
 6150            delta_for_start_row + delta_for_end_row
 6151        } else {
 6152            delta_for_end_row
 6153        }
 6154    }
 6155
 6156    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6157        if self.read_only(cx) {
 6158            return;
 6159        }
 6160        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6161        let selections = self.selections.all::<Point>(cx);
 6162        let mut deletion_ranges = Vec::new();
 6163        let mut last_outdent = None;
 6164        {
 6165            let buffer = self.buffer.read(cx);
 6166            let snapshot = buffer.snapshot(cx);
 6167            for selection in &selections {
 6168                let settings = buffer.settings_at(selection.start, cx);
 6169                let tab_size = settings.tab_size.get();
 6170                let mut rows = selection.spanned_rows(false, &display_map);
 6171
 6172                // Avoid re-outdenting a row that has already been outdented by a
 6173                // previous selection.
 6174                if let Some(last_row) = last_outdent {
 6175                    if last_row == rows.start {
 6176                        rows.start = rows.start.next_row();
 6177                    }
 6178                }
 6179                let has_multiple_rows = rows.len() > 1;
 6180                for row in rows.iter_rows() {
 6181                    let indent_size = snapshot.indent_size_for_line(row);
 6182                    if indent_size.len > 0 {
 6183                        let deletion_len = match indent_size.kind {
 6184                            IndentKind::Space => {
 6185                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6186                                if columns_to_prev_tab_stop == 0 {
 6187                                    tab_size
 6188                                } else {
 6189                                    columns_to_prev_tab_stop
 6190                                }
 6191                            }
 6192                            IndentKind::Tab => 1,
 6193                        };
 6194                        let start = if has_multiple_rows
 6195                            || deletion_len > selection.start.column
 6196                            || indent_size.len < selection.start.column
 6197                        {
 6198                            0
 6199                        } else {
 6200                            selection.start.column - deletion_len
 6201                        };
 6202                        deletion_ranges.push(
 6203                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6204                        );
 6205                        last_outdent = Some(row);
 6206                    }
 6207                }
 6208            }
 6209        }
 6210
 6211        self.transact(cx, |this, cx| {
 6212            this.buffer.update(cx, |buffer, cx| {
 6213                let empty_str: Arc<str> = Arc::default();
 6214                buffer.edit(
 6215                    deletion_ranges
 6216                        .into_iter()
 6217                        .map(|range| (range, empty_str.clone())),
 6218                    None,
 6219                    cx,
 6220                );
 6221            });
 6222            let selections = this.selections.all::<usize>(cx);
 6223            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6224        });
 6225    }
 6226
 6227    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6228        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6229        let selections = self.selections.all::<Point>(cx);
 6230
 6231        let mut new_cursors = Vec::new();
 6232        let mut edit_ranges = Vec::new();
 6233        let mut selections = selections.iter().peekable();
 6234        while let Some(selection) = selections.next() {
 6235            let mut rows = selection.spanned_rows(false, &display_map);
 6236            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6237
 6238            // Accumulate contiguous regions of rows that we want to delete.
 6239            while let Some(next_selection) = selections.peek() {
 6240                let next_rows = next_selection.spanned_rows(false, &display_map);
 6241                if next_rows.start <= rows.end {
 6242                    rows.end = next_rows.end;
 6243                    selections.next().unwrap();
 6244                } else {
 6245                    break;
 6246                }
 6247            }
 6248
 6249            let buffer = &display_map.buffer_snapshot;
 6250            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6251            let edit_end;
 6252            let cursor_buffer_row;
 6253            if buffer.max_point().row >= rows.end.0 {
 6254                // If there's a line after the range, delete the \n from the end of the row range
 6255                // and position the cursor on the next line.
 6256                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6257                cursor_buffer_row = rows.end;
 6258            } else {
 6259                // If there isn't a line after the range, delete the \n from the line before the
 6260                // start of the row range and position the cursor there.
 6261                edit_start = edit_start.saturating_sub(1);
 6262                edit_end = buffer.len();
 6263                cursor_buffer_row = rows.start.previous_row();
 6264            }
 6265
 6266            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6267            *cursor.column_mut() =
 6268                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6269
 6270            new_cursors.push((
 6271                selection.id,
 6272                buffer.anchor_after(cursor.to_point(&display_map)),
 6273            ));
 6274            edit_ranges.push(edit_start..edit_end);
 6275        }
 6276
 6277        self.transact(cx, |this, cx| {
 6278            let buffer = this.buffer.update(cx, |buffer, cx| {
 6279                let empty_str: Arc<str> = Arc::default();
 6280                buffer.edit(
 6281                    edit_ranges
 6282                        .into_iter()
 6283                        .map(|range| (range, empty_str.clone())),
 6284                    None,
 6285                    cx,
 6286                );
 6287                buffer.snapshot(cx)
 6288            });
 6289            let new_selections = new_cursors
 6290                .into_iter()
 6291                .map(|(id, cursor)| {
 6292                    let cursor = cursor.to_point(&buffer);
 6293                    Selection {
 6294                        id,
 6295                        start: cursor,
 6296                        end: cursor,
 6297                        reversed: false,
 6298                        goal: SelectionGoal::None,
 6299                    }
 6300                })
 6301                .collect();
 6302
 6303            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6304                s.select(new_selections);
 6305            });
 6306        });
 6307    }
 6308
 6309    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6310        if self.read_only(cx) {
 6311            return;
 6312        }
 6313        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6314        for selection in self.selections.all::<Point>(cx) {
 6315            let start = MultiBufferRow(selection.start.row);
 6316            let end = if selection.start.row == selection.end.row {
 6317                MultiBufferRow(selection.start.row + 1)
 6318            } else {
 6319                MultiBufferRow(selection.end.row)
 6320            };
 6321
 6322            if let Some(last_row_range) = row_ranges.last_mut() {
 6323                if start <= last_row_range.end {
 6324                    last_row_range.end = end;
 6325                    continue;
 6326                }
 6327            }
 6328            row_ranges.push(start..end);
 6329        }
 6330
 6331        let snapshot = self.buffer.read(cx).snapshot(cx);
 6332        let mut cursor_positions = Vec::new();
 6333        for row_range in &row_ranges {
 6334            let anchor = snapshot.anchor_before(Point::new(
 6335                row_range.end.previous_row().0,
 6336                snapshot.line_len(row_range.end.previous_row()),
 6337            ));
 6338            cursor_positions.push(anchor..anchor);
 6339        }
 6340
 6341        self.transact(cx, |this, cx| {
 6342            for row_range in row_ranges.into_iter().rev() {
 6343                for row in row_range.iter_rows().rev() {
 6344                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6345                    let next_line_row = row.next_row();
 6346                    let indent = snapshot.indent_size_for_line(next_line_row);
 6347                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6348
 6349                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6350                        " "
 6351                    } else {
 6352                        ""
 6353                    };
 6354
 6355                    this.buffer.update(cx, |buffer, cx| {
 6356                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6357                    });
 6358                }
 6359            }
 6360
 6361            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6362                s.select_anchor_ranges(cursor_positions)
 6363            });
 6364        });
 6365    }
 6366
 6367    pub fn sort_lines_case_sensitive(
 6368        &mut self,
 6369        _: &SortLinesCaseSensitive,
 6370        cx: &mut ViewContext<Self>,
 6371    ) {
 6372        self.manipulate_lines(cx, |lines| lines.sort())
 6373    }
 6374
 6375    pub fn sort_lines_case_insensitive(
 6376        &mut self,
 6377        _: &SortLinesCaseInsensitive,
 6378        cx: &mut ViewContext<Self>,
 6379    ) {
 6380        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6381    }
 6382
 6383    pub fn unique_lines_case_insensitive(
 6384        &mut self,
 6385        _: &UniqueLinesCaseInsensitive,
 6386        cx: &mut ViewContext<Self>,
 6387    ) {
 6388        self.manipulate_lines(cx, |lines| {
 6389            let mut seen = HashSet::default();
 6390            lines.retain(|line| seen.insert(line.to_lowercase()));
 6391        })
 6392    }
 6393
 6394    pub fn unique_lines_case_sensitive(
 6395        &mut self,
 6396        _: &UniqueLinesCaseSensitive,
 6397        cx: &mut ViewContext<Self>,
 6398    ) {
 6399        self.manipulate_lines(cx, |lines| {
 6400            let mut seen = HashSet::default();
 6401            lines.retain(|line| seen.insert(*line));
 6402        })
 6403    }
 6404
 6405    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6406        let mut revert_changes = HashMap::default();
 6407        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6408        for hunk in hunks_for_rows(
 6409            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6410            &multi_buffer_snapshot,
 6411        ) {
 6412            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6413        }
 6414        if !revert_changes.is_empty() {
 6415            self.transact(cx, |editor, cx| {
 6416                editor.revert(revert_changes, cx);
 6417            });
 6418        }
 6419    }
 6420
 6421    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6422        let Some(project) = self.project.clone() else {
 6423            return;
 6424        };
 6425        self.reload(project, cx).detach_and_notify_err(cx);
 6426    }
 6427
 6428    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6429        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6430        if !revert_changes.is_empty() {
 6431            self.transact(cx, |editor, cx| {
 6432                editor.revert(revert_changes, cx);
 6433            });
 6434        }
 6435    }
 6436
 6437    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6438        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6439            let project_path = buffer.read(cx).project_path(cx)?;
 6440            let project = self.project.as_ref()?.read(cx);
 6441            let entry = project.entry_for_path(&project_path, cx)?;
 6442            let parent = match &entry.canonical_path {
 6443                Some(canonical_path) => canonical_path.to_path_buf(),
 6444                None => project.absolute_path(&project_path, cx)?,
 6445            }
 6446            .parent()?
 6447            .to_path_buf();
 6448            Some(parent)
 6449        }) {
 6450            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6451        }
 6452    }
 6453
 6454    fn gather_revert_changes(
 6455        &mut self,
 6456        selections: &[Selection<Anchor>],
 6457        cx: &mut ViewContext<'_, Editor>,
 6458    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6459        let mut revert_changes = HashMap::default();
 6460        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6461        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6462            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6463        }
 6464        revert_changes
 6465    }
 6466
 6467    pub fn prepare_revert_change(
 6468        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6469        multi_buffer: &Model<MultiBuffer>,
 6470        hunk: &MultiBufferDiffHunk,
 6471        cx: &AppContext,
 6472    ) -> Option<()> {
 6473        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6474        let buffer = buffer.read(cx);
 6475        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6476        let buffer_snapshot = buffer.snapshot();
 6477        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6478        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6479            probe
 6480                .0
 6481                .start
 6482                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6483                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6484        }) {
 6485            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6486            Some(())
 6487        } else {
 6488            None
 6489        }
 6490    }
 6491
 6492    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6493        self.manipulate_lines(cx, |lines| lines.reverse())
 6494    }
 6495
 6496    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6497        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6498    }
 6499
 6500    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6501    where
 6502        Fn: FnMut(&mut Vec<&str>),
 6503    {
 6504        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6505        let buffer = self.buffer.read(cx).snapshot(cx);
 6506
 6507        let mut edits = Vec::new();
 6508
 6509        let selections = self.selections.all::<Point>(cx);
 6510        let mut selections = selections.iter().peekable();
 6511        let mut contiguous_row_selections = Vec::new();
 6512        let mut new_selections = Vec::new();
 6513        let mut added_lines = 0;
 6514        let mut removed_lines = 0;
 6515
 6516        while let Some(selection) = selections.next() {
 6517            let (start_row, end_row) = consume_contiguous_rows(
 6518                &mut contiguous_row_selections,
 6519                selection,
 6520                &display_map,
 6521                &mut selections,
 6522            );
 6523
 6524            let start_point = Point::new(start_row.0, 0);
 6525            let end_point = Point::new(
 6526                end_row.previous_row().0,
 6527                buffer.line_len(end_row.previous_row()),
 6528            );
 6529            let text = buffer
 6530                .text_for_range(start_point..end_point)
 6531                .collect::<String>();
 6532
 6533            let mut lines = text.split('\n').collect_vec();
 6534
 6535            let lines_before = lines.len();
 6536            callback(&mut lines);
 6537            let lines_after = lines.len();
 6538
 6539            edits.push((start_point..end_point, lines.join("\n")));
 6540
 6541            // Selections must change based on added and removed line count
 6542            let start_row =
 6543                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6544            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6545            new_selections.push(Selection {
 6546                id: selection.id,
 6547                start: start_row,
 6548                end: end_row,
 6549                goal: SelectionGoal::None,
 6550                reversed: selection.reversed,
 6551            });
 6552
 6553            if lines_after > lines_before {
 6554                added_lines += lines_after - lines_before;
 6555            } else if lines_before > lines_after {
 6556                removed_lines += lines_before - lines_after;
 6557            }
 6558        }
 6559
 6560        self.transact(cx, |this, cx| {
 6561            let buffer = this.buffer.update(cx, |buffer, cx| {
 6562                buffer.edit(edits, None, cx);
 6563                buffer.snapshot(cx)
 6564            });
 6565
 6566            // Recalculate offsets on newly edited buffer
 6567            let new_selections = new_selections
 6568                .iter()
 6569                .map(|s| {
 6570                    let start_point = Point::new(s.start.0, 0);
 6571                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6572                    Selection {
 6573                        id: s.id,
 6574                        start: buffer.point_to_offset(start_point),
 6575                        end: buffer.point_to_offset(end_point),
 6576                        goal: s.goal,
 6577                        reversed: s.reversed,
 6578                    }
 6579                })
 6580                .collect();
 6581
 6582            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6583                s.select(new_selections);
 6584            });
 6585
 6586            this.request_autoscroll(Autoscroll::fit(), cx);
 6587        });
 6588    }
 6589
 6590    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6591        self.manipulate_text(cx, |text| text.to_uppercase())
 6592    }
 6593
 6594    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6595        self.manipulate_text(cx, |text| text.to_lowercase())
 6596    }
 6597
 6598    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6599        self.manipulate_text(cx, |text| {
 6600            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6601            // https://github.com/rutrum/convert-case/issues/16
 6602            text.split('\n')
 6603                .map(|line| line.to_case(Case::Title))
 6604                .join("\n")
 6605        })
 6606    }
 6607
 6608    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6609        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6610    }
 6611
 6612    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6613        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6614    }
 6615
 6616    pub fn convert_to_upper_camel_case(
 6617        &mut self,
 6618        _: &ConvertToUpperCamelCase,
 6619        cx: &mut ViewContext<Self>,
 6620    ) {
 6621        self.manipulate_text(cx, |text| {
 6622            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6623            // https://github.com/rutrum/convert-case/issues/16
 6624            text.split('\n')
 6625                .map(|line| line.to_case(Case::UpperCamel))
 6626                .join("\n")
 6627        })
 6628    }
 6629
 6630    pub fn convert_to_lower_camel_case(
 6631        &mut self,
 6632        _: &ConvertToLowerCamelCase,
 6633        cx: &mut ViewContext<Self>,
 6634    ) {
 6635        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6636    }
 6637
 6638    pub fn convert_to_opposite_case(
 6639        &mut self,
 6640        _: &ConvertToOppositeCase,
 6641        cx: &mut ViewContext<Self>,
 6642    ) {
 6643        self.manipulate_text(cx, |text| {
 6644            text.chars()
 6645                .fold(String::with_capacity(text.len()), |mut t, c| {
 6646                    if c.is_uppercase() {
 6647                        t.extend(c.to_lowercase());
 6648                    } else {
 6649                        t.extend(c.to_uppercase());
 6650                    }
 6651                    t
 6652                })
 6653        })
 6654    }
 6655
 6656    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6657    where
 6658        Fn: FnMut(&str) -> String,
 6659    {
 6660        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6661        let buffer = self.buffer.read(cx).snapshot(cx);
 6662
 6663        let mut new_selections = Vec::new();
 6664        let mut edits = Vec::new();
 6665        let mut selection_adjustment = 0i32;
 6666
 6667        for selection in self.selections.all::<usize>(cx) {
 6668            let selection_is_empty = selection.is_empty();
 6669
 6670            let (start, end) = if selection_is_empty {
 6671                let word_range = movement::surrounding_word(
 6672                    &display_map,
 6673                    selection.start.to_display_point(&display_map),
 6674                );
 6675                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6676                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6677                (start, end)
 6678            } else {
 6679                (selection.start, selection.end)
 6680            };
 6681
 6682            let text = buffer.text_for_range(start..end).collect::<String>();
 6683            let old_length = text.len() as i32;
 6684            let text = callback(&text);
 6685
 6686            new_selections.push(Selection {
 6687                start: (start as i32 - selection_adjustment) as usize,
 6688                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6689                goal: SelectionGoal::None,
 6690                ..selection
 6691            });
 6692
 6693            selection_adjustment += old_length - text.len() as i32;
 6694
 6695            edits.push((start..end, text));
 6696        }
 6697
 6698        self.transact(cx, |this, cx| {
 6699            this.buffer.update(cx, |buffer, cx| {
 6700                buffer.edit(edits, None, cx);
 6701            });
 6702
 6703            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6704                s.select(new_selections);
 6705            });
 6706
 6707            this.request_autoscroll(Autoscroll::fit(), cx);
 6708        });
 6709    }
 6710
 6711    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6712        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6713        let buffer = &display_map.buffer_snapshot;
 6714        let selections = self.selections.all::<Point>(cx);
 6715
 6716        let mut edits = Vec::new();
 6717        let mut selections_iter = selections.iter().peekable();
 6718        while let Some(selection) = selections_iter.next() {
 6719            // Avoid duplicating the same lines twice.
 6720            let mut rows = selection.spanned_rows(false, &display_map);
 6721
 6722            while let Some(next_selection) = selections_iter.peek() {
 6723                let next_rows = next_selection.spanned_rows(false, &display_map);
 6724                if next_rows.start < rows.end {
 6725                    rows.end = next_rows.end;
 6726                    selections_iter.next().unwrap();
 6727                } else {
 6728                    break;
 6729                }
 6730            }
 6731
 6732            // Copy the text from the selected row region and splice it either at the start
 6733            // or end of the region.
 6734            let start = Point::new(rows.start.0, 0);
 6735            let end = Point::new(
 6736                rows.end.previous_row().0,
 6737                buffer.line_len(rows.end.previous_row()),
 6738            );
 6739            let text = buffer
 6740                .text_for_range(start..end)
 6741                .chain(Some("\n"))
 6742                .collect::<String>();
 6743            let insert_location = if upwards {
 6744                Point::new(rows.end.0, 0)
 6745            } else {
 6746                start
 6747            };
 6748            edits.push((insert_location..insert_location, text));
 6749        }
 6750
 6751        self.transact(cx, |this, cx| {
 6752            this.buffer.update(cx, |buffer, cx| {
 6753                buffer.edit(edits, None, cx);
 6754            });
 6755
 6756            this.request_autoscroll(Autoscroll::fit(), cx);
 6757        });
 6758    }
 6759
 6760    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6761        self.duplicate_line(true, cx);
 6762    }
 6763
 6764    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6765        self.duplicate_line(false, cx);
 6766    }
 6767
 6768    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6769        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6770        let buffer = self.buffer.read(cx).snapshot(cx);
 6771
 6772        let mut edits = Vec::new();
 6773        let mut unfold_ranges = Vec::new();
 6774        let mut refold_ranges = Vec::new();
 6775
 6776        let selections = self.selections.all::<Point>(cx);
 6777        let mut selections = selections.iter().peekable();
 6778        let mut contiguous_row_selections = Vec::new();
 6779        let mut new_selections = Vec::new();
 6780
 6781        while let Some(selection) = selections.next() {
 6782            // Find all the selections that span a contiguous row range
 6783            let (start_row, end_row) = consume_contiguous_rows(
 6784                &mut contiguous_row_selections,
 6785                selection,
 6786                &display_map,
 6787                &mut selections,
 6788            );
 6789
 6790            // Move the text spanned by the row range to be before the line preceding the row range
 6791            if start_row.0 > 0 {
 6792                let range_to_move = Point::new(
 6793                    start_row.previous_row().0,
 6794                    buffer.line_len(start_row.previous_row()),
 6795                )
 6796                    ..Point::new(
 6797                        end_row.previous_row().0,
 6798                        buffer.line_len(end_row.previous_row()),
 6799                    );
 6800                let insertion_point = display_map
 6801                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6802                    .0;
 6803
 6804                // Don't move lines across excerpts
 6805                if buffer
 6806                    .excerpt_boundaries_in_range((
 6807                        Bound::Excluded(insertion_point),
 6808                        Bound::Included(range_to_move.end),
 6809                    ))
 6810                    .next()
 6811                    .is_none()
 6812                {
 6813                    let text = buffer
 6814                        .text_for_range(range_to_move.clone())
 6815                        .flat_map(|s| s.chars())
 6816                        .skip(1)
 6817                        .chain(['\n'])
 6818                        .collect::<String>();
 6819
 6820                    edits.push((
 6821                        buffer.anchor_after(range_to_move.start)
 6822                            ..buffer.anchor_before(range_to_move.end),
 6823                        String::new(),
 6824                    ));
 6825                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6826                    edits.push((insertion_anchor..insertion_anchor, text));
 6827
 6828                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6829
 6830                    // Move selections up
 6831                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6832                        |mut selection| {
 6833                            selection.start.row -= row_delta;
 6834                            selection.end.row -= row_delta;
 6835                            selection
 6836                        },
 6837                    ));
 6838
 6839                    // Move folds up
 6840                    unfold_ranges.push(range_to_move.clone());
 6841                    for fold in display_map.folds_in_range(
 6842                        buffer.anchor_before(range_to_move.start)
 6843                            ..buffer.anchor_after(range_to_move.end),
 6844                    ) {
 6845                        let mut start = fold.range.start.to_point(&buffer);
 6846                        let mut end = fold.range.end.to_point(&buffer);
 6847                        start.row -= row_delta;
 6848                        end.row -= row_delta;
 6849                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6850                    }
 6851                }
 6852            }
 6853
 6854            // If we didn't move line(s), preserve the existing selections
 6855            new_selections.append(&mut contiguous_row_selections);
 6856        }
 6857
 6858        self.transact(cx, |this, cx| {
 6859            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6860            this.buffer.update(cx, |buffer, cx| {
 6861                for (range, text) in edits {
 6862                    buffer.edit([(range, text)], None, cx);
 6863                }
 6864            });
 6865            this.fold_ranges(refold_ranges, true, cx);
 6866            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6867                s.select(new_selections);
 6868            })
 6869        });
 6870    }
 6871
 6872    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6873        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6874        let buffer = self.buffer.read(cx).snapshot(cx);
 6875
 6876        let mut edits = Vec::new();
 6877        let mut unfold_ranges = Vec::new();
 6878        let mut refold_ranges = Vec::new();
 6879
 6880        let selections = self.selections.all::<Point>(cx);
 6881        let mut selections = selections.iter().peekable();
 6882        let mut contiguous_row_selections = Vec::new();
 6883        let mut new_selections = Vec::new();
 6884
 6885        while let Some(selection) = selections.next() {
 6886            // Find all the selections that span a contiguous row range
 6887            let (start_row, end_row) = consume_contiguous_rows(
 6888                &mut contiguous_row_selections,
 6889                selection,
 6890                &display_map,
 6891                &mut selections,
 6892            );
 6893
 6894            // Move the text spanned by the row range to be after the last line of the row range
 6895            if end_row.0 <= buffer.max_point().row {
 6896                let range_to_move =
 6897                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6898                let insertion_point = display_map
 6899                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6900                    .0;
 6901
 6902                // Don't move lines across excerpt boundaries
 6903                if buffer
 6904                    .excerpt_boundaries_in_range((
 6905                        Bound::Excluded(range_to_move.start),
 6906                        Bound::Included(insertion_point),
 6907                    ))
 6908                    .next()
 6909                    .is_none()
 6910                {
 6911                    let mut text = String::from("\n");
 6912                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6913                    text.pop(); // Drop trailing newline
 6914                    edits.push((
 6915                        buffer.anchor_after(range_to_move.start)
 6916                            ..buffer.anchor_before(range_to_move.end),
 6917                        String::new(),
 6918                    ));
 6919                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6920                    edits.push((insertion_anchor..insertion_anchor, text));
 6921
 6922                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6923
 6924                    // Move selections down
 6925                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6926                        |mut selection| {
 6927                            selection.start.row += row_delta;
 6928                            selection.end.row += row_delta;
 6929                            selection
 6930                        },
 6931                    ));
 6932
 6933                    // Move folds down
 6934                    unfold_ranges.push(range_to_move.clone());
 6935                    for fold in display_map.folds_in_range(
 6936                        buffer.anchor_before(range_to_move.start)
 6937                            ..buffer.anchor_after(range_to_move.end),
 6938                    ) {
 6939                        let mut start = fold.range.start.to_point(&buffer);
 6940                        let mut end = fold.range.end.to_point(&buffer);
 6941                        start.row += row_delta;
 6942                        end.row += row_delta;
 6943                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6944                    }
 6945                }
 6946            }
 6947
 6948            // If we didn't move line(s), preserve the existing selections
 6949            new_selections.append(&mut contiguous_row_selections);
 6950        }
 6951
 6952        self.transact(cx, |this, cx| {
 6953            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6954            this.buffer.update(cx, |buffer, cx| {
 6955                for (range, text) in edits {
 6956                    buffer.edit([(range, text)], None, cx);
 6957                }
 6958            });
 6959            this.fold_ranges(refold_ranges, true, cx);
 6960            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6961        });
 6962    }
 6963
 6964    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6965        let text_layout_details = &self.text_layout_details(cx);
 6966        self.transact(cx, |this, cx| {
 6967            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6968                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6969                let line_mode = s.line_mode;
 6970                s.move_with(|display_map, selection| {
 6971                    if !selection.is_empty() || line_mode {
 6972                        return;
 6973                    }
 6974
 6975                    let mut head = selection.head();
 6976                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6977                    if head.column() == display_map.line_len(head.row()) {
 6978                        transpose_offset = display_map
 6979                            .buffer_snapshot
 6980                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6981                    }
 6982
 6983                    if transpose_offset == 0 {
 6984                        return;
 6985                    }
 6986
 6987                    *head.column_mut() += 1;
 6988                    head = display_map.clip_point(head, Bias::Right);
 6989                    let goal = SelectionGoal::HorizontalPosition(
 6990                        display_map
 6991                            .x_for_display_point(head, text_layout_details)
 6992                            .into(),
 6993                    );
 6994                    selection.collapse_to(head, goal);
 6995
 6996                    let transpose_start = display_map
 6997                        .buffer_snapshot
 6998                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6999                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7000                        let transpose_end = display_map
 7001                            .buffer_snapshot
 7002                            .clip_offset(transpose_offset + 1, Bias::Right);
 7003                        if let Some(ch) =
 7004                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7005                        {
 7006                            edits.push((transpose_start..transpose_offset, String::new()));
 7007                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7008                        }
 7009                    }
 7010                });
 7011                edits
 7012            });
 7013            this.buffer
 7014                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7015            let selections = this.selections.all::<usize>(cx);
 7016            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7017                s.select(selections);
 7018            });
 7019        });
 7020    }
 7021
 7022    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7023        self.rewrap_impl(true, cx)
 7024    }
 7025
 7026    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 7027        let buffer = self.buffer.read(cx).snapshot(cx);
 7028        let selections = self.selections.all::<Point>(cx);
 7029        let mut selections = selections.iter().peekable();
 7030
 7031        let mut edits = Vec::new();
 7032        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7033
 7034        while let Some(selection) = selections.next() {
 7035            let mut start_row = selection.start.row;
 7036            let mut end_row = selection.end.row;
 7037
 7038            // Skip selections that overlap with a range that has already been rewrapped.
 7039            let selection_range = start_row..end_row;
 7040            if rewrapped_row_ranges
 7041                .iter()
 7042                .any(|range| range.overlaps(&selection_range))
 7043            {
 7044                continue;
 7045            }
 7046
 7047            let mut should_rewrap = !only_text;
 7048
 7049            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7050                match language_scope.language_name().0.as_ref() {
 7051                    "Markdown" | "Plain Text" => {
 7052                        should_rewrap = true;
 7053                    }
 7054                    _ => {}
 7055                }
 7056            }
 7057
 7058            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7059
 7060            // Since not all lines in the selection may be at the same indent
 7061            // level, choose the indent size that is the most common between all
 7062            // of the lines.
 7063            //
 7064            // If there is a tie, we use the deepest indent.
 7065            let (indent_size, indent_end) = {
 7066                let mut indent_size_occurrences = HashMap::default();
 7067                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7068
 7069                for row in start_row..=end_row {
 7070                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7071                    rows_by_indent_size.entry(indent).or_default().push(row);
 7072                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7073                }
 7074
 7075                let indent_size = indent_size_occurrences
 7076                    .into_iter()
 7077                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7078                    .map(|(indent, _)| indent)
 7079                    .unwrap_or_default();
 7080                let row = rows_by_indent_size[&indent_size][0];
 7081                let indent_end = Point::new(row, indent_size.len);
 7082
 7083                (indent_size, indent_end)
 7084            };
 7085
 7086            let mut line_prefix = indent_size.chars().collect::<String>();
 7087
 7088            if let Some(comment_prefix) =
 7089                buffer
 7090                    .language_scope_at(selection.head())
 7091                    .and_then(|language| {
 7092                        language
 7093                            .line_comment_prefixes()
 7094                            .iter()
 7095                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7096                            .cloned()
 7097                    })
 7098            {
 7099                line_prefix.push_str(&comment_prefix);
 7100                should_rewrap = true;
 7101            }
 7102
 7103            if !should_rewrap {
 7104                continue;
 7105            }
 7106
 7107            if selection.is_empty() {
 7108                'expand_upwards: while start_row > 0 {
 7109                    let prev_row = start_row - 1;
 7110                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7111                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7112                    {
 7113                        start_row = prev_row;
 7114                    } else {
 7115                        break 'expand_upwards;
 7116                    }
 7117                }
 7118
 7119                'expand_downwards: while end_row < buffer.max_point().row {
 7120                    let next_row = end_row + 1;
 7121                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7122                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7123                    {
 7124                        end_row = next_row;
 7125                    } else {
 7126                        break 'expand_downwards;
 7127                    }
 7128                }
 7129            }
 7130
 7131            let start = Point::new(start_row, 0);
 7132            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7133            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7134            let Some(lines_without_prefixes) = selection_text
 7135                .lines()
 7136                .map(|line| {
 7137                    line.strip_prefix(&line_prefix)
 7138                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7139                        .ok_or_else(|| {
 7140                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7141                        })
 7142                })
 7143                .collect::<Result<Vec<_>, _>>()
 7144                .log_err()
 7145            else {
 7146                continue;
 7147            };
 7148
 7149            let wrap_column = buffer
 7150                .settings_at(Point::new(start_row, 0), cx)
 7151                .preferred_line_length as usize;
 7152            let wrapped_text = wrap_with_prefix(
 7153                line_prefix,
 7154                lines_without_prefixes.join(" "),
 7155                wrap_column,
 7156                tab_size,
 7157            );
 7158
 7159            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7160            let mut offset = start.to_offset(&buffer);
 7161            let mut moved_since_edit = true;
 7162
 7163            for change in diff.iter_all_changes() {
 7164                let value = change.value();
 7165                match change.tag() {
 7166                    ChangeTag::Equal => {
 7167                        offset += value.len();
 7168                        moved_since_edit = true;
 7169                    }
 7170                    ChangeTag::Delete => {
 7171                        let start = buffer.anchor_after(offset);
 7172                        let end = buffer.anchor_before(offset + value.len());
 7173
 7174                        if moved_since_edit {
 7175                            edits.push((start..end, String::new()));
 7176                        } else {
 7177                            edits.last_mut().unwrap().0.end = end;
 7178                        }
 7179
 7180                        offset += value.len();
 7181                        moved_since_edit = false;
 7182                    }
 7183                    ChangeTag::Insert => {
 7184                        if moved_since_edit {
 7185                            let anchor = buffer.anchor_after(offset);
 7186                            edits.push((anchor..anchor, value.to_string()));
 7187                        } else {
 7188                            edits.last_mut().unwrap().1.push_str(value);
 7189                        }
 7190
 7191                        moved_since_edit = false;
 7192                    }
 7193                }
 7194            }
 7195
 7196            rewrapped_row_ranges.push(start_row..=end_row);
 7197        }
 7198
 7199        self.buffer
 7200            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7201    }
 7202
 7203    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7204        let mut text = String::new();
 7205        let buffer = self.buffer.read(cx).snapshot(cx);
 7206        let mut selections = self.selections.all::<Point>(cx);
 7207        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7208        {
 7209            let max_point = buffer.max_point();
 7210            let mut is_first = true;
 7211            for selection in &mut selections {
 7212                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7213                if is_entire_line {
 7214                    selection.start = Point::new(selection.start.row, 0);
 7215                    if !selection.is_empty() && selection.end.column == 0 {
 7216                        selection.end = cmp::min(max_point, selection.end);
 7217                    } else {
 7218                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7219                    }
 7220                    selection.goal = SelectionGoal::None;
 7221                }
 7222                if is_first {
 7223                    is_first = false;
 7224                } else {
 7225                    text += "\n";
 7226                }
 7227                let mut len = 0;
 7228                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7229                    text.push_str(chunk);
 7230                    len += chunk.len();
 7231                }
 7232                clipboard_selections.push(ClipboardSelection {
 7233                    len,
 7234                    is_entire_line,
 7235                    first_line_indent: buffer
 7236                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7237                        .len,
 7238                });
 7239            }
 7240        }
 7241
 7242        self.transact(cx, |this, cx| {
 7243            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7244                s.select(selections);
 7245            });
 7246            this.insert("", cx);
 7247            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7248                text,
 7249                clipboard_selections,
 7250            ));
 7251        });
 7252    }
 7253
 7254    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7255        let selections = self.selections.all::<Point>(cx);
 7256        let buffer = self.buffer.read(cx).read(cx);
 7257        let mut text = String::new();
 7258
 7259        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7260        {
 7261            let max_point = buffer.max_point();
 7262            let mut is_first = true;
 7263            for selection in selections.iter() {
 7264                let mut start = selection.start;
 7265                let mut end = selection.end;
 7266                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7267                if is_entire_line {
 7268                    start = Point::new(start.row, 0);
 7269                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7270                }
 7271                if is_first {
 7272                    is_first = false;
 7273                } else {
 7274                    text += "\n";
 7275                }
 7276                let mut len = 0;
 7277                for chunk in buffer.text_for_range(start..end) {
 7278                    text.push_str(chunk);
 7279                    len += chunk.len();
 7280                }
 7281                clipboard_selections.push(ClipboardSelection {
 7282                    len,
 7283                    is_entire_line,
 7284                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7285                });
 7286            }
 7287        }
 7288
 7289        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7290            text,
 7291            clipboard_selections,
 7292        ));
 7293    }
 7294
 7295    pub fn do_paste(
 7296        &mut self,
 7297        text: &String,
 7298        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7299        handle_entire_lines: bool,
 7300        cx: &mut ViewContext<Self>,
 7301    ) {
 7302        if self.read_only(cx) {
 7303            return;
 7304        }
 7305
 7306        let clipboard_text = Cow::Borrowed(text);
 7307
 7308        self.transact(cx, |this, cx| {
 7309            if let Some(mut clipboard_selections) = clipboard_selections {
 7310                let old_selections = this.selections.all::<usize>(cx);
 7311                let all_selections_were_entire_line =
 7312                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7313                let first_selection_indent_column =
 7314                    clipboard_selections.first().map(|s| s.first_line_indent);
 7315                if clipboard_selections.len() != old_selections.len() {
 7316                    clipboard_selections.drain(..);
 7317                }
 7318                let cursor_offset = this.selections.last::<usize>(cx).head();
 7319                let mut auto_indent_on_paste = true;
 7320
 7321                this.buffer.update(cx, |buffer, cx| {
 7322                    let snapshot = buffer.read(cx);
 7323                    auto_indent_on_paste =
 7324                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7325
 7326                    let mut start_offset = 0;
 7327                    let mut edits = Vec::new();
 7328                    let mut original_indent_columns = Vec::new();
 7329                    for (ix, selection) in old_selections.iter().enumerate() {
 7330                        let to_insert;
 7331                        let entire_line;
 7332                        let original_indent_column;
 7333                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7334                            let end_offset = start_offset + clipboard_selection.len;
 7335                            to_insert = &clipboard_text[start_offset..end_offset];
 7336                            entire_line = clipboard_selection.is_entire_line;
 7337                            start_offset = end_offset + 1;
 7338                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7339                        } else {
 7340                            to_insert = clipboard_text.as_str();
 7341                            entire_line = all_selections_were_entire_line;
 7342                            original_indent_column = first_selection_indent_column
 7343                        }
 7344
 7345                        // If the corresponding selection was empty when this slice of the
 7346                        // clipboard text was written, then the entire line containing the
 7347                        // selection was copied. If this selection is also currently empty,
 7348                        // then paste the line before the current line of the buffer.
 7349                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7350                            let column = selection.start.to_point(&snapshot).column as usize;
 7351                            let line_start = selection.start - column;
 7352                            line_start..line_start
 7353                        } else {
 7354                            selection.range()
 7355                        };
 7356
 7357                        edits.push((range, to_insert));
 7358                        original_indent_columns.extend(original_indent_column);
 7359                    }
 7360                    drop(snapshot);
 7361
 7362                    buffer.edit(
 7363                        edits,
 7364                        if auto_indent_on_paste {
 7365                            Some(AutoindentMode::Block {
 7366                                original_indent_columns,
 7367                            })
 7368                        } else {
 7369                            None
 7370                        },
 7371                        cx,
 7372                    );
 7373                });
 7374
 7375                let selections = this.selections.all::<usize>(cx);
 7376                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7377            } else {
 7378                this.insert(&clipboard_text, cx);
 7379            }
 7380        });
 7381    }
 7382
 7383    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7384        if let Some(item) = cx.read_from_clipboard() {
 7385            let entries = item.entries();
 7386
 7387            match entries.first() {
 7388                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7389                // of all the pasted entries.
 7390                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7391                    .do_paste(
 7392                        clipboard_string.text(),
 7393                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7394                        true,
 7395                        cx,
 7396                    ),
 7397                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7398            }
 7399        }
 7400    }
 7401
 7402    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7403        if self.read_only(cx) {
 7404            return;
 7405        }
 7406
 7407        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7408            if let Some((selections, _)) =
 7409                self.selection_history.transaction(transaction_id).cloned()
 7410            {
 7411                self.change_selections(None, cx, |s| {
 7412                    s.select_anchors(selections.to_vec());
 7413                });
 7414            }
 7415            self.request_autoscroll(Autoscroll::fit(), cx);
 7416            self.unmark_text(cx);
 7417            self.refresh_inline_completion(true, false, cx);
 7418            cx.emit(EditorEvent::Edited { transaction_id });
 7419            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7420        }
 7421    }
 7422
 7423    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7424        if self.read_only(cx) {
 7425            return;
 7426        }
 7427
 7428        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7429            if let Some((_, Some(selections))) =
 7430                self.selection_history.transaction(transaction_id).cloned()
 7431            {
 7432                self.change_selections(None, cx, |s| {
 7433                    s.select_anchors(selections.to_vec());
 7434                });
 7435            }
 7436            self.request_autoscroll(Autoscroll::fit(), cx);
 7437            self.unmark_text(cx);
 7438            self.refresh_inline_completion(true, false, cx);
 7439            cx.emit(EditorEvent::Edited { transaction_id });
 7440        }
 7441    }
 7442
 7443    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7444        self.buffer
 7445            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7446    }
 7447
 7448    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7449        self.buffer
 7450            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7451    }
 7452
 7453    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7454        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7455            let line_mode = s.line_mode;
 7456            s.move_with(|map, selection| {
 7457                let cursor = if selection.is_empty() && !line_mode {
 7458                    movement::left(map, selection.start)
 7459                } else {
 7460                    selection.start
 7461                };
 7462                selection.collapse_to(cursor, SelectionGoal::None);
 7463            });
 7464        })
 7465    }
 7466
 7467    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7468        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7469            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7470        })
 7471    }
 7472
 7473    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7474        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7475            let line_mode = s.line_mode;
 7476            s.move_with(|map, selection| {
 7477                let cursor = if selection.is_empty() && !line_mode {
 7478                    movement::right(map, selection.end)
 7479                } else {
 7480                    selection.end
 7481                };
 7482                selection.collapse_to(cursor, SelectionGoal::None)
 7483            });
 7484        })
 7485    }
 7486
 7487    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7488        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7489            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7490        })
 7491    }
 7492
 7493    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7494        if self.take_rename(true, cx).is_some() {
 7495            return;
 7496        }
 7497
 7498        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7499            cx.propagate();
 7500            return;
 7501        }
 7502
 7503        let text_layout_details = &self.text_layout_details(cx);
 7504        let selection_count = self.selections.count();
 7505        let first_selection = self.selections.first_anchor();
 7506
 7507        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7508            let line_mode = s.line_mode;
 7509            s.move_with(|map, selection| {
 7510                if !selection.is_empty() && !line_mode {
 7511                    selection.goal = SelectionGoal::None;
 7512                }
 7513                let (cursor, goal) = movement::up(
 7514                    map,
 7515                    selection.start,
 7516                    selection.goal,
 7517                    false,
 7518                    text_layout_details,
 7519                );
 7520                selection.collapse_to(cursor, goal);
 7521            });
 7522        });
 7523
 7524        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7525        {
 7526            cx.propagate();
 7527        }
 7528    }
 7529
 7530    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7531        if self.take_rename(true, cx).is_some() {
 7532            return;
 7533        }
 7534
 7535        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7536            cx.propagate();
 7537            return;
 7538        }
 7539
 7540        let text_layout_details = &self.text_layout_details(cx);
 7541
 7542        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7543            let line_mode = s.line_mode;
 7544            s.move_with(|map, selection| {
 7545                if !selection.is_empty() && !line_mode {
 7546                    selection.goal = SelectionGoal::None;
 7547                }
 7548                let (cursor, goal) = movement::up_by_rows(
 7549                    map,
 7550                    selection.start,
 7551                    action.lines,
 7552                    selection.goal,
 7553                    false,
 7554                    text_layout_details,
 7555                );
 7556                selection.collapse_to(cursor, goal);
 7557            });
 7558        })
 7559    }
 7560
 7561    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7562        if self.take_rename(true, cx).is_some() {
 7563            return;
 7564        }
 7565
 7566        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7567            cx.propagate();
 7568            return;
 7569        }
 7570
 7571        let text_layout_details = &self.text_layout_details(cx);
 7572
 7573        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7574            let line_mode = s.line_mode;
 7575            s.move_with(|map, selection| {
 7576                if !selection.is_empty() && !line_mode {
 7577                    selection.goal = SelectionGoal::None;
 7578                }
 7579                let (cursor, goal) = movement::down_by_rows(
 7580                    map,
 7581                    selection.start,
 7582                    action.lines,
 7583                    selection.goal,
 7584                    false,
 7585                    text_layout_details,
 7586                );
 7587                selection.collapse_to(cursor, goal);
 7588            });
 7589        })
 7590    }
 7591
 7592    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7593        let text_layout_details = &self.text_layout_details(cx);
 7594        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7595            s.move_heads_with(|map, head, goal| {
 7596                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7597            })
 7598        })
 7599    }
 7600
 7601    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7602        let text_layout_details = &self.text_layout_details(cx);
 7603        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7604            s.move_heads_with(|map, head, goal| {
 7605                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7606            })
 7607        })
 7608    }
 7609
 7610    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7611        let Some(row_count) = self.visible_row_count() else {
 7612            return;
 7613        };
 7614
 7615        let text_layout_details = &self.text_layout_details(cx);
 7616
 7617        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7618            s.move_heads_with(|map, head, goal| {
 7619                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7620            })
 7621        })
 7622    }
 7623
 7624    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7625        if self.take_rename(true, cx).is_some() {
 7626            return;
 7627        }
 7628
 7629        if self
 7630            .context_menu
 7631            .write()
 7632            .as_mut()
 7633            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7634            .unwrap_or(false)
 7635        {
 7636            return;
 7637        }
 7638
 7639        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7640            cx.propagate();
 7641            return;
 7642        }
 7643
 7644        let Some(row_count) = self.visible_row_count() else {
 7645            return;
 7646        };
 7647
 7648        let autoscroll = if action.center_cursor {
 7649            Autoscroll::center()
 7650        } else {
 7651            Autoscroll::fit()
 7652        };
 7653
 7654        let text_layout_details = &self.text_layout_details(cx);
 7655
 7656        self.change_selections(Some(autoscroll), cx, |s| {
 7657            let line_mode = s.line_mode;
 7658            s.move_with(|map, selection| {
 7659                if !selection.is_empty() && !line_mode {
 7660                    selection.goal = SelectionGoal::None;
 7661                }
 7662                let (cursor, goal) = movement::up_by_rows(
 7663                    map,
 7664                    selection.end,
 7665                    row_count,
 7666                    selection.goal,
 7667                    false,
 7668                    text_layout_details,
 7669                );
 7670                selection.collapse_to(cursor, goal);
 7671            });
 7672        });
 7673    }
 7674
 7675    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7676        let text_layout_details = &self.text_layout_details(cx);
 7677        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7678            s.move_heads_with(|map, head, goal| {
 7679                movement::up(map, head, goal, false, text_layout_details)
 7680            })
 7681        })
 7682    }
 7683
 7684    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7685        self.take_rename(true, cx);
 7686
 7687        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7688            cx.propagate();
 7689            return;
 7690        }
 7691
 7692        let text_layout_details = &self.text_layout_details(cx);
 7693        let selection_count = self.selections.count();
 7694        let first_selection = self.selections.first_anchor();
 7695
 7696        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7697            let line_mode = s.line_mode;
 7698            s.move_with(|map, selection| {
 7699                if !selection.is_empty() && !line_mode {
 7700                    selection.goal = SelectionGoal::None;
 7701                }
 7702                let (cursor, goal) = movement::down(
 7703                    map,
 7704                    selection.end,
 7705                    selection.goal,
 7706                    false,
 7707                    text_layout_details,
 7708                );
 7709                selection.collapse_to(cursor, goal);
 7710            });
 7711        });
 7712
 7713        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7714        {
 7715            cx.propagate();
 7716        }
 7717    }
 7718
 7719    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7720        let Some(row_count) = self.visible_row_count() else {
 7721            return;
 7722        };
 7723
 7724        let text_layout_details = &self.text_layout_details(cx);
 7725
 7726        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7727            s.move_heads_with(|map, head, goal| {
 7728                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7729            })
 7730        })
 7731    }
 7732
 7733    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7734        if self.take_rename(true, cx).is_some() {
 7735            return;
 7736        }
 7737
 7738        if self
 7739            .context_menu
 7740            .write()
 7741            .as_mut()
 7742            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7743            .unwrap_or(false)
 7744        {
 7745            return;
 7746        }
 7747
 7748        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7749            cx.propagate();
 7750            return;
 7751        }
 7752
 7753        let Some(row_count) = self.visible_row_count() else {
 7754            return;
 7755        };
 7756
 7757        let autoscroll = if action.center_cursor {
 7758            Autoscroll::center()
 7759        } else {
 7760            Autoscroll::fit()
 7761        };
 7762
 7763        let text_layout_details = &self.text_layout_details(cx);
 7764        self.change_selections(Some(autoscroll), cx, |s| {
 7765            let line_mode = s.line_mode;
 7766            s.move_with(|map, selection| {
 7767                if !selection.is_empty() && !line_mode {
 7768                    selection.goal = SelectionGoal::None;
 7769                }
 7770                let (cursor, goal) = movement::down_by_rows(
 7771                    map,
 7772                    selection.end,
 7773                    row_count,
 7774                    selection.goal,
 7775                    false,
 7776                    text_layout_details,
 7777                );
 7778                selection.collapse_to(cursor, goal);
 7779            });
 7780        });
 7781    }
 7782
 7783    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7784        let text_layout_details = &self.text_layout_details(cx);
 7785        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7786            s.move_heads_with(|map, head, goal| {
 7787                movement::down(map, head, goal, false, text_layout_details)
 7788            })
 7789        });
 7790    }
 7791
 7792    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7793        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7794            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7795        }
 7796    }
 7797
 7798    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7799        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7800            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7801        }
 7802    }
 7803
 7804    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7805        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7806            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7807        }
 7808    }
 7809
 7810    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7811        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7812            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7813        }
 7814    }
 7815
 7816    pub fn move_to_previous_word_start(
 7817        &mut self,
 7818        _: &MoveToPreviousWordStart,
 7819        cx: &mut ViewContext<Self>,
 7820    ) {
 7821        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7822            s.move_cursors_with(|map, head, _| {
 7823                (
 7824                    movement::previous_word_start(map, head),
 7825                    SelectionGoal::None,
 7826                )
 7827            });
 7828        })
 7829    }
 7830
 7831    pub fn move_to_previous_subword_start(
 7832        &mut self,
 7833        _: &MoveToPreviousSubwordStart,
 7834        cx: &mut ViewContext<Self>,
 7835    ) {
 7836        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7837            s.move_cursors_with(|map, head, _| {
 7838                (
 7839                    movement::previous_subword_start(map, head),
 7840                    SelectionGoal::None,
 7841                )
 7842            });
 7843        })
 7844    }
 7845
 7846    pub fn select_to_previous_word_start(
 7847        &mut self,
 7848        _: &SelectToPreviousWordStart,
 7849        cx: &mut ViewContext<Self>,
 7850    ) {
 7851        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7852            s.move_heads_with(|map, head, _| {
 7853                (
 7854                    movement::previous_word_start(map, head),
 7855                    SelectionGoal::None,
 7856                )
 7857            });
 7858        })
 7859    }
 7860
 7861    pub fn select_to_previous_subword_start(
 7862        &mut self,
 7863        _: &SelectToPreviousSubwordStart,
 7864        cx: &mut ViewContext<Self>,
 7865    ) {
 7866        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7867            s.move_heads_with(|map, head, _| {
 7868                (
 7869                    movement::previous_subword_start(map, head),
 7870                    SelectionGoal::None,
 7871                )
 7872            });
 7873        })
 7874    }
 7875
 7876    pub fn delete_to_previous_word_start(
 7877        &mut self,
 7878        action: &DeleteToPreviousWordStart,
 7879        cx: &mut ViewContext<Self>,
 7880    ) {
 7881        self.transact(cx, |this, cx| {
 7882            this.select_autoclose_pair(cx);
 7883            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7884                let line_mode = s.line_mode;
 7885                s.move_with(|map, selection| {
 7886                    if selection.is_empty() && !line_mode {
 7887                        let cursor = if action.ignore_newlines {
 7888                            movement::previous_word_start(map, selection.head())
 7889                        } else {
 7890                            movement::previous_word_start_or_newline(map, selection.head())
 7891                        };
 7892                        selection.set_head(cursor, SelectionGoal::None);
 7893                    }
 7894                });
 7895            });
 7896            this.insert("", cx);
 7897        });
 7898    }
 7899
 7900    pub fn delete_to_previous_subword_start(
 7901        &mut self,
 7902        _: &DeleteToPreviousSubwordStart,
 7903        cx: &mut ViewContext<Self>,
 7904    ) {
 7905        self.transact(cx, |this, cx| {
 7906            this.select_autoclose_pair(cx);
 7907            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7908                let line_mode = s.line_mode;
 7909                s.move_with(|map, selection| {
 7910                    if selection.is_empty() && !line_mode {
 7911                        let cursor = movement::previous_subword_start(map, selection.head());
 7912                        selection.set_head(cursor, SelectionGoal::None);
 7913                    }
 7914                });
 7915            });
 7916            this.insert("", cx);
 7917        });
 7918    }
 7919
 7920    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7921        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7922            s.move_cursors_with(|map, head, _| {
 7923                (movement::next_word_end(map, head), SelectionGoal::None)
 7924            });
 7925        })
 7926    }
 7927
 7928    pub fn move_to_next_subword_end(
 7929        &mut self,
 7930        _: &MoveToNextSubwordEnd,
 7931        cx: &mut ViewContext<Self>,
 7932    ) {
 7933        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7934            s.move_cursors_with(|map, head, _| {
 7935                (movement::next_subword_end(map, head), SelectionGoal::None)
 7936            });
 7937        })
 7938    }
 7939
 7940    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7941        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7942            s.move_heads_with(|map, head, _| {
 7943                (movement::next_word_end(map, head), SelectionGoal::None)
 7944            });
 7945        })
 7946    }
 7947
 7948    pub fn select_to_next_subword_end(
 7949        &mut self,
 7950        _: &SelectToNextSubwordEnd,
 7951        cx: &mut ViewContext<Self>,
 7952    ) {
 7953        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7954            s.move_heads_with(|map, head, _| {
 7955                (movement::next_subword_end(map, head), SelectionGoal::None)
 7956            });
 7957        })
 7958    }
 7959
 7960    pub fn delete_to_next_word_end(
 7961        &mut self,
 7962        action: &DeleteToNextWordEnd,
 7963        cx: &mut ViewContext<Self>,
 7964    ) {
 7965        self.transact(cx, |this, cx| {
 7966            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7967                let line_mode = s.line_mode;
 7968                s.move_with(|map, selection| {
 7969                    if selection.is_empty() && !line_mode {
 7970                        let cursor = if action.ignore_newlines {
 7971                            movement::next_word_end(map, selection.head())
 7972                        } else {
 7973                            movement::next_word_end_or_newline(map, selection.head())
 7974                        };
 7975                        selection.set_head(cursor, SelectionGoal::None);
 7976                    }
 7977                });
 7978            });
 7979            this.insert("", cx);
 7980        });
 7981    }
 7982
 7983    pub fn delete_to_next_subword_end(
 7984        &mut self,
 7985        _: &DeleteToNextSubwordEnd,
 7986        cx: &mut ViewContext<Self>,
 7987    ) {
 7988        self.transact(cx, |this, cx| {
 7989            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7990                s.move_with(|map, selection| {
 7991                    if selection.is_empty() {
 7992                        let cursor = movement::next_subword_end(map, selection.head());
 7993                        selection.set_head(cursor, SelectionGoal::None);
 7994                    }
 7995                });
 7996            });
 7997            this.insert("", cx);
 7998        });
 7999    }
 8000
 8001    pub fn move_to_beginning_of_line(
 8002        &mut self,
 8003        action: &MoveToBeginningOfLine,
 8004        cx: &mut ViewContext<Self>,
 8005    ) {
 8006        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8007            s.move_cursors_with(|map, head, _| {
 8008                (
 8009                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8010                    SelectionGoal::None,
 8011                )
 8012            });
 8013        })
 8014    }
 8015
 8016    pub fn select_to_beginning_of_line(
 8017        &mut self,
 8018        action: &SelectToBeginningOfLine,
 8019        cx: &mut ViewContext<Self>,
 8020    ) {
 8021        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8022            s.move_heads_with(|map, head, _| {
 8023                (
 8024                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8025                    SelectionGoal::None,
 8026                )
 8027            });
 8028        });
 8029    }
 8030
 8031    pub fn delete_to_beginning_of_line(
 8032        &mut self,
 8033        _: &DeleteToBeginningOfLine,
 8034        cx: &mut ViewContext<Self>,
 8035    ) {
 8036        self.transact(cx, |this, cx| {
 8037            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8038                s.move_with(|_, selection| {
 8039                    selection.reversed = true;
 8040                });
 8041            });
 8042
 8043            this.select_to_beginning_of_line(
 8044                &SelectToBeginningOfLine {
 8045                    stop_at_soft_wraps: false,
 8046                },
 8047                cx,
 8048            );
 8049            this.backspace(&Backspace, cx);
 8050        });
 8051    }
 8052
 8053    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8054        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8055            s.move_cursors_with(|map, head, _| {
 8056                (
 8057                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8058                    SelectionGoal::None,
 8059                )
 8060            });
 8061        })
 8062    }
 8063
 8064    pub fn select_to_end_of_line(
 8065        &mut self,
 8066        action: &SelectToEndOfLine,
 8067        cx: &mut ViewContext<Self>,
 8068    ) {
 8069        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8070            s.move_heads_with(|map, head, _| {
 8071                (
 8072                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8073                    SelectionGoal::None,
 8074                )
 8075            });
 8076        })
 8077    }
 8078
 8079    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8080        self.transact(cx, |this, cx| {
 8081            this.select_to_end_of_line(
 8082                &SelectToEndOfLine {
 8083                    stop_at_soft_wraps: false,
 8084                },
 8085                cx,
 8086            );
 8087            this.delete(&Delete, cx);
 8088        });
 8089    }
 8090
 8091    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8092        self.transact(cx, |this, cx| {
 8093            this.select_to_end_of_line(
 8094                &SelectToEndOfLine {
 8095                    stop_at_soft_wraps: false,
 8096                },
 8097                cx,
 8098            );
 8099            this.cut(&Cut, cx);
 8100        });
 8101    }
 8102
 8103    pub fn move_to_start_of_paragraph(
 8104        &mut self,
 8105        _: &MoveToStartOfParagraph,
 8106        cx: &mut ViewContext<Self>,
 8107    ) {
 8108        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8109            cx.propagate();
 8110            return;
 8111        }
 8112
 8113        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8114            s.move_with(|map, selection| {
 8115                selection.collapse_to(
 8116                    movement::start_of_paragraph(map, selection.head(), 1),
 8117                    SelectionGoal::None,
 8118                )
 8119            });
 8120        })
 8121    }
 8122
 8123    pub fn move_to_end_of_paragraph(
 8124        &mut self,
 8125        _: &MoveToEndOfParagraph,
 8126        cx: &mut ViewContext<Self>,
 8127    ) {
 8128        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8129            cx.propagate();
 8130            return;
 8131        }
 8132
 8133        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8134            s.move_with(|map, selection| {
 8135                selection.collapse_to(
 8136                    movement::end_of_paragraph(map, selection.head(), 1),
 8137                    SelectionGoal::None,
 8138                )
 8139            });
 8140        })
 8141    }
 8142
 8143    pub fn select_to_start_of_paragraph(
 8144        &mut self,
 8145        _: &SelectToStartOfParagraph,
 8146        cx: &mut ViewContext<Self>,
 8147    ) {
 8148        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8149            cx.propagate();
 8150            return;
 8151        }
 8152
 8153        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8154            s.move_heads_with(|map, head, _| {
 8155                (
 8156                    movement::start_of_paragraph(map, head, 1),
 8157                    SelectionGoal::None,
 8158                )
 8159            });
 8160        })
 8161    }
 8162
 8163    pub fn select_to_end_of_paragraph(
 8164        &mut self,
 8165        _: &SelectToEndOfParagraph,
 8166        cx: &mut ViewContext<Self>,
 8167    ) {
 8168        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8169            cx.propagate();
 8170            return;
 8171        }
 8172
 8173        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8174            s.move_heads_with(|map, head, _| {
 8175                (
 8176                    movement::end_of_paragraph(map, head, 1),
 8177                    SelectionGoal::None,
 8178                )
 8179            });
 8180        })
 8181    }
 8182
 8183    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8184        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8185            cx.propagate();
 8186            return;
 8187        }
 8188
 8189        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8190            s.select_ranges(vec![0..0]);
 8191        });
 8192    }
 8193
 8194    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8195        let mut selection = self.selections.last::<Point>(cx);
 8196        selection.set_head(Point::zero(), SelectionGoal::None);
 8197
 8198        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8199            s.select(vec![selection]);
 8200        });
 8201    }
 8202
 8203    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8204        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8205            cx.propagate();
 8206            return;
 8207        }
 8208
 8209        let cursor = self.buffer.read(cx).read(cx).len();
 8210        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8211            s.select_ranges(vec![cursor..cursor])
 8212        });
 8213    }
 8214
 8215    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8216        self.nav_history = nav_history;
 8217    }
 8218
 8219    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8220        self.nav_history.as_ref()
 8221    }
 8222
 8223    fn push_to_nav_history(
 8224        &mut self,
 8225        cursor_anchor: Anchor,
 8226        new_position: Option<Point>,
 8227        cx: &mut ViewContext<Self>,
 8228    ) {
 8229        if let Some(nav_history) = self.nav_history.as_mut() {
 8230            let buffer = self.buffer.read(cx).read(cx);
 8231            let cursor_position = cursor_anchor.to_point(&buffer);
 8232            let scroll_state = self.scroll_manager.anchor();
 8233            let scroll_top_row = scroll_state.top_row(&buffer);
 8234            drop(buffer);
 8235
 8236            if let Some(new_position) = new_position {
 8237                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8238                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8239                    return;
 8240                }
 8241            }
 8242
 8243            nav_history.push(
 8244                Some(NavigationData {
 8245                    cursor_anchor,
 8246                    cursor_position,
 8247                    scroll_anchor: scroll_state,
 8248                    scroll_top_row,
 8249                }),
 8250                cx,
 8251            );
 8252        }
 8253    }
 8254
 8255    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8256        let buffer = self.buffer.read(cx).snapshot(cx);
 8257        let mut selection = self.selections.first::<usize>(cx);
 8258        selection.set_head(buffer.len(), SelectionGoal::None);
 8259        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8260            s.select(vec![selection]);
 8261        });
 8262    }
 8263
 8264    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8265        let end = self.buffer.read(cx).read(cx).len();
 8266        self.change_selections(None, cx, |s| {
 8267            s.select_ranges(vec![0..end]);
 8268        });
 8269    }
 8270
 8271    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8272        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8273        let mut selections = self.selections.all::<Point>(cx);
 8274        let max_point = display_map.buffer_snapshot.max_point();
 8275        for selection in &mut selections {
 8276            let rows = selection.spanned_rows(true, &display_map);
 8277            selection.start = Point::new(rows.start.0, 0);
 8278            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8279            selection.reversed = false;
 8280        }
 8281        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8282            s.select(selections);
 8283        });
 8284    }
 8285
 8286    pub fn split_selection_into_lines(
 8287        &mut self,
 8288        _: &SplitSelectionIntoLines,
 8289        cx: &mut ViewContext<Self>,
 8290    ) {
 8291        let mut to_unfold = Vec::new();
 8292        let mut new_selection_ranges = Vec::new();
 8293        {
 8294            let selections = self.selections.all::<Point>(cx);
 8295            let buffer = self.buffer.read(cx).read(cx);
 8296            for selection in selections {
 8297                for row in selection.start.row..selection.end.row {
 8298                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8299                    new_selection_ranges.push(cursor..cursor);
 8300                }
 8301                new_selection_ranges.push(selection.end..selection.end);
 8302                to_unfold.push(selection.start..selection.end);
 8303            }
 8304        }
 8305        self.unfold_ranges(&to_unfold, true, true, cx);
 8306        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8307            s.select_ranges(new_selection_ranges);
 8308        });
 8309    }
 8310
 8311    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8312        self.add_selection(true, cx);
 8313    }
 8314
 8315    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8316        self.add_selection(false, cx);
 8317    }
 8318
 8319    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8320        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8321        let mut selections = self.selections.all::<Point>(cx);
 8322        let text_layout_details = self.text_layout_details(cx);
 8323        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8324            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8325            let range = oldest_selection.display_range(&display_map).sorted();
 8326
 8327            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8328            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8329            let positions = start_x.min(end_x)..start_x.max(end_x);
 8330
 8331            selections.clear();
 8332            let mut stack = Vec::new();
 8333            for row in range.start.row().0..=range.end.row().0 {
 8334                if let Some(selection) = self.selections.build_columnar_selection(
 8335                    &display_map,
 8336                    DisplayRow(row),
 8337                    &positions,
 8338                    oldest_selection.reversed,
 8339                    &text_layout_details,
 8340                ) {
 8341                    stack.push(selection.id);
 8342                    selections.push(selection);
 8343                }
 8344            }
 8345
 8346            if above {
 8347                stack.reverse();
 8348            }
 8349
 8350            AddSelectionsState { above, stack }
 8351        });
 8352
 8353        let last_added_selection = *state.stack.last().unwrap();
 8354        let mut new_selections = Vec::new();
 8355        if above == state.above {
 8356            let end_row = if above {
 8357                DisplayRow(0)
 8358            } else {
 8359                display_map.max_point().row()
 8360            };
 8361
 8362            'outer: for selection in selections {
 8363                if selection.id == last_added_selection {
 8364                    let range = selection.display_range(&display_map).sorted();
 8365                    debug_assert_eq!(range.start.row(), range.end.row());
 8366                    let mut row = range.start.row();
 8367                    let positions =
 8368                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8369                            px(start)..px(end)
 8370                        } else {
 8371                            let start_x =
 8372                                display_map.x_for_display_point(range.start, &text_layout_details);
 8373                            let end_x =
 8374                                display_map.x_for_display_point(range.end, &text_layout_details);
 8375                            start_x.min(end_x)..start_x.max(end_x)
 8376                        };
 8377
 8378                    while row != end_row {
 8379                        if above {
 8380                            row.0 -= 1;
 8381                        } else {
 8382                            row.0 += 1;
 8383                        }
 8384
 8385                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8386                            &display_map,
 8387                            row,
 8388                            &positions,
 8389                            selection.reversed,
 8390                            &text_layout_details,
 8391                        ) {
 8392                            state.stack.push(new_selection.id);
 8393                            if above {
 8394                                new_selections.push(new_selection);
 8395                                new_selections.push(selection);
 8396                            } else {
 8397                                new_selections.push(selection);
 8398                                new_selections.push(new_selection);
 8399                            }
 8400
 8401                            continue 'outer;
 8402                        }
 8403                    }
 8404                }
 8405
 8406                new_selections.push(selection);
 8407            }
 8408        } else {
 8409            new_selections = selections;
 8410            new_selections.retain(|s| s.id != last_added_selection);
 8411            state.stack.pop();
 8412        }
 8413
 8414        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8415            s.select(new_selections);
 8416        });
 8417        if state.stack.len() > 1 {
 8418            self.add_selections_state = Some(state);
 8419        }
 8420    }
 8421
 8422    pub fn select_next_match_internal(
 8423        &mut self,
 8424        display_map: &DisplaySnapshot,
 8425        replace_newest: bool,
 8426        autoscroll: Option<Autoscroll>,
 8427        cx: &mut ViewContext<Self>,
 8428    ) -> Result<()> {
 8429        fn select_next_match_ranges(
 8430            this: &mut Editor,
 8431            range: Range<usize>,
 8432            replace_newest: bool,
 8433            auto_scroll: Option<Autoscroll>,
 8434            cx: &mut ViewContext<Editor>,
 8435        ) {
 8436            this.unfold_ranges(&[range.clone()], false, true, cx);
 8437            this.change_selections(auto_scroll, cx, |s| {
 8438                if replace_newest {
 8439                    s.delete(s.newest_anchor().id);
 8440                }
 8441                s.insert_range(range.clone());
 8442            });
 8443        }
 8444
 8445        let buffer = &display_map.buffer_snapshot;
 8446        let mut selections = self.selections.all::<usize>(cx);
 8447        if let Some(mut select_next_state) = self.select_next_state.take() {
 8448            let query = &select_next_state.query;
 8449            if !select_next_state.done {
 8450                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8451                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8452                let mut next_selected_range = None;
 8453
 8454                let bytes_after_last_selection =
 8455                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8456                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8457                let query_matches = query
 8458                    .stream_find_iter(bytes_after_last_selection)
 8459                    .map(|result| (last_selection.end, result))
 8460                    .chain(
 8461                        query
 8462                            .stream_find_iter(bytes_before_first_selection)
 8463                            .map(|result| (0, result)),
 8464                    );
 8465
 8466                for (start_offset, query_match) in query_matches {
 8467                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8468                    let offset_range =
 8469                        start_offset + query_match.start()..start_offset + query_match.end();
 8470                    let display_range = offset_range.start.to_display_point(display_map)
 8471                        ..offset_range.end.to_display_point(display_map);
 8472
 8473                    if !select_next_state.wordwise
 8474                        || (!movement::is_inside_word(display_map, display_range.start)
 8475                            && !movement::is_inside_word(display_map, display_range.end))
 8476                    {
 8477                        // TODO: This is n^2, because we might check all the selections
 8478                        if !selections
 8479                            .iter()
 8480                            .any(|selection| selection.range().overlaps(&offset_range))
 8481                        {
 8482                            next_selected_range = Some(offset_range);
 8483                            break;
 8484                        }
 8485                    }
 8486                }
 8487
 8488                if let Some(next_selected_range) = next_selected_range {
 8489                    select_next_match_ranges(
 8490                        self,
 8491                        next_selected_range,
 8492                        replace_newest,
 8493                        autoscroll,
 8494                        cx,
 8495                    );
 8496                } else {
 8497                    select_next_state.done = true;
 8498                }
 8499            }
 8500
 8501            self.select_next_state = Some(select_next_state);
 8502        } else {
 8503            let mut only_carets = true;
 8504            let mut same_text_selected = true;
 8505            let mut selected_text = None;
 8506
 8507            let mut selections_iter = selections.iter().peekable();
 8508            while let Some(selection) = selections_iter.next() {
 8509                if selection.start != selection.end {
 8510                    only_carets = false;
 8511                }
 8512
 8513                if same_text_selected {
 8514                    if selected_text.is_none() {
 8515                        selected_text =
 8516                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8517                    }
 8518
 8519                    if let Some(next_selection) = selections_iter.peek() {
 8520                        if next_selection.range().len() == selection.range().len() {
 8521                            let next_selected_text = buffer
 8522                                .text_for_range(next_selection.range())
 8523                                .collect::<String>();
 8524                            if Some(next_selected_text) != selected_text {
 8525                                same_text_selected = false;
 8526                                selected_text = None;
 8527                            }
 8528                        } else {
 8529                            same_text_selected = false;
 8530                            selected_text = None;
 8531                        }
 8532                    }
 8533                }
 8534            }
 8535
 8536            if only_carets {
 8537                for selection in &mut selections {
 8538                    let word_range = movement::surrounding_word(
 8539                        display_map,
 8540                        selection.start.to_display_point(display_map),
 8541                    );
 8542                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8543                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8544                    selection.goal = SelectionGoal::None;
 8545                    selection.reversed = false;
 8546                    select_next_match_ranges(
 8547                        self,
 8548                        selection.start..selection.end,
 8549                        replace_newest,
 8550                        autoscroll,
 8551                        cx,
 8552                    );
 8553                }
 8554
 8555                if selections.len() == 1 {
 8556                    let selection = selections
 8557                        .last()
 8558                        .expect("ensured that there's only one selection");
 8559                    let query = buffer
 8560                        .text_for_range(selection.start..selection.end)
 8561                        .collect::<String>();
 8562                    let is_empty = query.is_empty();
 8563                    let select_state = SelectNextState {
 8564                        query: AhoCorasick::new(&[query])?,
 8565                        wordwise: true,
 8566                        done: is_empty,
 8567                    };
 8568                    self.select_next_state = Some(select_state);
 8569                } else {
 8570                    self.select_next_state = None;
 8571                }
 8572            } else if let Some(selected_text) = selected_text {
 8573                self.select_next_state = Some(SelectNextState {
 8574                    query: AhoCorasick::new(&[selected_text])?,
 8575                    wordwise: false,
 8576                    done: false,
 8577                });
 8578                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8579            }
 8580        }
 8581        Ok(())
 8582    }
 8583
 8584    pub fn select_all_matches(
 8585        &mut self,
 8586        _action: &SelectAllMatches,
 8587        cx: &mut ViewContext<Self>,
 8588    ) -> Result<()> {
 8589        self.push_to_selection_history();
 8590        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8591
 8592        self.select_next_match_internal(&display_map, false, None, cx)?;
 8593        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8594            return Ok(());
 8595        };
 8596        if select_next_state.done {
 8597            return Ok(());
 8598        }
 8599
 8600        let mut new_selections = self.selections.all::<usize>(cx);
 8601
 8602        let buffer = &display_map.buffer_snapshot;
 8603        let query_matches = select_next_state
 8604            .query
 8605            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8606
 8607        for query_match in query_matches {
 8608            let query_match = query_match.unwrap(); // can only fail due to I/O
 8609            let offset_range = query_match.start()..query_match.end();
 8610            let display_range = offset_range.start.to_display_point(&display_map)
 8611                ..offset_range.end.to_display_point(&display_map);
 8612
 8613            if !select_next_state.wordwise
 8614                || (!movement::is_inside_word(&display_map, display_range.start)
 8615                    && !movement::is_inside_word(&display_map, display_range.end))
 8616            {
 8617                self.selections.change_with(cx, |selections| {
 8618                    new_selections.push(Selection {
 8619                        id: selections.new_selection_id(),
 8620                        start: offset_range.start,
 8621                        end: offset_range.end,
 8622                        reversed: false,
 8623                        goal: SelectionGoal::None,
 8624                    });
 8625                });
 8626            }
 8627        }
 8628
 8629        new_selections.sort_by_key(|selection| selection.start);
 8630        let mut ix = 0;
 8631        while ix + 1 < new_selections.len() {
 8632            let current_selection = &new_selections[ix];
 8633            let next_selection = &new_selections[ix + 1];
 8634            if current_selection.range().overlaps(&next_selection.range()) {
 8635                if current_selection.id < next_selection.id {
 8636                    new_selections.remove(ix + 1);
 8637                } else {
 8638                    new_selections.remove(ix);
 8639                }
 8640            } else {
 8641                ix += 1;
 8642            }
 8643        }
 8644
 8645        select_next_state.done = true;
 8646        self.unfold_ranges(
 8647            &new_selections
 8648                .iter()
 8649                .map(|selection| selection.range())
 8650                .collect::<Vec<_>>(),
 8651            false,
 8652            false,
 8653            cx,
 8654        );
 8655        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8656            selections.select(new_selections)
 8657        });
 8658
 8659        Ok(())
 8660    }
 8661
 8662    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8663        self.push_to_selection_history();
 8664        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8665        self.select_next_match_internal(
 8666            &display_map,
 8667            action.replace_newest,
 8668            Some(Autoscroll::newest()),
 8669            cx,
 8670        )?;
 8671        Ok(())
 8672    }
 8673
 8674    pub fn select_previous(
 8675        &mut self,
 8676        action: &SelectPrevious,
 8677        cx: &mut ViewContext<Self>,
 8678    ) -> Result<()> {
 8679        self.push_to_selection_history();
 8680        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8681        let buffer = &display_map.buffer_snapshot;
 8682        let mut selections = self.selections.all::<usize>(cx);
 8683        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8684            let query = &select_prev_state.query;
 8685            if !select_prev_state.done {
 8686                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8687                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8688                let mut next_selected_range = None;
 8689                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8690                let bytes_before_last_selection =
 8691                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8692                let bytes_after_first_selection =
 8693                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8694                let query_matches = query
 8695                    .stream_find_iter(bytes_before_last_selection)
 8696                    .map(|result| (last_selection.start, result))
 8697                    .chain(
 8698                        query
 8699                            .stream_find_iter(bytes_after_first_selection)
 8700                            .map(|result| (buffer.len(), result)),
 8701                    );
 8702                for (end_offset, query_match) in query_matches {
 8703                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8704                    let offset_range =
 8705                        end_offset - query_match.end()..end_offset - query_match.start();
 8706                    let display_range = offset_range.start.to_display_point(&display_map)
 8707                        ..offset_range.end.to_display_point(&display_map);
 8708
 8709                    if !select_prev_state.wordwise
 8710                        || (!movement::is_inside_word(&display_map, display_range.start)
 8711                            && !movement::is_inside_word(&display_map, display_range.end))
 8712                    {
 8713                        next_selected_range = Some(offset_range);
 8714                        break;
 8715                    }
 8716                }
 8717
 8718                if let Some(next_selected_range) = next_selected_range {
 8719                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8720                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8721                        if action.replace_newest {
 8722                            s.delete(s.newest_anchor().id);
 8723                        }
 8724                        s.insert_range(next_selected_range);
 8725                    });
 8726                } else {
 8727                    select_prev_state.done = true;
 8728                }
 8729            }
 8730
 8731            self.select_prev_state = Some(select_prev_state);
 8732        } else {
 8733            let mut only_carets = true;
 8734            let mut same_text_selected = true;
 8735            let mut selected_text = None;
 8736
 8737            let mut selections_iter = selections.iter().peekable();
 8738            while let Some(selection) = selections_iter.next() {
 8739                if selection.start != selection.end {
 8740                    only_carets = false;
 8741                }
 8742
 8743                if same_text_selected {
 8744                    if selected_text.is_none() {
 8745                        selected_text =
 8746                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8747                    }
 8748
 8749                    if let Some(next_selection) = selections_iter.peek() {
 8750                        if next_selection.range().len() == selection.range().len() {
 8751                            let next_selected_text = buffer
 8752                                .text_for_range(next_selection.range())
 8753                                .collect::<String>();
 8754                            if Some(next_selected_text) != selected_text {
 8755                                same_text_selected = false;
 8756                                selected_text = None;
 8757                            }
 8758                        } else {
 8759                            same_text_selected = false;
 8760                            selected_text = None;
 8761                        }
 8762                    }
 8763                }
 8764            }
 8765
 8766            if only_carets {
 8767                for selection in &mut selections {
 8768                    let word_range = movement::surrounding_word(
 8769                        &display_map,
 8770                        selection.start.to_display_point(&display_map),
 8771                    );
 8772                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8773                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8774                    selection.goal = SelectionGoal::None;
 8775                    selection.reversed = false;
 8776                }
 8777                if selections.len() == 1 {
 8778                    let selection = selections
 8779                        .last()
 8780                        .expect("ensured that there's only one selection");
 8781                    let query = buffer
 8782                        .text_for_range(selection.start..selection.end)
 8783                        .collect::<String>();
 8784                    let is_empty = query.is_empty();
 8785                    let select_state = SelectNextState {
 8786                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8787                        wordwise: true,
 8788                        done: is_empty,
 8789                    };
 8790                    self.select_prev_state = Some(select_state);
 8791                } else {
 8792                    self.select_prev_state = None;
 8793                }
 8794
 8795                self.unfold_ranges(
 8796                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8797                    false,
 8798                    true,
 8799                    cx,
 8800                );
 8801                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8802                    s.select(selections);
 8803                });
 8804            } else if let Some(selected_text) = selected_text {
 8805                self.select_prev_state = Some(SelectNextState {
 8806                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8807                    wordwise: false,
 8808                    done: false,
 8809                });
 8810                self.select_previous(action, cx)?;
 8811            }
 8812        }
 8813        Ok(())
 8814    }
 8815
 8816    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8817        if self.read_only(cx) {
 8818            return;
 8819        }
 8820        let text_layout_details = &self.text_layout_details(cx);
 8821        self.transact(cx, |this, cx| {
 8822            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8823            let mut edits = Vec::new();
 8824            let mut selection_edit_ranges = Vec::new();
 8825            let mut last_toggled_row = None;
 8826            let snapshot = this.buffer.read(cx).read(cx);
 8827            let empty_str: Arc<str> = Arc::default();
 8828            let mut suffixes_inserted = Vec::new();
 8829            let ignore_indent = action.ignore_indent;
 8830
 8831            fn comment_prefix_range(
 8832                snapshot: &MultiBufferSnapshot,
 8833                row: MultiBufferRow,
 8834                comment_prefix: &str,
 8835                comment_prefix_whitespace: &str,
 8836                ignore_indent: bool,
 8837            ) -> Range<Point> {
 8838                let indent_size = if ignore_indent {
 8839                    0
 8840                } else {
 8841                    snapshot.indent_size_for_line(row).len
 8842                };
 8843
 8844                let start = Point::new(row.0, indent_size);
 8845
 8846                let mut line_bytes = snapshot
 8847                    .bytes_in_range(start..snapshot.max_point())
 8848                    .flatten()
 8849                    .copied();
 8850
 8851                // If this line currently begins with the line comment prefix, then record
 8852                // the range containing the prefix.
 8853                if line_bytes
 8854                    .by_ref()
 8855                    .take(comment_prefix.len())
 8856                    .eq(comment_prefix.bytes())
 8857                {
 8858                    // Include any whitespace that matches the comment prefix.
 8859                    let matching_whitespace_len = line_bytes
 8860                        .zip(comment_prefix_whitespace.bytes())
 8861                        .take_while(|(a, b)| a == b)
 8862                        .count() as u32;
 8863                    let end = Point::new(
 8864                        start.row,
 8865                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8866                    );
 8867                    start..end
 8868                } else {
 8869                    start..start
 8870                }
 8871            }
 8872
 8873            fn comment_suffix_range(
 8874                snapshot: &MultiBufferSnapshot,
 8875                row: MultiBufferRow,
 8876                comment_suffix: &str,
 8877                comment_suffix_has_leading_space: bool,
 8878            ) -> Range<Point> {
 8879                let end = Point::new(row.0, snapshot.line_len(row));
 8880                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8881
 8882                let mut line_end_bytes = snapshot
 8883                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8884                    .flatten()
 8885                    .copied();
 8886
 8887                let leading_space_len = if suffix_start_column > 0
 8888                    && line_end_bytes.next() == Some(b' ')
 8889                    && comment_suffix_has_leading_space
 8890                {
 8891                    1
 8892                } else {
 8893                    0
 8894                };
 8895
 8896                // If this line currently begins with the line comment prefix, then record
 8897                // the range containing the prefix.
 8898                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8899                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8900                    start..end
 8901                } else {
 8902                    end..end
 8903                }
 8904            }
 8905
 8906            // TODO: Handle selections that cross excerpts
 8907            for selection in &mut selections {
 8908                let start_column = snapshot
 8909                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8910                    .len;
 8911                let language = if let Some(language) =
 8912                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8913                {
 8914                    language
 8915                } else {
 8916                    continue;
 8917                };
 8918
 8919                selection_edit_ranges.clear();
 8920
 8921                // If multiple selections contain a given row, avoid processing that
 8922                // row more than once.
 8923                let mut start_row = MultiBufferRow(selection.start.row);
 8924                if last_toggled_row == Some(start_row) {
 8925                    start_row = start_row.next_row();
 8926                }
 8927                let end_row =
 8928                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8929                        MultiBufferRow(selection.end.row - 1)
 8930                    } else {
 8931                        MultiBufferRow(selection.end.row)
 8932                    };
 8933                last_toggled_row = Some(end_row);
 8934
 8935                if start_row > end_row {
 8936                    continue;
 8937                }
 8938
 8939                // If the language has line comments, toggle those.
 8940                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8941
 8942                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8943                if ignore_indent {
 8944                    full_comment_prefixes = full_comment_prefixes
 8945                        .into_iter()
 8946                        .map(|s| Arc::from(s.trim_end()))
 8947                        .collect();
 8948                }
 8949
 8950                if !full_comment_prefixes.is_empty() {
 8951                    let first_prefix = full_comment_prefixes
 8952                        .first()
 8953                        .expect("prefixes is non-empty");
 8954                    let prefix_trimmed_lengths = full_comment_prefixes
 8955                        .iter()
 8956                        .map(|p| p.trim_end_matches(' ').len())
 8957                        .collect::<SmallVec<[usize; 4]>>();
 8958
 8959                    let mut all_selection_lines_are_comments = true;
 8960
 8961                    for row in start_row.0..=end_row.0 {
 8962                        let row = MultiBufferRow(row);
 8963                        if start_row < end_row && snapshot.is_line_blank(row) {
 8964                            continue;
 8965                        }
 8966
 8967                        let prefix_range = full_comment_prefixes
 8968                            .iter()
 8969                            .zip(prefix_trimmed_lengths.iter().copied())
 8970                            .map(|(prefix, trimmed_prefix_len)| {
 8971                                comment_prefix_range(
 8972                                    snapshot.deref(),
 8973                                    row,
 8974                                    &prefix[..trimmed_prefix_len],
 8975                                    &prefix[trimmed_prefix_len..],
 8976                                    ignore_indent,
 8977                                )
 8978                            })
 8979                            .max_by_key(|range| range.end.column - range.start.column)
 8980                            .expect("prefixes is non-empty");
 8981
 8982                        if prefix_range.is_empty() {
 8983                            all_selection_lines_are_comments = false;
 8984                        }
 8985
 8986                        selection_edit_ranges.push(prefix_range);
 8987                    }
 8988
 8989                    if all_selection_lines_are_comments {
 8990                        edits.extend(
 8991                            selection_edit_ranges
 8992                                .iter()
 8993                                .cloned()
 8994                                .map(|range| (range, empty_str.clone())),
 8995                        );
 8996                    } else {
 8997                        let min_column = selection_edit_ranges
 8998                            .iter()
 8999                            .map(|range| range.start.column)
 9000                            .min()
 9001                            .unwrap_or(0);
 9002                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9003                            let position = Point::new(range.start.row, min_column);
 9004                            (position..position, first_prefix.clone())
 9005                        }));
 9006                    }
 9007                } else if let Some((full_comment_prefix, comment_suffix)) =
 9008                    language.block_comment_delimiters()
 9009                {
 9010                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9011                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9012                    let prefix_range = comment_prefix_range(
 9013                        snapshot.deref(),
 9014                        start_row,
 9015                        comment_prefix,
 9016                        comment_prefix_whitespace,
 9017                        ignore_indent,
 9018                    );
 9019                    let suffix_range = comment_suffix_range(
 9020                        snapshot.deref(),
 9021                        end_row,
 9022                        comment_suffix.trim_start_matches(' '),
 9023                        comment_suffix.starts_with(' '),
 9024                    );
 9025
 9026                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9027                        edits.push((
 9028                            prefix_range.start..prefix_range.start,
 9029                            full_comment_prefix.clone(),
 9030                        ));
 9031                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9032                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9033                    } else {
 9034                        edits.push((prefix_range, empty_str.clone()));
 9035                        edits.push((suffix_range, empty_str.clone()));
 9036                    }
 9037                } else {
 9038                    continue;
 9039                }
 9040            }
 9041
 9042            drop(snapshot);
 9043            this.buffer.update(cx, |buffer, cx| {
 9044                buffer.edit(edits, None, cx);
 9045            });
 9046
 9047            // Adjust selections so that they end before any comment suffixes that
 9048            // were inserted.
 9049            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9050            let mut selections = this.selections.all::<Point>(cx);
 9051            let snapshot = this.buffer.read(cx).read(cx);
 9052            for selection in &mut selections {
 9053                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9054                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9055                        Ordering::Less => {
 9056                            suffixes_inserted.next();
 9057                            continue;
 9058                        }
 9059                        Ordering::Greater => break,
 9060                        Ordering::Equal => {
 9061                            if selection.end.column == snapshot.line_len(row) {
 9062                                if selection.is_empty() {
 9063                                    selection.start.column -= suffix_len as u32;
 9064                                }
 9065                                selection.end.column -= suffix_len as u32;
 9066                            }
 9067                            break;
 9068                        }
 9069                    }
 9070                }
 9071            }
 9072
 9073            drop(snapshot);
 9074            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9075
 9076            let selections = this.selections.all::<Point>(cx);
 9077            let selections_on_single_row = selections.windows(2).all(|selections| {
 9078                selections[0].start.row == selections[1].start.row
 9079                    && selections[0].end.row == selections[1].end.row
 9080                    && selections[0].start.row == selections[0].end.row
 9081            });
 9082            let selections_selecting = selections
 9083                .iter()
 9084                .any(|selection| selection.start != selection.end);
 9085            let advance_downwards = action.advance_downwards
 9086                && selections_on_single_row
 9087                && !selections_selecting
 9088                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9089
 9090            if advance_downwards {
 9091                let snapshot = this.buffer.read(cx).snapshot(cx);
 9092
 9093                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9094                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9095                        let mut point = display_point.to_point(display_snapshot);
 9096                        point.row += 1;
 9097                        point = snapshot.clip_point(point, Bias::Left);
 9098                        let display_point = point.to_display_point(display_snapshot);
 9099                        let goal = SelectionGoal::HorizontalPosition(
 9100                            display_snapshot
 9101                                .x_for_display_point(display_point, text_layout_details)
 9102                                .into(),
 9103                        );
 9104                        (display_point, goal)
 9105                    })
 9106                });
 9107            }
 9108        });
 9109    }
 9110
 9111    pub fn select_enclosing_symbol(
 9112        &mut self,
 9113        _: &SelectEnclosingSymbol,
 9114        cx: &mut ViewContext<Self>,
 9115    ) {
 9116        let buffer = self.buffer.read(cx).snapshot(cx);
 9117        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9118
 9119        fn update_selection(
 9120            selection: &Selection<usize>,
 9121            buffer_snap: &MultiBufferSnapshot,
 9122        ) -> Option<Selection<usize>> {
 9123            let cursor = selection.head();
 9124            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9125            for symbol in symbols.iter().rev() {
 9126                let start = symbol.range.start.to_offset(buffer_snap);
 9127                let end = symbol.range.end.to_offset(buffer_snap);
 9128                let new_range = start..end;
 9129                if start < selection.start || end > selection.end {
 9130                    return Some(Selection {
 9131                        id: selection.id,
 9132                        start: new_range.start,
 9133                        end: new_range.end,
 9134                        goal: SelectionGoal::None,
 9135                        reversed: selection.reversed,
 9136                    });
 9137                }
 9138            }
 9139            None
 9140        }
 9141
 9142        let mut selected_larger_symbol = false;
 9143        let new_selections = old_selections
 9144            .iter()
 9145            .map(|selection| match update_selection(selection, &buffer) {
 9146                Some(new_selection) => {
 9147                    if new_selection.range() != selection.range() {
 9148                        selected_larger_symbol = true;
 9149                    }
 9150                    new_selection
 9151                }
 9152                None => selection.clone(),
 9153            })
 9154            .collect::<Vec<_>>();
 9155
 9156        if selected_larger_symbol {
 9157            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9158                s.select(new_selections);
 9159            });
 9160        }
 9161    }
 9162
 9163    pub fn select_larger_syntax_node(
 9164        &mut self,
 9165        _: &SelectLargerSyntaxNode,
 9166        cx: &mut ViewContext<Self>,
 9167    ) {
 9168        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9169        let buffer = self.buffer.read(cx).snapshot(cx);
 9170        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9171
 9172        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9173        let mut selected_larger_node = false;
 9174        let new_selections = old_selections
 9175            .iter()
 9176            .map(|selection| {
 9177                let old_range = selection.start..selection.end;
 9178                let mut new_range = old_range.clone();
 9179                while let Some(containing_range) =
 9180                    buffer.range_for_syntax_ancestor(new_range.clone())
 9181                {
 9182                    new_range = containing_range;
 9183                    if !display_map.intersects_fold(new_range.start)
 9184                        && !display_map.intersects_fold(new_range.end)
 9185                    {
 9186                        break;
 9187                    }
 9188                }
 9189
 9190                selected_larger_node |= new_range != old_range;
 9191                Selection {
 9192                    id: selection.id,
 9193                    start: new_range.start,
 9194                    end: new_range.end,
 9195                    goal: SelectionGoal::None,
 9196                    reversed: selection.reversed,
 9197                }
 9198            })
 9199            .collect::<Vec<_>>();
 9200
 9201        if selected_larger_node {
 9202            stack.push(old_selections);
 9203            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9204                s.select(new_selections);
 9205            });
 9206        }
 9207        self.select_larger_syntax_node_stack = stack;
 9208    }
 9209
 9210    pub fn select_smaller_syntax_node(
 9211        &mut self,
 9212        _: &SelectSmallerSyntaxNode,
 9213        cx: &mut ViewContext<Self>,
 9214    ) {
 9215        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9216        if let Some(selections) = stack.pop() {
 9217            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9218                s.select(selections.to_vec());
 9219            });
 9220        }
 9221        self.select_larger_syntax_node_stack = stack;
 9222    }
 9223
 9224    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9225        if !EditorSettings::get_global(cx).gutter.runnables {
 9226            self.clear_tasks();
 9227            return Task::ready(());
 9228        }
 9229        let project = self.project.as_ref().map(Model::downgrade);
 9230        cx.spawn(|this, mut cx| async move {
 9231            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9232            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9233                return;
 9234            };
 9235            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9236                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9237            }) else {
 9238                return;
 9239            };
 9240
 9241            let hide_runnables = project
 9242                .update(&mut cx, |project, cx| {
 9243                    // Do not display any test indicators in non-dev server remote projects.
 9244                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9245                })
 9246                .unwrap_or(true);
 9247            if hide_runnables {
 9248                return;
 9249            }
 9250            let new_rows =
 9251                cx.background_executor()
 9252                    .spawn({
 9253                        let snapshot = display_snapshot.clone();
 9254                        async move {
 9255                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9256                        }
 9257                    })
 9258                    .await;
 9259            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9260
 9261            this.update(&mut cx, |this, _| {
 9262                this.clear_tasks();
 9263                for (key, value) in rows {
 9264                    this.insert_tasks(key, value);
 9265                }
 9266            })
 9267            .ok();
 9268        })
 9269    }
 9270    fn fetch_runnable_ranges(
 9271        snapshot: &DisplaySnapshot,
 9272        range: Range<Anchor>,
 9273    ) -> Vec<language::RunnableRange> {
 9274        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9275    }
 9276
 9277    fn runnable_rows(
 9278        project: Model<Project>,
 9279        snapshot: DisplaySnapshot,
 9280        runnable_ranges: Vec<RunnableRange>,
 9281        mut cx: AsyncWindowContext,
 9282    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9283        runnable_ranges
 9284            .into_iter()
 9285            .filter_map(|mut runnable| {
 9286                let tasks = cx
 9287                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9288                    .ok()?;
 9289                if tasks.is_empty() {
 9290                    return None;
 9291                }
 9292
 9293                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9294
 9295                let row = snapshot
 9296                    .buffer_snapshot
 9297                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9298                    .1
 9299                    .start
 9300                    .row;
 9301
 9302                let context_range =
 9303                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9304                Some((
 9305                    (runnable.buffer_id, row),
 9306                    RunnableTasks {
 9307                        templates: tasks,
 9308                        offset: MultiBufferOffset(runnable.run_range.start),
 9309                        context_range,
 9310                        column: point.column,
 9311                        extra_variables: runnable.extra_captures,
 9312                    },
 9313                ))
 9314            })
 9315            .collect()
 9316    }
 9317
 9318    fn templates_with_tags(
 9319        project: &Model<Project>,
 9320        runnable: &mut Runnable,
 9321        cx: &WindowContext<'_>,
 9322    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9323        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9324            let (worktree_id, file) = project
 9325                .buffer_for_id(runnable.buffer, cx)
 9326                .and_then(|buffer| buffer.read(cx).file())
 9327                .map(|file| (file.worktree_id(cx), file.clone()))
 9328                .unzip();
 9329
 9330            (
 9331                project.task_store().read(cx).task_inventory().cloned(),
 9332                worktree_id,
 9333                file,
 9334            )
 9335        });
 9336
 9337        let tags = mem::take(&mut runnable.tags);
 9338        let mut tags: Vec<_> = tags
 9339            .into_iter()
 9340            .flat_map(|tag| {
 9341                let tag = tag.0.clone();
 9342                inventory
 9343                    .as_ref()
 9344                    .into_iter()
 9345                    .flat_map(|inventory| {
 9346                        inventory.read(cx).list_tasks(
 9347                            file.clone(),
 9348                            Some(runnable.language.clone()),
 9349                            worktree_id,
 9350                            cx,
 9351                        )
 9352                    })
 9353                    .filter(move |(_, template)| {
 9354                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9355                    })
 9356            })
 9357            .sorted_by_key(|(kind, _)| kind.to_owned())
 9358            .collect();
 9359        if let Some((leading_tag_source, _)) = tags.first() {
 9360            // Strongest source wins; if we have worktree tag binding, prefer that to
 9361            // global and language bindings;
 9362            // if we have a global binding, prefer that to language binding.
 9363            let first_mismatch = tags
 9364                .iter()
 9365                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9366            if let Some(index) = first_mismatch {
 9367                tags.truncate(index);
 9368            }
 9369        }
 9370
 9371        tags
 9372    }
 9373
 9374    pub fn move_to_enclosing_bracket(
 9375        &mut self,
 9376        _: &MoveToEnclosingBracket,
 9377        cx: &mut ViewContext<Self>,
 9378    ) {
 9379        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9380            s.move_offsets_with(|snapshot, selection| {
 9381                let Some(enclosing_bracket_ranges) =
 9382                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9383                else {
 9384                    return;
 9385                };
 9386
 9387                let mut best_length = usize::MAX;
 9388                let mut best_inside = false;
 9389                let mut best_in_bracket_range = false;
 9390                let mut best_destination = None;
 9391                for (open, close) in enclosing_bracket_ranges {
 9392                    let close = close.to_inclusive();
 9393                    let length = close.end() - open.start;
 9394                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9395                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9396                        || close.contains(&selection.head());
 9397
 9398                    // If best is next to a bracket and current isn't, skip
 9399                    if !in_bracket_range && best_in_bracket_range {
 9400                        continue;
 9401                    }
 9402
 9403                    // Prefer smaller lengths unless best is inside and current isn't
 9404                    if length > best_length && (best_inside || !inside) {
 9405                        continue;
 9406                    }
 9407
 9408                    best_length = length;
 9409                    best_inside = inside;
 9410                    best_in_bracket_range = in_bracket_range;
 9411                    best_destination = Some(
 9412                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9413                            if inside {
 9414                                open.end
 9415                            } else {
 9416                                open.start
 9417                            }
 9418                        } else if inside {
 9419                            *close.start()
 9420                        } else {
 9421                            *close.end()
 9422                        },
 9423                    );
 9424                }
 9425
 9426                if let Some(destination) = best_destination {
 9427                    selection.collapse_to(destination, SelectionGoal::None);
 9428                }
 9429            })
 9430        });
 9431    }
 9432
 9433    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9434        self.end_selection(cx);
 9435        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9436        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9437            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9438            self.select_next_state = entry.select_next_state;
 9439            self.select_prev_state = entry.select_prev_state;
 9440            self.add_selections_state = entry.add_selections_state;
 9441            self.request_autoscroll(Autoscroll::newest(), cx);
 9442        }
 9443        self.selection_history.mode = SelectionHistoryMode::Normal;
 9444    }
 9445
 9446    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9447        self.end_selection(cx);
 9448        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9449        if let Some(entry) = self.selection_history.redo_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 expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9460        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9461    }
 9462
 9463    pub fn expand_excerpts_down(
 9464        &mut self,
 9465        action: &ExpandExcerptsDown,
 9466        cx: &mut ViewContext<Self>,
 9467    ) {
 9468        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9469    }
 9470
 9471    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9472        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9473    }
 9474
 9475    pub fn expand_excerpts_for_direction(
 9476        &mut self,
 9477        lines: u32,
 9478        direction: ExpandExcerptDirection,
 9479        cx: &mut ViewContext<Self>,
 9480    ) {
 9481        let selections = self.selections.disjoint_anchors();
 9482
 9483        let lines = if lines == 0 {
 9484            EditorSettings::get_global(cx).expand_excerpt_lines
 9485        } else {
 9486            lines
 9487        };
 9488
 9489        self.buffer.update(cx, |buffer, cx| {
 9490            buffer.expand_excerpts(
 9491                selections
 9492                    .iter()
 9493                    .map(|selection| selection.head().excerpt_id)
 9494                    .dedup(),
 9495                lines,
 9496                direction,
 9497                cx,
 9498            )
 9499        })
 9500    }
 9501
 9502    pub fn expand_excerpt(
 9503        &mut self,
 9504        excerpt: ExcerptId,
 9505        direction: ExpandExcerptDirection,
 9506        cx: &mut ViewContext<Self>,
 9507    ) {
 9508        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9509        self.buffer.update(cx, |buffer, cx| {
 9510            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9511        })
 9512    }
 9513
 9514    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9515        self.go_to_diagnostic_impl(Direction::Next, cx)
 9516    }
 9517
 9518    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9519        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9520    }
 9521
 9522    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9523        let buffer = self.buffer.read(cx).snapshot(cx);
 9524        let selection = self.selections.newest::<usize>(cx);
 9525
 9526        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9527        if direction == Direction::Next {
 9528            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9529                let (group_id, jump_to) = popover.activation_info();
 9530                if self.activate_diagnostics(group_id, cx) {
 9531                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9532                        let mut new_selection = s.newest_anchor().clone();
 9533                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9534                        s.select_anchors(vec![new_selection.clone()]);
 9535                    });
 9536                }
 9537                return;
 9538            }
 9539        }
 9540
 9541        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9542            active_diagnostics
 9543                .primary_range
 9544                .to_offset(&buffer)
 9545                .to_inclusive()
 9546        });
 9547        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9548            if active_primary_range.contains(&selection.head()) {
 9549                *active_primary_range.start()
 9550            } else {
 9551                selection.head()
 9552            }
 9553        } else {
 9554            selection.head()
 9555        };
 9556        let snapshot = self.snapshot(cx);
 9557        loop {
 9558            let diagnostics = if direction == Direction::Prev {
 9559                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9560            } else {
 9561                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9562            }
 9563            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9564            let group = diagnostics
 9565                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9566                // be sorted in a stable way
 9567                // skip until we are at current active diagnostic, if it exists
 9568                .skip_while(|entry| {
 9569                    (match direction {
 9570                        Direction::Prev => entry.range.start >= search_start,
 9571                        Direction::Next => entry.range.start <= search_start,
 9572                    }) && self
 9573                        .active_diagnostics
 9574                        .as_ref()
 9575                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9576                })
 9577                .find_map(|entry| {
 9578                    if entry.diagnostic.is_primary
 9579                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9580                        && !entry.range.is_empty()
 9581                        // if we match with the active diagnostic, skip it
 9582                        && Some(entry.diagnostic.group_id)
 9583                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9584                    {
 9585                        Some((entry.range, entry.diagnostic.group_id))
 9586                    } else {
 9587                        None
 9588                    }
 9589                });
 9590
 9591            if let Some((primary_range, group_id)) = group {
 9592                if self.activate_diagnostics(group_id, cx) {
 9593                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9594                        s.select(vec![Selection {
 9595                            id: selection.id,
 9596                            start: primary_range.start,
 9597                            end: primary_range.start,
 9598                            reversed: false,
 9599                            goal: SelectionGoal::None,
 9600                        }]);
 9601                    });
 9602                }
 9603                break;
 9604            } else {
 9605                // Cycle around to the start of the buffer, potentially moving back to the start of
 9606                // the currently active diagnostic.
 9607                active_primary_range.take();
 9608                if direction == Direction::Prev {
 9609                    if search_start == buffer.len() {
 9610                        break;
 9611                    } else {
 9612                        search_start = buffer.len();
 9613                    }
 9614                } else if search_start == 0 {
 9615                    break;
 9616                } else {
 9617                    search_start = 0;
 9618                }
 9619            }
 9620        }
 9621    }
 9622
 9623    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9624        let snapshot = self
 9625            .display_map
 9626            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9627        let selection = self.selections.newest::<Point>(cx);
 9628        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9629    }
 9630
 9631    fn go_to_hunk_after_position(
 9632        &mut self,
 9633        snapshot: &DisplaySnapshot,
 9634        position: Point,
 9635        cx: &mut ViewContext<'_, Editor>,
 9636    ) -> Option<MultiBufferDiffHunk> {
 9637        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9638            snapshot,
 9639            position,
 9640            false,
 9641            snapshot
 9642                .buffer_snapshot
 9643                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9644            cx,
 9645        ) {
 9646            return Some(hunk);
 9647        }
 9648
 9649        let wrapped_point = Point::zero();
 9650        self.go_to_next_hunk_in_direction(
 9651            snapshot,
 9652            wrapped_point,
 9653            true,
 9654            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9655                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9656            ),
 9657            cx,
 9658        )
 9659    }
 9660
 9661    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9662        let snapshot = self
 9663            .display_map
 9664            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9665        let selection = self.selections.newest::<Point>(cx);
 9666
 9667        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9668    }
 9669
 9670    fn go_to_hunk_before_position(
 9671        &mut self,
 9672        snapshot: &DisplaySnapshot,
 9673        position: Point,
 9674        cx: &mut ViewContext<'_, Editor>,
 9675    ) -> Option<MultiBufferDiffHunk> {
 9676        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9677            snapshot,
 9678            position,
 9679            false,
 9680            snapshot
 9681                .buffer_snapshot
 9682                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9683            cx,
 9684        ) {
 9685            return Some(hunk);
 9686        }
 9687
 9688        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9689        self.go_to_next_hunk_in_direction(
 9690            snapshot,
 9691            wrapped_point,
 9692            true,
 9693            snapshot
 9694                .buffer_snapshot
 9695                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9696            cx,
 9697        )
 9698    }
 9699
 9700    fn go_to_next_hunk_in_direction(
 9701        &mut self,
 9702        snapshot: &DisplaySnapshot,
 9703        initial_point: Point,
 9704        is_wrapped: bool,
 9705        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9706        cx: &mut ViewContext<Editor>,
 9707    ) -> Option<MultiBufferDiffHunk> {
 9708        let display_point = initial_point.to_display_point(snapshot);
 9709        let mut hunks = hunks
 9710            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9711            .filter(|(display_hunk, _)| {
 9712                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9713            })
 9714            .dedup();
 9715
 9716        if let Some((display_hunk, hunk)) = hunks.next() {
 9717            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9718                let row = display_hunk.start_display_row();
 9719                let point = DisplayPoint::new(row, 0);
 9720                s.select_display_ranges([point..point]);
 9721            });
 9722
 9723            Some(hunk)
 9724        } else {
 9725            None
 9726        }
 9727    }
 9728
 9729    pub fn go_to_definition(
 9730        &mut self,
 9731        _: &GoToDefinition,
 9732        cx: &mut ViewContext<Self>,
 9733    ) -> Task<Result<Navigated>> {
 9734        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9735        cx.spawn(|editor, mut cx| async move {
 9736            if definition.await? == Navigated::Yes {
 9737                return Ok(Navigated::Yes);
 9738            }
 9739            match editor.update(&mut cx, |editor, cx| {
 9740                editor.find_all_references(&FindAllReferences, cx)
 9741            })? {
 9742                Some(references) => references.await,
 9743                None => Ok(Navigated::No),
 9744            }
 9745        })
 9746    }
 9747
 9748    pub fn go_to_declaration(
 9749        &mut self,
 9750        _: &GoToDeclaration,
 9751        cx: &mut ViewContext<Self>,
 9752    ) -> Task<Result<Navigated>> {
 9753        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9754    }
 9755
 9756    pub fn go_to_declaration_split(
 9757        &mut self,
 9758        _: &GoToDeclaration,
 9759        cx: &mut ViewContext<Self>,
 9760    ) -> Task<Result<Navigated>> {
 9761        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9762    }
 9763
 9764    pub fn go_to_implementation(
 9765        &mut self,
 9766        _: &GoToImplementation,
 9767        cx: &mut ViewContext<Self>,
 9768    ) -> Task<Result<Navigated>> {
 9769        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9770    }
 9771
 9772    pub fn go_to_implementation_split(
 9773        &mut self,
 9774        _: &GoToImplementationSplit,
 9775        cx: &mut ViewContext<Self>,
 9776    ) -> Task<Result<Navigated>> {
 9777        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9778    }
 9779
 9780    pub fn go_to_type_definition(
 9781        &mut self,
 9782        _: &GoToTypeDefinition,
 9783        cx: &mut ViewContext<Self>,
 9784    ) -> Task<Result<Navigated>> {
 9785        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9786    }
 9787
 9788    pub fn go_to_definition_split(
 9789        &mut self,
 9790        _: &GoToDefinitionSplit,
 9791        cx: &mut ViewContext<Self>,
 9792    ) -> Task<Result<Navigated>> {
 9793        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9794    }
 9795
 9796    pub fn go_to_type_definition_split(
 9797        &mut self,
 9798        _: &GoToTypeDefinitionSplit,
 9799        cx: &mut ViewContext<Self>,
 9800    ) -> Task<Result<Navigated>> {
 9801        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9802    }
 9803
 9804    fn go_to_definition_of_kind(
 9805        &mut self,
 9806        kind: GotoDefinitionKind,
 9807        split: bool,
 9808        cx: &mut ViewContext<Self>,
 9809    ) -> Task<Result<Navigated>> {
 9810        let Some(provider) = self.semantics_provider.clone() else {
 9811            return Task::ready(Ok(Navigated::No));
 9812        };
 9813        let head = self.selections.newest::<usize>(cx).head();
 9814        let buffer = self.buffer.read(cx);
 9815        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9816            text_anchor
 9817        } else {
 9818            return Task::ready(Ok(Navigated::No));
 9819        };
 9820
 9821        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9822            return Task::ready(Ok(Navigated::No));
 9823        };
 9824
 9825        cx.spawn(|editor, mut cx| async move {
 9826            let definitions = definitions.await?;
 9827            let navigated = editor
 9828                .update(&mut cx, |editor, cx| {
 9829                    editor.navigate_to_hover_links(
 9830                        Some(kind),
 9831                        definitions
 9832                            .into_iter()
 9833                            .filter(|location| {
 9834                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9835                            })
 9836                            .map(HoverLink::Text)
 9837                            .collect::<Vec<_>>(),
 9838                        split,
 9839                        cx,
 9840                    )
 9841                })?
 9842                .await?;
 9843            anyhow::Ok(navigated)
 9844        })
 9845    }
 9846
 9847    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9848        let position = self.selections.newest_anchor().head();
 9849        let Some((buffer, buffer_position)) =
 9850            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9851        else {
 9852            return;
 9853        };
 9854
 9855        cx.spawn(|editor, mut cx| async move {
 9856            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9857                editor.update(&mut cx, |_, cx| {
 9858                    cx.open_url(&url);
 9859                })
 9860            } else {
 9861                Ok(())
 9862            }
 9863        })
 9864        .detach();
 9865    }
 9866
 9867    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9868        let Some(workspace) = self.workspace() else {
 9869            return;
 9870        };
 9871
 9872        let position = self.selections.newest_anchor().head();
 9873
 9874        let Some((buffer, buffer_position)) =
 9875            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9876        else {
 9877            return;
 9878        };
 9879
 9880        let project = self.project.clone();
 9881
 9882        cx.spawn(|_, mut cx| async move {
 9883            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9884
 9885            if let Some((_, path)) = result {
 9886                workspace
 9887                    .update(&mut cx, |workspace, cx| {
 9888                        workspace.open_resolved_path(path, cx)
 9889                    })?
 9890                    .await?;
 9891            }
 9892            anyhow::Ok(())
 9893        })
 9894        .detach();
 9895    }
 9896
 9897    pub(crate) fn navigate_to_hover_links(
 9898        &mut self,
 9899        kind: Option<GotoDefinitionKind>,
 9900        mut definitions: Vec<HoverLink>,
 9901        split: bool,
 9902        cx: &mut ViewContext<Editor>,
 9903    ) -> Task<Result<Navigated>> {
 9904        // If there is one definition, just open it directly
 9905        if definitions.len() == 1 {
 9906            let definition = definitions.pop().unwrap();
 9907
 9908            enum TargetTaskResult {
 9909                Location(Option<Location>),
 9910                AlreadyNavigated,
 9911            }
 9912
 9913            let target_task = match definition {
 9914                HoverLink::Text(link) => {
 9915                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9916                }
 9917                HoverLink::InlayHint(lsp_location, server_id) => {
 9918                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9919                    cx.background_executor().spawn(async move {
 9920                        let location = computation.await?;
 9921                        Ok(TargetTaskResult::Location(location))
 9922                    })
 9923                }
 9924                HoverLink::Url(url) => {
 9925                    cx.open_url(&url);
 9926                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9927                }
 9928                HoverLink::File(path) => {
 9929                    if let Some(workspace) = self.workspace() {
 9930                        cx.spawn(|_, mut cx| async move {
 9931                            workspace
 9932                                .update(&mut cx, |workspace, cx| {
 9933                                    workspace.open_resolved_path(path, cx)
 9934                                })?
 9935                                .await
 9936                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9937                        })
 9938                    } else {
 9939                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9940                    }
 9941                }
 9942            };
 9943            cx.spawn(|editor, mut cx| async move {
 9944                let target = match target_task.await.context("target resolution task")? {
 9945                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9946                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9947                    TargetTaskResult::Location(Some(target)) => target,
 9948                };
 9949
 9950                editor.update(&mut cx, |editor, cx| {
 9951                    let Some(workspace) = editor.workspace() else {
 9952                        return Navigated::No;
 9953                    };
 9954                    let pane = workspace.read(cx).active_pane().clone();
 9955
 9956                    let range = target.range.to_offset(target.buffer.read(cx));
 9957                    let range = editor.range_for_match(&range);
 9958
 9959                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9960                        let buffer = target.buffer.read(cx);
 9961                        let range = check_multiline_range(buffer, range);
 9962                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9963                            s.select_ranges([range]);
 9964                        });
 9965                    } else {
 9966                        cx.window_context().defer(move |cx| {
 9967                            let target_editor: View<Self> =
 9968                                workspace.update(cx, |workspace, cx| {
 9969                                    let pane = if split {
 9970                                        workspace.adjacent_pane(cx)
 9971                                    } else {
 9972                                        workspace.active_pane().clone()
 9973                                    };
 9974
 9975                                    workspace.open_project_item(
 9976                                        pane,
 9977                                        target.buffer.clone(),
 9978                                        true,
 9979                                        true,
 9980                                        cx,
 9981                                    )
 9982                                });
 9983                            target_editor.update(cx, |target_editor, cx| {
 9984                                // When selecting a definition in a different buffer, disable the nav history
 9985                                // to avoid creating a history entry at the previous cursor location.
 9986                                pane.update(cx, |pane, _| pane.disable_history());
 9987                                let buffer = target.buffer.read(cx);
 9988                                let range = check_multiline_range(buffer, range);
 9989                                target_editor.change_selections(
 9990                                    Some(Autoscroll::focused()),
 9991                                    cx,
 9992                                    |s| {
 9993                                        s.select_ranges([range]);
 9994                                    },
 9995                                );
 9996                                pane.update(cx, |pane, _| pane.enable_history());
 9997                            });
 9998                        });
 9999                    }
10000                    Navigated::Yes
10001                })
10002            })
10003        } else if !definitions.is_empty() {
10004            cx.spawn(|editor, mut cx| async move {
10005                let (title, location_tasks, workspace) = editor
10006                    .update(&mut cx, |editor, cx| {
10007                        let tab_kind = match kind {
10008                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10009                            _ => "Definitions",
10010                        };
10011                        let title = definitions
10012                            .iter()
10013                            .find_map(|definition| match definition {
10014                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10015                                    let buffer = origin.buffer.read(cx);
10016                                    format!(
10017                                        "{} for {}",
10018                                        tab_kind,
10019                                        buffer
10020                                            .text_for_range(origin.range.clone())
10021                                            .collect::<String>()
10022                                    )
10023                                }),
10024                                HoverLink::InlayHint(_, _) => None,
10025                                HoverLink::Url(_) => None,
10026                                HoverLink::File(_) => None,
10027                            })
10028                            .unwrap_or(tab_kind.to_string());
10029                        let location_tasks = definitions
10030                            .into_iter()
10031                            .map(|definition| match definition {
10032                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10033                                HoverLink::InlayHint(lsp_location, server_id) => {
10034                                    editor.compute_target_location(lsp_location, server_id, cx)
10035                                }
10036                                HoverLink::Url(_) => Task::ready(Ok(None)),
10037                                HoverLink::File(_) => Task::ready(Ok(None)),
10038                            })
10039                            .collect::<Vec<_>>();
10040                        (title, location_tasks, editor.workspace().clone())
10041                    })
10042                    .context("location tasks preparation")?;
10043
10044                let locations = future::join_all(location_tasks)
10045                    .await
10046                    .into_iter()
10047                    .filter_map(|location| location.transpose())
10048                    .collect::<Result<_>>()
10049                    .context("location tasks")?;
10050
10051                let Some(workspace) = workspace else {
10052                    return Ok(Navigated::No);
10053                };
10054                let opened = workspace
10055                    .update(&mut cx, |workspace, cx| {
10056                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10057                    })
10058                    .ok();
10059
10060                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10061            })
10062        } else {
10063            Task::ready(Ok(Navigated::No))
10064        }
10065    }
10066
10067    fn compute_target_location(
10068        &self,
10069        lsp_location: lsp::Location,
10070        server_id: LanguageServerId,
10071        cx: &mut ViewContext<Self>,
10072    ) -> Task<anyhow::Result<Option<Location>>> {
10073        let Some(project) = self.project.clone() else {
10074            return Task::Ready(Some(Ok(None)));
10075        };
10076
10077        cx.spawn(move |editor, mut cx| async move {
10078            let location_task = editor.update(&mut cx, |_, cx| {
10079                project.update(cx, |project, cx| {
10080                    let language_server_name = project
10081                        .language_server_statuses(cx)
10082                        .find(|(id, _)| server_id == *id)
10083                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10084                    language_server_name.map(|language_server_name| {
10085                        project.open_local_buffer_via_lsp(
10086                            lsp_location.uri.clone(),
10087                            server_id,
10088                            language_server_name,
10089                            cx,
10090                        )
10091                    })
10092                })
10093            })?;
10094            let location = match location_task {
10095                Some(task) => Some({
10096                    let target_buffer_handle = task.await.context("open local buffer")?;
10097                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10098                        let target_start = target_buffer
10099                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10100                        let target_end = target_buffer
10101                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10102                        target_buffer.anchor_after(target_start)
10103                            ..target_buffer.anchor_before(target_end)
10104                    })?;
10105                    Location {
10106                        buffer: target_buffer_handle,
10107                        range,
10108                    }
10109                }),
10110                None => None,
10111            };
10112            Ok(location)
10113        })
10114    }
10115
10116    pub fn find_all_references(
10117        &mut self,
10118        _: &FindAllReferences,
10119        cx: &mut ViewContext<Self>,
10120    ) -> Option<Task<Result<Navigated>>> {
10121        let selection = self.selections.newest::<usize>(cx);
10122        let multi_buffer = self.buffer.read(cx);
10123        let head = selection.head();
10124
10125        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10126        let head_anchor = multi_buffer_snapshot.anchor_at(
10127            head,
10128            if head < selection.tail() {
10129                Bias::Right
10130            } else {
10131                Bias::Left
10132            },
10133        );
10134
10135        match self
10136            .find_all_references_task_sources
10137            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10138        {
10139            Ok(_) => {
10140                log::info!(
10141                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10142                );
10143                return None;
10144            }
10145            Err(i) => {
10146                self.find_all_references_task_sources.insert(i, head_anchor);
10147            }
10148        }
10149
10150        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10151        let workspace = self.workspace()?;
10152        let project = workspace.read(cx).project().clone();
10153        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10154        Some(cx.spawn(|editor, mut cx| async move {
10155            let _cleanup = defer({
10156                let mut cx = cx.clone();
10157                move || {
10158                    let _ = editor.update(&mut cx, |editor, _| {
10159                        if let Ok(i) =
10160                            editor
10161                                .find_all_references_task_sources
10162                                .binary_search_by(|anchor| {
10163                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10164                                })
10165                        {
10166                            editor.find_all_references_task_sources.remove(i);
10167                        }
10168                    });
10169                }
10170            });
10171
10172            let locations = references.await?;
10173            if locations.is_empty() {
10174                return anyhow::Ok(Navigated::No);
10175            }
10176
10177            workspace.update(&mut cx, |workspace, cx| {
10178                let title = locations
10179                    .first()
10180                    .as_ref()
10181                    .map(|location| {
10182                        let buffer = location.buffer.read(cx);
10183                        format!(
10184                            "References to `{}`",
10185                            buffer
10186                                .text_for_range(location.range.clone())
10187                                .collect::<String>()
10188                        )
10189                    })
10190                    .unwrap();
10191                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10192                Navigated::Yes
10193            })
10194        }))
10195    }
10196
10197    /// Opens a multibuffer with the given project locations in it
10198    pub fn open_locations_in_multibuffer(
10199        workspace: &mut Workspace,
10200        mut locations: Vec<Location>,
10201        title: String,
10202        split: bool,
10203        cx: &mut ViewContext<Workspace>,
10204    ) {
10205        // If there are multiple definitions, open them in a multibuffer
10206        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10207        let mut locations = locations.into_iter().peekable();
10208        let mut ranges_to_highlight = Vec::new();
10209        let capability = workspace.project().read(cx).capability();
10210
10211        let excerpt_buffer = cx.new_model(|cx| {
10212            let mut multibuffer = MultiBuffer::new(capability);
10213            while let Some(location) = locations.next() {
10214                let buffer = location.buffer.read(cx);
10215                let mut ranges_for_buffer = Vec::new();
10216                let range = location.range.to_offset(buffer);
10217                ranges_for_buffer.push(range.clone());
10218
10219                while let Some(next_location) = locations.peek() {
10220                    if next_location.buffer == location.buffer {
10221                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10222                        locations.next();
10223                    } else {
10224                        break;
10225                    }
10226                }
10227
10228                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10229                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10230                    location.buffer.clone(),
10231                    ranges_for_buffer,
10232                    DEFAULT_MULTIBUFFER_CONTEXT,
10233                    cx,
10234                ))
10235            }
10236
10237            multibuffer.with_title(title)
10238        });
10239
10240        let editor = cx.new_view(|cx| {
10241            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10242        });
10243        editor.update(cx, |editor, cx| {
10244            if let Some(first_range) = ranges_to_highlight.first() {
10245                editor.change_selections(None, cx, |selections| {
10246                    selections.clear_disjoint();
10247                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10248                });
10249            }
10250            editor.highlight_background::<Self>(
10251                &ranges_to_highlight,
10252                |theme| theme.editor_highlighted_line_background,
10253                cx,
10254            );
10255        });
10256
10257        let item = Box::new(editor);
10258        let item_id = item.item_id();
10259
10260        if split {
10261            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10262        } else {
10263            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10264                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10265                    pane.close_current_preview_item(cx)
10266                } else {
10267                    None
10268                }
10269            });
10270            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10271        }
10272        workspace.active_pane().update(cx, |pane, cx| {
10273            pane.set_preview_item_id(Some(item_id), cx);
10274        });
10275    }
10276
10277    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10278        use language::ToOffset as _;
10279
10280        let provider = self.semantics_provider.clone()?;
10281        let selection = self.selections.newest_anchor().clone();
10282        let (cursor_buffer, cursor_buffer_position) = self
10283            .buffer
10284            .read(cx)
10285            .text_anchor_for_position(selection.head(), cx)?;
10286        let (tail_buffer, cursor_buffer_position_end) = self
10287            .buffer
10288            .read(cx)
10289            .text_anchor_for_position(selection.tail(), cx)?;
10290        if tail_buffer != cursor_buffer {
10291            return None;
10292        }
10293
10294        let snapshot = cursor_buffer.read(cx).snapshot();
10295        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10296        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10297        let prepare_rename = provider
10298            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10299            .unwrap_or_else(|| Task::ready(Ok(None)));
10300        drop(snapshot);
10301
10302        Some(cx.spawn(|this, mut cx| async move {
10303            let rename_range = if let Some(range) = prepare_rename.await? {
10304                Some(range)
10305            } else {
10306                this.update(&mut cx, |this, cx| {
10307                    let buffer = this.buffer.read(cx).snapshot(cx);
10308                    let mut buffer_highlights = this
10309                        .document_highlights_for_position(selection.head(), &buffer)
10310                        .filter(|highlight| {
10311                            highlight.start.excerpt_id == selection.head().excerpt_id
10312                                && highlight.end.excerpt_id == selection.head().excerpt_id
10313                        });
10314                    buffer_highlights
10315                        .next()
10316                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10317                })?
10318            };
10319            if let Some(rename_range) = rename_range {
10320                this.update(&mut cx, |this, cx| {
10321                    let snapshot = cursor_buffer.read(cx).snapshot();
10322                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10323                    let cursor_offset_in_rename_range =
10324                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10325                    let cursor_offset_in_rename_range_end =
10326                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10327
10328                    this.take_rename(false, cx);
10329                    let buffer = this.buffer.read(cx).read(cx);
10330                    let cursor_offset = selection.head().to_offset(&buffer);
10331                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10332                    let rename_end = rename_start + rename_buffer_range.len();
10333                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10334                    let mut old_highlight_id = None;
10335                    let old_name: Arc<str> = buffer
10336                        .chunks(rename_start..rename_end, true)
10337                        .map(|chunk| {
10338                            if old_highlight_id.is_none() {
10339                                old_highlight_id = chunk.syntax_highlight_id;
10340                            }
10341                            chunk.text
10342                        })
10343                        .collect::<String>()
10344                        .into();
10345
10346                    drop(buffer);
10347
10348                    // Position the selection in the rename editor so that it matches the current selection.
10349                    this.show_local_selections = false;
10350                    let rename_editor = cx.new_view(|cx| {
10351                        let mut editor = Editor::single_line(cx);
10352                        editor.buffer.update(cx, |buffer, cx| {
10353                            buffer.edit([(0..0, old_name.clone())], None, cx)
10354                        });
10355                        let rename_selection_range = match cursor_offset_in_rename_range
10356                            .cmp(&cursor_offset_in_rename_range_end)
10357                        {
10358                            Ordering::Equal => {
10359                                editor.select_all(&SelectAll, cx);
10360                                return editor;
10361                            }
10362                            Ordering::Less => {
10363                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10364                            }
10365                            Ordering::Greater => {
10366                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10367                            }
10368                        };
10369                        if rename_selection_range.end > old_name.len() {
10370                            editor.select_all(&SelectAll, cx);
10371                        } else {
10372                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10373                                s.select_ranges([rename_selection_range]);
10374                            });
10375                        }
10376                        editor
10377                    });
10378                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10379                        if e == &EditorEvent::Focused {
10380                            cx.emit(EditorEvent::FocusedIn)
10381                        }
10382                    })
10383                    .detach();
10384
10385                    let write_highlights =
10386                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10387                    let read_highlights =
10388                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10389                    let ranges = write_highlights
10390                        .iter()
10391                        .flat_map(|(_, ranges)| ranges.iter())
10392                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10393                        .cloned()
10394                        .collect();
10395
10396                    this.highlight_text::<Rename>(
10397                        ranges,
10398                        HighlightStyle {
10399                            fade_out: Some(0.6),
10400                            ..Default::default()
10401                        },
10402                        cx,
10403                    );
10404                    let rename_focus_handle = rename_editor.focus_handle(cx);
10405                    cx.focus(&rename_focus_handle);
10406                    let block_id = this.insert_blocks(
10407                        [BlockProperties {
10408                            style: BlockStyle::Flex,
10409                            placement: BlockPlacement::Below(range.start),
10410                            height: 1,
10411                            render: Box::new({
10412                                let rename_editor = rename_editor.clone();
10413                                move |cx: &mut BlockContext| {
10414                                    let mut text_style = cx.editor_style.text.clone();
10415                                    if let Some(highlight_style) = old_highlight_id
10416                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10417                                    {
10418                                        text_style = text_style.highlight(highlight_style);
10419                                    }
10420                                    div()
10421                                        .pl(cx.anchor_x)
10422                                        .child(EditorElement::new(
10423                                            &rename_editor,
10424                                            EditorStyle {
10425                                                background: cx.theme().system().transparent,
10426                                                local_player: cx.editor_style.local_player,
10427                                                text: text_style,
10428                                                scrollbar_width: cx.editor_style.scrollbar_width,
10429                                                syntax: cx.editor_style.syntax.clone(),
10430                                                status: cx.editor_style.status.clone(),
10431                                                inlay_hints_style: HighlightStyle {
10432                                                    font_weight: Some(FontWeight::BOLD),
10433                                                    ..make_inlay_hints_style(cx)
10434                                                },
10435                                                suggestions_style: HighlightStyle {
10436                                                    color: Some(cx.theme().status().predictive),
10437                                                    ..HighlightStyle::default()
10438                                                },
10439                                                ..EditorStyle::default()
10440                                            },
10441                                        ))
10442                                        .into_any_element()
10443                                }
10444                            }),
10445                            priority: 0,
10446                        }],
10447                        Some(Autoscroll::fit()),
10448                        cx,
10449                    )[0];
10450                    this.pending_rename = Some(RenameState {
10451                        range,
10452                        old_name,
10453                        editor: rename_editor,
10454                        block_id,
10455                    });
10456                })?;
10457            }
10458
10459            Ok(())
10460        }))
10461    }
10462
10463    pub fn confirm_rename(
10464        &mut self,
10465        _: &ConfirmRename,
10466        cx: &mut ViewContext<Self>,
10467    ) -> Option<Task<Result<()>>> {
10468        let rename = self.take_rename(false, cx)?;
10469        let workspace = self.workspace()?.downgrade();
10470        let (buffer, start) = self
10471            .buffer
10472            .read(cx)
10473            .text_anchor_for_position(rename.range.start, cx)?;
10474        let (end_buffer, _) = self
10475            .buffer
10476            .read(cx)
10477            .text_anchor_for_position(rename.range.end, cx)?;
10478        if buffer != end_buffer {
10479            return None;
10480        }
10481
10482        let old_name = rename.old_name;
10483        let new_name = rename.editor.read(cx).text(cx);
10484
10485        let rename = self.semantics_provider.as_ref()?.perform_rename(
10486            &buffer,
10487            start,
10488            new_name.clone(),
10489            cx,
10490        )?;
10491
10492        Some(cx.spawn(|editor, mut cx| async move {
10493            let project_transaction = rename.await?;
10494            Self::open_project_transaction(
10495                &editor,
10496                workspace,
10497                project_transaction,
10498                format!("Rename: {}{}", old_name, new_name),
10499                cx.clone(),
10500            )
10501            .await?;
10502
10503            editor.update(&mut cx, |editor, cx| {
10504                editor.refresh_document_highlights(cx);
10505            })?;
10506            Ok(())
10507        }))
10508    }
10509
10510    fn take_rename(
10511        &mut self,
10512        moving_cursor: bool,
10513        cx: &mut ViewContext<Self>,
10514    ) -> Option<RenameState> {
10515        let rename = self.pending_rename.take()?;
10516        if rename.editor.focus_handle(cx).is_focused(cx) {
10517            cx.focus(&self.focus_handle);
10518        }
10519
10520        self.remove_blocks(
10521            [rename.block_id].into_iter().collect(),
10522            Some(Autoscroll::fit()),
10523            cx,
10524        );
10525        self.clear_highlights::<Rename>(cx);
10526        self.show_local_selections = true;
10527
10528        if moving_cursor {
10529            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10530                editor.selections.newest::<usize>(cx).head()
10531            });
10532
10533            // Update the selection to match the position of the selection inside
10534            // the rename editor.
10535            let snapshot = self.buffer.read(cx).read(cx);
10536            let rename_range = rename.range.to_offset(&snapshot);
10537            let cursor_in_editor = snapshot
10538                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10539                .min(rename_range.end);
10540            drop(snapshot);
10541
10542            self.change_selections(None, cx, |s| {
10543                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10544            });
10545        } else {
10546            self.refresh_document_highlights(cx);
10547        }
10548
10549        Some(rename)
10550    }
10551
10552    pub fn pending_rename(&self) -> Option<&RenameState> {
10553        self.pending_rename.as_ref()
10554    }
10555
10556    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10557        let project = match &self.project {
10558            Some(project) => project.clone(),
10559            None => return None,
10560        };
10561
10562        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10563    }
10564
10565    fn format_selections(
10566        &mut self,
10567        _: &FormatSelections,
10568        cx: &mut ViewContext<Self>,
10569    ) -> Option<Task<Result<()>>> {
10570        let project = match &self.project {
10571            Some(project) => project.clone(),
10572            None => return None,
10573        };
10574
10575        let selections = self
10576            .selections
10577            .all_adjusted(cx)
10578            .into_iter()
10579            .filter(|s| !s.is_empty())
10580            .collect_vec();
10581
10582        Some(self.perform_format(
10583            project,
10584            FormatTrigger::Manual,
10585            FormatTarget::Ranges(selections),
10586            cx,
10587        ))
10588    }
10589
10590    fn perform_format(
10591        &mut self,
10592        project: Model<Project>,
10593        trigger: FormatTrigger,
10594        target: FormatTarget,
10595        cx: &mut ViewContext<Self>,
10596    ) -> Task<Result<()>> {
10597        let buffer = self.buffer().clone();
10598        let mut buffers = buffer.read(cx).all_buffers();
10599        if trigger == FormatTrigger::Save {
10600            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10601        }
10602
10603        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10604        let format = project.update(cx, |project, cx| {
10605            project.format(buffers, true, trigger, target, cx)
10606        });
10607
10608        cx.spawn(|_, mut cx| async move {
10609            let transaction = futures::select_biased! {
10610                () = timeout => {
10611                    log::warn!("timed out waiting for formatting");
10612                    None
10613                }
10614                transaction = format.log_err().fuse() => transaction,
10615            };
10616
10617            buffer
10618                .update(&mut cx, |buffer, cx| {
10619                    if let Some(transaction) = transaction {
10620                        if !buffer.is_singleton() {
10621                            buffer.push_transaction(&transaction.0, cx);
10622                        }
10623                    }
10624
10625                    cx.notify();
10626                })
10627                .ok();
10628
10629            Ok(())
10630        })
10631    }
10632
10633    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10634        if let Some(project) = self.project.clone() {
10635            self.buffer.update(cx, |multi_buffer, cx| {
10636                project.update(cx, |project, cx| {
10637                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10638                });
10639            })
10640        }
10641    }
10642
10643    fn cancel_language_server_work(
10644        &mut self,
10645        _: &actions::CancelLanguageServerWork,
10646        cx: &mut ViewContext<Self>,
10647    ) {
10648        if let Some(project) = self.project.clone() {
10649            self.buffer.update(cx, |multi_buffer, cx| {
10650                project.update(cx, |project, cx| {
10651                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10652                });
10653            })
10654        }
10655    }
10656
10657    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10658        cx.show_character_palette();
10659    }
10660
10661    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10662        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10663            let buffer = self.buffer.read(cx).snapshot(cx);
10664            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10665            let is_valid = buffer
10666                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10667                .any(|entry| {
10668                    entry.diagnostic.is_primary
10669                        && !entry.range.is_empty()
10670                        && entry.range.start == primary_range_start
10671                        && entry.diagnostic.message == active_diagnostics.primary_message
10672                });
10673
10674            if is_valid != active_diagnostics.is_valid {
10675                active_diagnostics.is_valid = is_valid;
10676                let mut new_styles = HashMap::default();
10677                for (block_id, diagnostic) in &active_diagnostics.blocks {
10678                    new_styles.insert(
10679                        *block_id,
10680                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10681                    );
10682                }
10683                self.display_map.update(cx, |display_map, _cx| {
10684                    display_map.replace_blocks(new_styles)
10685                });
10686            }
10687        }
10688    }
10689
10690    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10691        self.dismiss_diagnostics(cx);
10692        let snapshot = self.snapshot(cx);
10693        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10694            let buffer = self.buffer.read(cx).snapshot(cx);
10695
10696            let mut primary_range = None;
10697            let mut primary_message = None;
10698            let mut group_end = Point::zero();
10699            let diagnostic_group = buffer
10700                .diagnostic_group::<MultiBufferPoint>(group_id)
10701                .filter_map(|entry| {
10702                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10703                        && (entry.range.start.row == entry.range.end.row
10704                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10705                    {
10706                        return None;
10707                    }
10708                    if entry.range.end > group_end {
10709                        group_end = entry.range.end;
10710                    }
10711                    if entry.diagnostic.is_primary {
10712                        primary_range = Some(entry.range.clone());
10713                        primary_message = Some(entry.diagnostic.message.clone());
10714                    }
10715                    Some(entry)
10716                })
10717                .collect::<Vec<_>>();
10718            let primary_range = primary_range?;
10719            let primary_message = primary_message?;
10720            let primary_range =
10721                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10722
10723            let blocks = display_map
10724                .insert_blocks(
10725                    diagnostic_group.iter().map(|entry| {
10726                        let diagnostic = entry.diagnostic.clone();
10727                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10728                        BlockProperties {
10729                            style: BlockStyle::Fixed,
10730                            placement: BlockPlacement::Below(
10731                                buffer.anchor_after(entry.range.start),
10732                            ),
10733                            height: message_height,
10734                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10735                            priority: 0,
10736                        }
10737                    }),
10738                    cx,
10739                )
10740                .into_iter()
10741                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10742                .collect();
10743
10744            Some(ActiveDiagnosticGroup {
10745                primary_range,
10746                primary_message,
10747                group_id,
10748                blocks,
10749                is_valid: true,
10750            })
10751        });
10752        self.active_diagnostics.is_some()
10753    }
10754
10755    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10756        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10757            self.display_map.update(cx, |display_map, cx| {
10758                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10759            });
10760            cx.notify();
10761        }
10762    }
10763
10764    pub fn set_selections_from_remote(
10765        &mut self,
10766        selections: Vec<Selection<Anchor>>,
10767        pending_selection: Option<Selection<Anchor>>,
10768        cx: &mut ViewContext<Self>,
10769    ) {
10770        let old_cursor_position = self.selections.newest_anchor().head();
10771        self.selections.change_with(cx, |s| {
10772            s.select_anchors(selections);
10773            if let Some(pending_selection) = pending_selection {
10774                s.set_pending(pending_selection, SelectMode::Character);
10775            } else {
10776                s.clear_pending();
10777            }
10778        });
10779        self.selections_did_change(false, &old_cursor_position, true, cx);
10780    }
10781
10782    fn push_to_selection_history(&mut self) {
10783        self.selection_history.push(SelectionHistoryEntry {
10784            selections: self.selections.disjoint_anchors(),
10785            select_next_state: self.select_next_state.clone(),
10786            select_prev_state: self.select_prev_state.clone(),
10787            add_selections_state: self.add_selections_state.clone(),
10788        });
10789    }
10790
10791    pub fn transact(
10792        &mut self,
10793        cx: &mut ViewContext<Self>,
10794        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10795    ) -> Option<TransactionId> {
10796        self.start_transaction_at(Instant::now(), cx);
10797        update(self, cx);
10798        self.end_transaction_at(Instant::now(), cx)
10799    }
10800
10801    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10802        self.end_selection(cx);
10803        if let Some(tx_id) = self
10804            .buffer
10805            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10806        {
10807            self.selection_history
10808                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10809            cx.emit(EditorEvent::TransactionBegun {
10810                transaction_id: tx_id,
10811            })
10812        }
10813    }
10814
10815    fn end_transaction_at(
10816        &mut self,
10817        now: Instant,
10818        cx: &mut ViewContext<Self>,
10819    ) -> Option<TransactionId> {
10820        if let Some(transaction_id) = self
10821            .buffer
10822            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10823        {
10824            if let Some((_, end_selections)) =
10825                self.selection_history.transaction_mut(transaction_id)
10826            {
10827                *end_selections = Some(self.selections.disjoint_anchors());
10828            } else {
10829                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10830            }
10831
10832            cx.emit(EditorEvent::Edited { transaction_id });
10833            Some(transaction_id)
10834        } else {
10835            None
10836        }
10837    }
10838
10839    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10840        let selection = self.selections.newest::<Point>(cx);
10841
10842        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10843        let range = if selection.is_empty() {
10844            let point = selection.head().to_display_point(&display_map);
10845            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10846            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10847                .to_point(&display_map);
10848            start..end
10849        } else {
10850            selection.range()
10851        };
10852        if display_map.folds_in_range(range).next().is_some() {
10853            self.unfold_lines(&Default::default(), cx)
10854        } else {
10855            self.fold(&Default::default(), cx)
10856        }
10857    }
10858
10859    pub fn toggle_fold_recursive(
10860        &mut self,
10861        _: &actions::ToggleFoldRecursive,
10862        cx: &mut ViewContext<Self>,
10863    ) {
10864        let selection = self.selections.newest::<Point>(cx);
10865
10866        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10867        let range = if selection.is_empty() {
10868            let point = selection.head().to_display_point(&display_map);
10869            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10870            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10871                .to_point(&display_map);
10872            start..end
10873        } else {
10874            selection.range()
10875        };
10876        if display_map.folds_in_range(range).next().is_some() {
10877            self.unfold_recursive(&Default::default(), cx)
10878        } else {
10879            self.fold_recursive(&Default::default(), cx)
10880        }
10881    }
10882
10883    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10884        let mut fold_ranges = Vec::new();
10885        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10886        let selections = self.selections.all_adjusted(cx);
10887
10888        for selection in selections {
10889            let range = selection.range().sorted();
10890            let buffer_start_row = range.start.row;
10891
10892            if range.start.row != range.end.row {
10893                let mut found = false;
10894                let mut row = range.start.row;
10895                while row <= range.end.row {
10896                    if let Some((foldable_range, fold_text)) =
10897                        { display_map.foldable_range(MultiBufferRow(row)) }
10898                    {
10899                        found = true;
10900                        row = foldable_range.end.row + 1;
10901                        fold_ranges.push((foldable_range, fold_text));
10902                    } else {
10903                        row += 1
10904                    }
10905                }
10906                if found {
10907                    continue;
10908                }
10909            }
10910
10911            for row in (0..=range.start.row).rev() {
10912                if let Some((foldable_range, fold_text)) =
10913                    display_map.foldable_range(MultiBufferRow(row))
10914                {
10915                    if foldable_range.end.row >= buffer_start_row {
10916                        fold_ranges.push((foldable_range, fold_text));
10917                        if row <= range.start.row {
10918                            break;
10919                        }
10920                    }
10921                }
10922            }
10923        }
10924
10925        self.fold_ranges(fold_ranges, true, cx);
10926    }
10927
10928    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10929        let fold_at_level = fold_at.level;
10930        let snapshot = self.buffer.read(cx).snapshot(cx);
10931        let mut fold_ranges = Vec::new();
10932        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10933
10934        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10935            while start_row < end_row {
10936                match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10937                    Some(foldable_range) => {
10938                        let nested_start_row = foldable_range.0.start.row + 1;
10939                        let nested_end_row = foldable_range.0.end.row;
10940
10941                        if current_level < fold_at_level {
10942                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10943                        } else if current_level == fold_at_level {
10944                            fold_ranges.push(foldable_range);
10945                        }
10946
10947                        start_row = nested_end_row + 1;
10948                    }
10949                    None => start_row += 1,
10950                }
10951            }
10952        }
10953
10954        self.fold_ranges(fold_ranges, true, cx);
10955    }
10956
10957    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10958        let mut fold_ranges = Vec::new();
10959        let snapshot = self.buffer.read(cx).snapshot(cx);
10960
10961        for row in 0..snapshot.max_buffer_row().0 {
10962            if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10963                fold_ranges.push(foldable_range);
10964            }
10965        }
10966
10967        self.fold_ranges(fold_ranges, true, cx);
10968    }
10969
10970    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10971        let mut fold_ranges = Vec::new();
10972        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10973        let selections = self.selections.all_adjusted(cx);
10974
10975        for selection in selections {
10976            let range = selection.range().sorted();
10977            let buffer_start_row = range.start.row;
10978
10979            if range.start.row != range.end.row {
10980                let mut found = false;
10981                for row in range.start.row..=range.end.row {
10982                    if let Some((foldable_range, fold_text)) =
10983                        { display_map.foldable_range(MultiBufferRow(row)) }
10984                    {
10985                        found = true;
10986                        fold_ranges.push((foldable_range, fold_text));
10987                    }
10988                }
10989                if found {
10990                    continue;
10991                }
10992            }
10993
10994            for row in (0..=range.start.row).rev() {
10995                if let Some((foldable_range, fold_text)) =
10996                    display_map.foldable_range(MultiBufferRow(row))
10997                {
10998                    if foldable_range.end.row >= buffer_start_row {
10999                        fold_ranges.push((foldable_range, fold_text));
11000                    } else {
11001                        break;
11002                    }
11003                }
11004            }
11005        }
11006
11007        self.fold_ranges(fold_ranges, true, cx);
11008    }
11009
11010    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11011        let buffer_row = fold_at.buffer_row;
11012        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11013
11014        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
11015            let autoscroll = self
11016                .selections
11017                .all::<Point>(cx)
11018                .iter()
11019                .any(|selection| fold_range.overlaps(&selection.range()));
11020
11021            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
11022        }
11023    }
11024
11025    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11026        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11027        let buffer = &display_map.buffer_snapshot;
11028        let selections = self.selections.all::<Point>(cx);
11029        let ranges = selections
11030            .iter()
11031            .map(|s| {
11032                let range = s.display_range(&display_map).sorted();
11033                let mut start = range.start.to_point(&display_map);
11034                let mut end = range.end.to_point(&display_map);
11035                start.column = 0;
11036                end.column = buffer.line_len(MultiBufferRow(end.row));
11037                start..end
11038            })
11039            .collect::<Vec<_>>();
11040
11041        self.unfold_ranges(&ranges, true, true, cx);
11042    }
11043
11044    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11045        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11046        let selections = self.selections.all::<Point>(cx);
11047        let ranges = selections
11048            .iter()
11049            .map(|s| {
11050                let mut range = s.display_range(&display_map).sorted();
11051                *range.start.column_mut() = 0;
11052                *range.end.column_mut() = display_map.line_len(range.end.row());
11053                let start = range.start.to_point(&display_map);
11054                let end = range.end.to_point(&display_map);
11055                start..end
11056            })
11057            .collect::<Vec<_>>();
11058
11059        self.unfold_ranges(&ranges, true, true, cx);
11060    }
11061
11062    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11063        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11064
11065        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11066            ..Point::new(
11067                unfold_at.buffer_row.0,
11068                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11069            );
11070
11071        let autoscroll = self
11072            .selections
11073            .all::<Point>(cx)
11074            .iter()
11075            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11076
11077        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11078    }
11079
11080    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11081        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11082        self.unfold_ranges(
11083            &[Point::zero()..display_map.max_point().to_point(&display_map)],
11084            true,
11085            true,
11086            cx,
11087        );
11088    }
11089
11090    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11091        let selections = self.selections.all::<Point>(cx);
11092        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11093        let line_mode = self.selections.line_mode;
11094        let ranges = selections.into_iter().map(|s| {
11095            if line_mode {
11096                let start = Point::new(s.start.row, 0);
11097                let end = Point::new(
11098                    s.end.row,
11099                    display_map
11100                        .buffer_snapshot
11101                        .line_len(MultiBufferRow(s.end.row)),
11102                );
11103                (start..end, display_map.fold_placeholder.clone())
11104            } else {
11105                (s.start..s.end, display_map.fold_placeholder.clone())
11106            }
11107        });
11108        self.fold_ranges(ranges, true, cx);
11109    }
11110
11111    pub fn fold_ranges<T: ToOffset + Clone>(
11112        &mut self,
11113        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11114        auto_scroll: bool,
11115        cx: &mut ViewContext<Self>,
11116    ) {
11117        let mut fold_ranges = Vec::new();
11118        let mut buffers_affected = HashMap::default();
11119        let multi_buffer = self.buffer().read(cx);
11120        for (fold_range, fold_text) in ranges {
11121            if let Some((_, buffer, _)) =
11122                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11123            {
11124                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11125            };
11126            fold_ranges.push((fold_range, fold_text));
11127        }
11128
11129        let mut ranges = fold_ranges.into_iter().peekable();
11130        if ranges.peek().is_some() {
11131            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11132
11133            if auto_scroll {
11134                self.request_autoscroll(Autoscroll::fit(), cx);
11135            }
11136
11137            for buffer in buffers_affected.into_values() {
11138                self.sync_expanded_diff_hunks(buffer, cx);
11139            }
11140
11141            cx.notify();
11142
11143            if let Some(active_diagnostics) = self.active_diagnostics.take() {
11144                // Clear diagnostics block when folding a range that contains it.
11145                let snapshot = self.snapshot(cx);
11146                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11147                    drop(snapshot);
11148                    self.active_diagnostics = Some(active_diagnostics);
11149                    self.dismiss_diagnostics(cx);
11150                } else {
11151                    self.active_diagnostics = Some(active_diagnostics);
11152                }
11153            }
11154
11155            self.scrollbar_marker_state.dirty = true;
11156        }
11157    }
11158
11159    /// Removes any folds whose ranges intersect any of the given ranges.
11160    pub fn unfold_ranges<T: ToOffset + Clone>(
11161        &mut self,
11162        ranges: &[Range<T>],
11163        inclusive: bool,
11164        auto_scroll: bool,
11165        cx: &mut ViewContext<Self>,
11166    ) {
11167        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11168            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11169        });
11170    }
11171
11172    /// Removes any folds with the given ranges.
11173    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11174        &mut self,
11175        ranges: &[Range<T>],
11176        type_id: TypeId,
11177        auto_scroll: bool,
11178        cx: &mut ViewContext<Self>,
11179    ) {
11180        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11181            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11182        });
11183    }
11184
11185    fn remove_folds_with<T: ToOffset + Clone>(
11186        &mut self,
11187        ranges: &[Range<T>],
11188        auto_scroll: bool,
11189        cx: &mut ViewContext<Self>,
11190        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11191    ) {
11192        if ranges.is_empty() {
11193            return;
11194        }
11195
11196        let mut buffers_affected = HashMap::default();
11197        let multi_buffer = self.buffer().read(cx);
11198        for range in ranges {
11199            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11200                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11201            };
11202        }
11203
11204        self.display_map.update(cx, update);
11205        if auto_scroll {
11206            self.request_autoscroll(Autoscroll::fit(), cx);
11207        }
11208
11209        for buffer in buffers_affected.into_values() {
11210            self.sync_expanded_diff_hunks(buffer, cx);
11211        }
11212
11213        cx.notify();
11214        self.scrollbar_marker_state.dirty = true;
11215        self.active_indent_guides_state.dirty = true;
11216    }
11217
11218    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11219        self.display_map.read(cx).fold_placeholder.clone()
11220    }
11221
11222    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11223        if hovered != self.gutter_hovered {
11224            self.gutter_hovered = hovered;
11225            cx.notify();
11226        }
11227    }
11228
11229    pub fn insert_blocks(
11230        &mut self,
11231        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11232        autoscroll: Option<Autoscroll>,
11233        cx: &mut ViewContext<Self>,
11234    ) -> Vec<CustomBlockId> {
11235        let blocks = self
11236            .display_map
11237            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11238        if let Some(autoscroll) = autoscroll {
11239            self.request_autoscroll(autoscroll, cx);
11240        }
11241        cx.notify();
11242        blocks
11243    }
11244
11245    pub fn resize_blocks(
11246        &mut self,
11247        heights: HashMap<CustomBlockId, u32>,
11248        autoscroll: Option<Autoscroll>,
11249        cx: &mut ViewContext<Self>,
11250    ) {
11251        self.display_map
11252            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11253        if let Some(autoscroll) = autoscroll {
11254            self.request_autoscroll(autoscroll, cx);
11255        }
11256        cx.notify();
11257    }
11258
11259    pub fn replace_blocks(
11260        &mut self,
11261        renderers: HashMap<CustomBlockId, RenderBlock>,
11262        autoscroll: Option<Autoscroll>,
11263        cx: &mut ViewContext<Self>,
11264    ) {
11265        self.display_map
11266            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11267        if let Some(autoscroll) = autoscroll {
11268            self.request_autoscroll(autoscroll, cx);
11269        }
11270        cx.notify();
11271    }
11272
11273    pub fn remove_blocks(
11274        &mut self,
11275        block_ids: HashSet<CustomBlockId>,
11276        autoscroll: Option<Autoscroll>,
11277        cx: &mut ViewContext<Self>,
11278    ) {
11279        self.display_map.update(cx, |display_map, cx| {
11280            display_map.remove_blocks(block_ids, cx)
11281        });
11282        if let Some(autoscroll) = autoscroll {
11283            self.request_autoscroll(autoscroll, cx);
11284        }
11285        cx.notify();
11286    }
11287
11288    pub fn row_for_block(
11289        &self,
11290        block_id: CustomBlockId,
11291        cx: &mut ViewContext<Self>,
11292    ) -> Option<DisplayRow> {
11293        self.display_map
11294            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11295    }
11296
11297    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11298        self.focused_block = Some(focused_block);
11299    }
11300
11301    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11302        self.focused_block.take()
11303    }
11304
11305    pub fn insert_creases(
11306        &mut self,
11307        creases: impl IntoIterator<Item = Crease>,
11308        cx: &mut ViewContext<Self>,
11309    ) -> Vec<CreaseId> {
11310        self.display_map
11311            .update(cx, |map, cx| map.insert_creases(creases, cx))
11312    }
11313
11314    pub fn remove_creases(
11315        &mut self,
11316        ids: impl IntoIterator<Item = CreaseId>,
11317        cx: &mut ViewContext<Self>,
11318    ) {
11319        self.display_map
11320            .update(cx, |map, cx| map.remove_creases(ids, cx));
11321    }
11322
11323    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11324        self.display_map
11325            .update(cx, |map, cx| map.snapshot(cx))
11326            .longest_row()
11327    }
11328
11329    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11330        self.display_map
11331            .update(cx, |map, cx| map.snapshot(cx))
11332            .max_point()
11333    }
11334
11335    pub fn text(&self, cx: &AppContext) -> String {
11336        self.buffer.read(cx).read(cx).text()
11337    }
11338
11339    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11340        let text = self.text(cx);
11341        let text = text.trim();
11342
11343        if text.is_empty() {
11344            return None;
11345        }
11346
11347        Some(text.to_string())
11348    }
11349
11350    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11351        self.transact(cx, |this, cx| {
11352            this.buffer
11353                .read(cx)
11354                .as_singleton()
11355                .expect("you can only call set_text on editors for singleton buffers")
11356                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11357        });
11358    }
11359
11360    pub fn display_text(&self, cx: &mut AppContext) -> String {
11361        self.display_map
11362            .update(cx, |map, cx| map.snapshot(cx))
11363            .text()
11364    }
11365
11366    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11367        let mut wrap_guides = smallvec::smallvec![];
11368
11369        if self.show_wrap_guides == Some(false) {
11370            return wrap_guides;
11371        }
11372
11373        let settings = self.buffer.read(cx).settings_at(0, cx);
11374        if settings.show_wrap_guides {
11375            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11376                wrap_guides.push((soft_wrap as usize, true));
11377            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11378                wrap_guides.push((soft_wrap as usize, true));
11379            }
11380            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11381        }
11382
11383        wrap_guides
11384    }
11385
11386    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11387        let settings = self.buffer.read(cx).settings_at(0, cx);
11388        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11389        match mode {
11390            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11391                SoftWrap::None
11392            }
11393            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11394            language_settings::SoftWrap::PreferredLineLength => {
11395                SoftWrap::Column(settings.preferred_line_length)
11396            }
11397            language_settings::SoftWrap::Bounded => {
11398                SoftWrap::Bounded(settings.preferred_line_length)
11399            }
11400        }
11401    }
11402
11403    pub fn set_soft_wrap_mode(
11404        &mut self,
11405        mode: language_settings::SoftWrap,
11406        cx: &mut ViewContext<Self>,
11407    ) {
11408        self.soft_wrap_mode_override = Some(mode);
11409        cx.notify();
11410    }
11411
11412    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11413        self.text_style_refinement = Some(style);
11414    }
11415
11416    /// called by the Element so we know what style we were most recently rendered with.
11417    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11418        let rem_size = cx.rem_size();
11419        self.display_map.update(cx, |map, cx| {
11420            map.set_font(
11421                style.text.font(),
11422                style.text.font_size.to_pixels(rem_size),
11423                cx,
11424            )
11425        });
11426        self.style = Some(style);
11427    }
11428
11429    pub fn style(&self) -> Option<&EditorStyle> {
11430        self.style.as_ref()
11431    }
11432
11433    // Called by the element. This method is not designed to be called outside of the editor
11434    // element's layout code because it does not notify when rewrapping is computed synchronously.
11435    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11436        self.display_map
11437            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11438    }
11439
11440    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11441        if self.soft_wrap_mode_override.is_some() {
11442            self.soft_wrap_mode_override.take();
11443        } else {
11444            let soft_wrap = match self.soft_wrap_mode(cx) {
11445                SoftWrap::GitDiff => return,
11446                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11447                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11448                    language_settings::SoftWrap::None
11449                }
11450            };
11451            self.soft_wrap_mode_override = Some(soft_wrap);
11452        }
11453        cx.notify();
11454    }
11455
11456    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11457        let Some(workspace) = self.workspace() else {
11458            return;
11459        };
11460        let fs = workspace.read(cx).app_state().fs.clone();
11461        let current_show = TabBarSettings::get_global(cx).show;
11462        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11463            setting.show = Some(!current_show);
11464        });
11465    }
11466
11467    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11468        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11469            self.buffer
11470                .read(cx)
11471                .settings_at(0, cx)
11472                .indent_guides
11473                .enabled
11474        });
11475        self.show_indent_guides = Some(!currently_enabled);
11476        cx.notify();
11477    }
11478
11479    fn should_show_indent_guides(&self) -> Option<bool> {
11480        self.show_indent_guides
11481    }
11482
11483    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11484        let mut editor_settings = EditorSettings::get_global(cx).clone();
11485        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11486        EditorSettings::override_global(editor_settings, cx);
11487    }
11488
11489    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11490        self.use_relative_line_numbers
11491            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11492    }
11493
11494    pub fn toggle_relative_line_numbers(
11495        &mut self,
11496        _: &ToggleRelativeLineNumbers,
11497        cx: &mut ViewContext<Self>,
11498    ) {
11499        let is_relative = self.should_use_relative_line_numbers(cx);
11500        self.set_relative_line_number(Some(!is_relative), cx)
11501    }
11502
11503    pub fn set_relative_line_number(
11504        &mut self,
11505        is_relative: Option<bool>,
11506        cx: &mut ViewContext<Self>,
11507    ) {
11508        self.use_relative_line_numbers = is_relative;
11509        cx.notify();
11510    }
11511
11512    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11513        self.show_gutter = show_gutter;
11514        cx.notify();
11515    }
11516
11517    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11518        self.show_line_numbers = Some(show_line_numbers);
11519        cx.notify();
11520    }
11521
11522    pub fn set_show_git_diff_gutter(
11523        &mut self,
11524        show_git_diff_gutter: bool,
11525        cx: &mut ViewContext<Self>,
11526    ) {
11527        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11528        cx.notify();
11529    }
11530
11531    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11532        self.show_code_actions = Some(show_code_actions);
11533        cx.notify();
11534    }
11535
11536    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11537        self.show_runnables = Some(show_runnables);
11538        cx.notify();
11539    }
11540
11541    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11542        if self.display_map.read(cx).masked != masked {
11543            self.display_map.update(cx, |map, _| map.masked = masked);
11544        }
11545        cx.notify()
11546    }
11547
11548    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11549        self.show_wrap_guides = Some(show_wrap_guides);
11550        cx.notify();
11551    }
11552
11553    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11554        self.show_indent_guides = Some(show_indent_guides);
11555        cx.notify();
11556    }
11557
11558    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11559        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11560            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11561                if let Some(dir) = file.abs_path(cx).parent() {
11562                    return Some(dir.to_owned());
11563                }
11564            }
11565
11566            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11567                return Some(project_path.path.to_path_buf());
11568            }
11569        }
11570
11571        None
11572    }
11573
11574    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11575        self.active_excerpt(cx)?
11576            .1
11577            .read(cx)
11578            .file()
11579            .and_then(|f| f.as_local())
11580    }
11581
11582    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11583        if let Some(target) = self.target_file(cx) {
11584            cx.reveal_path(&target.abs_path(cx));
11585        }
11586    }
11587
11588    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11589        if let Some(file) = self.target_file(cx) {
11590            if let Some(path) = file.abs_path(cx).to_str() {
11591                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11592            }
11593        }
11594    }
11595
11596    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11597        if let Some(file) = self.target_file(cx) {
11598            if let Some(path) = file.path().to_str() {
11599                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11600            }
11601        }
11602    }
11603
11604    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11605        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11606
11607        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11608            self.start_git_blame(true, cx);
11609        }
11610
11611        cx.notify();
11612    }
11613
11614    pub fn toggle_git_blame_inline(
11615        &mut self,
11616        _: &ToggleGitBlameInline,
11617        cx: &mut ViewContext<Self>,
11618    ) {
11619        self.toggle_git_blame_inline_internal(true, cx);
11620        cx.notify();
11621    }
11622
11623    pub fn git_blame_inline_enabled(&self) -> bool {
11624        self.git_blame_inline_enabled
11625    }
11626
11627    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11628        self.show_selection_menu = self
11629            .show_selection_menu
11630            .map(|show_selections_menu| !show_selections_menu)
11631            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11632
11633        cx.notify();
11634    }
11635
11636    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11637        self.show_selection_menu
11638            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11639    }
11640
11641    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11642        if let Some(project) = self.project.as_ref() {
11643            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11644                return;
11645            };
11646
11647            if buffer.read(cx).file().is_none() {
11648                return;
11649            }
11650
11651            let focused = self.focus_handle(cx).contains_focused(cx);
11652
11653            let project = project.clone();
11654            let blame =
11655                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11656            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11657            self.blame = Some(blame);
11658        }
11659    }
11660
11661    fn toggle_git_blame_inline_internal(
11662        &mut self,
11663        user_triggered: bool,
11664        cx: &mut ViewContext<Self>,
11665    ) {
11666        if self.git_blame_inline_enabled {
11667            self.git_blame_inline_enabled = false;
11668            self.show_git_blame_inline = false;
11669            self.show_git_blame_inline_delay_task.take();
11670        } else {
11671            self.git_blame_inline_enabled = true;
11672            self.start_git_blame_inline(user_triggered, cx);
11673        }
11674
11675        cx.notify();
11676    }
11677
11678    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11679        self.start_git_blame(user_triggered, cx);
11680
11681        if ProjectSettings::get_global(cx)
11682            .git
11683            .inline_blame_delay()
11684            .is_some()
11685        {
11686            self.start_inline_blame_timer(cx);
11687        } else {
11688            self.show_git_blame_inline = true
11689        }
11690    }
11691
11692    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11693        self.blame.as_ref()
11694    }
11695
11696    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11697        self.show_git_blame_gutter && self.has_blame_entries(cx)
11698    }
11699
11700    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11701        self.show_git_blame_inline
11702            && self.focus_handle.is_focused(cx)
11703            && !self.newest_selection_head_on_empty_line(cx)
11704            && self.has_blame_entries(cx)
11705    }
11706
11707    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11708        self.blame()
11709            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11710    }
11711
11712    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11713        let cursor_anchor = self.selections.newest_anchor().head();
11714
11715        let snapshot = self.buffer.read(cx).snapshot(cx);
11716        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11717
11718        snapshot.line_len(buffer_row) == 0
11719    }
11720
11721    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11722        let buffer_and_selection = maybe!({
11723            let selection = self.selections.newest::<Point>(cx);
11724            let selection_range = selection.range();
11725
11726            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11727                (buffer, selection_range.start.row..selection_range.end.row)
11728            } else {
11729                let buffer_ranges = self
11730                    .buffer()
11731                    .read(cx)
11732                    .range_to_buffer_ranges(selection_range, cx);
11733
11734                let (buffer, range, _) = if selection.reversed {
11735                    buffer_ranges.first()
11736                } else {
11737                    buffer_ranges.last()
11738                }?;
11739
11740                let snapshot = buffer.read(cx).snapshot();
11741                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11742                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11743                (buffer.clone(), selection)
11744            };
11745
11746            Some((buffer, selection))
11747        });
11748
11749        let Some((buffer, selection)) = buffer_and_selection else {
11750            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11751        };
11752
11753        let Some(project) = self.project.as_ref() else {
11754            return Task::ready(Err(anyhow!("editor does not have project")));
11755        };
11756
11757        project.update(cx, |project, cx| {
11758            project.get_permalink_to_line(&buffer, selection, cx)
11759        })
11760    }
11761
11762    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11763        let permalink_task = self.get_permalink_to_line(cx);
11764        let workspace = self.workspace();
11765
11766        cx.spawn(|_, mut cx| async move {
11767            match permalink_task.await {
11768                Ok(permalink) => {
11769                    cx.update(|cx| {
11770                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11771                    })
11772                    .ok();
11773                }
11774                Err(err) => {
11775                    let message = format!("Failed to copy permalink: {err}");
11776
11777                    Err::<(), anyhow::Error>(err).log_err();
11778
11779                    if let Some(workspace) = workspace {
11780                        workspace
11781                            .update(&mut cx, |workspace, cx| {
11782                                struct CopyPermalinkToLine;
11783
11784                                workspace.show_toast(
11785                                    Toast::new(
11786                                        NotificationId::unique::<CopyPermalinkToLine>(),
11787                                        message,
11788                                    ),
11789                                    cx,
11790                                )
11791                            })
11792                            .ok();
11793                    }
11794                }
11795            }
11796        })
11797        .detach();
11798    }
11799
11800    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11801        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11802        if let Some(file) = self.target_file(cx) {
11803            if let Some(path) = file.path().to_str() {
11804                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11805            }
11806        }
11807    }
11808
11809    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11810        let permalink_task = self.get_permalink_to_line(cx);
11811        let workspace = self.workspace();
11812
11813        cx.spawn(|_, mut cx| async move {
11814            match permalink_task.await {
11815                Ok(permalink) => {
11816                    cx.update(|cx| {
11817                        cx.open_url(permalink.as_ref());
11818                    })
11819                    .ok();
11820                }
11821                Err(err) => {
11822                    let message = format!("Failed to open permalink: {err}");
11823
11824                    Err::<(), anyhow::Error>(err).log_err();
11825
11826                    if let Some(workspace) = workspace {
11827                        workspace
11828                            .update(&mut cx, |workspace, cx| {
11829                                struct OpenPermalinkToLine;
11830
11831                                workspace.show_toast(
11832                                    Toast::new(
11833                                        NotificationId::unique::<OpenPermalinkToLine>(),
11834                                        message,
11835                                    ),
11836                                    cx,
11837                                )
11838                            })
11839                            .ok();
11840                    }
11841                }
11842            }
11843        })
11844        .detach();
11845    }
11846
11847    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11848    /// last highlight added will be used.
11849    ///
11850    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11851    pub fn highlight_rows<T: 'static>(
11852        &mut self,
11853        range: Range<Anchor>,
11854        color: Hsla,
11855        should_autoscroll: bool,
11856        cx: &mut ViewContext<Self>,
11857    ) {
11858        let snapshot = self.buffer().read(cx).snapshot(cx);
11859        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11860        let ix = row_highlights.binary_search_by(|highlight| {
11861            Ordering::Equal
11862                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11863                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11864        });
11865
11866        if let Err(mut ix) = ix {
11867            let index = post_inc(&mut self.highlight_order);
11868
11869            // If this range intersects with the preceding highlight, then merge it with
11870            // the preceding highlight. Otherwise insert a new highlight.
11871            let mut merged = false;
11872            if ix > 0 {
11873                let prev_highlight = &mut row_highlights[ix - 1];
11874                if prev_highlight
11875                    .range
11876                    .end
11877                    .cmp(&range.start, &snapshot)
11878                    .is_ge()
11879                {
11880                    ix -= 1;
11881                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11882                        prev_highlight.range.end = range.end;
11883                    }
11884                    merged = true;
11885                    prev_highlight.index = index;
11886                    prev_highlight.color = color;
11887                    prev_highlight.should_autoscroll = should_autoscroll;
11888                }
11889            }
11890
11891            if !merged {
11892                row_highlights.insert(
11893                    ix,
11894                    RowHighlight {
11895                        range: range.clone(),
11896                        index,
11897                        color,
11898                        should_autoscroll,
11899                    },
11900                );
11901            }
11902
11903            // If any of the following highlights intersect with this one, merge them.
11904            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11905                let highlight = &row_highlights[ix];
11906                if next_highlight
11907                    .range
11908                    .start
11909                    .cmp(&highlight.range.end, &snapshot)
11910                    .is_le()
11911                {
11912                    if next_highlight
11913                        .range
11914                        .end
11915                        .cmp(&highlight.range.end, &snapshot)
11916                        .is_gt()
11917                    {
11918                        row_highlights[ix].range.end = next_highlight.range.end;
11919                    }
11920                    row_highlights.remove(ix + 1);
11921                } else {
11922                    break;
11923                }
11924            }
11925        }
11926    }
11927
11928    /// Remove any highlighted row ranges of the given type that intersect the
11929    /// given ranges.
11930    pub fn remove_highlighted_rows<T: 'static>(
11931        &mut self,
11932        ranges_to_remove: Vec<Range<Anchor>>,
11933        cx: &mut ViewContext<Self>,
11934    ) {
11935        let snapshot = self.buffer().read(cx).snapshot(cx);
11936        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11937        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11938        row_highlights.retain(|highlight| {
11939            while let Some(range_to_remove) = ranges_to_remove.peek() {
11940                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11941                    Ordering::Less | Ordering::Equal => {
11942                        ranges_to_remove.next();
11943                    }
11944                    Ordering::Greater => {
11945                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11946                            Ordering::Less | Ordering::Equal => {
11947                                return false;
11948                            }
11949                            Ordering::Greater => break,
11950                        }
11951                    }
11952                }
11953            }
11954
11955            true
11956        })
11957    }
11958
11959    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11960    pub fn clear_row_highlights<T: 'static>(&mut self) {
11961        self.highlighted_rows.remove(&TypeId::of::<T>());
11962    }
11963
11964    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11965    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11966        self.highlighted_rows
11967            .get(&TypeId::of::<T>())
11968            .map_or(&[] as &[_], |vec| vec.as_slice())
11969            .iter()
11970            .map(|highlight| (highlight.range.clone(), highlight.color))
11971    }
11972
11973    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11974    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11975    /// Allows to ignore certain kinds of highlights.
11976    pub fn highlighted_display_rows(
11977        &mut self,
11978        cx: &mut WindowContext,
11979    ) -> BTreeMap<DisplayRow, Hsla> {
11980        let snapshot = self.snapshot(cx);
11981        let mut used_highlight_orders = HashMap::default();
11982        self.highlighted_rows
11983            .iter()
11984            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11985            .fold(
11986                BTreeMap::<DisplayRow, Hsla>::new(),
11987                |mut unique_rows, highlight| {
11988                    let start = highlight.range.start.to_display_point(&snapshot);
11989                    let end = highlight.range.end.to_display_point(&snapshot);
11990                    let start_row = start.row().0;
11991                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11992                        && end.column() == 0
11993                    {
11994                        end.row().0.saturating_sub(1)
11995                    } else {
11996                        end.row().0
11997                    };
11998                    for row in start_row..=end_row {
11999                        let used_index =
12000                            used_highlight_orders.entry(row).or_insert(highlight.index);
12001                        if highlight.index >= *used_index {
12002                            *used_index = highlight.index;
12003                            unique_rows.insert(DisplayRow(row), highlight.color);
12004                        }
12005                    }
12006                    unique_rows
12007                },
12008            )
12009    }
12010
12011    pub fn highlighted_display_row_for_autoscroll(
12012        &self,
12013        snapshot: &DisplaySnapshot,
12014    ) -> Option<DisplayRow> {
12015        self.highlighted_rows
12016            .values()
12017            .flat_map(|highlighted_rows| highlighted_rows.iter())
12018            .filter_map(|highlight| {
12019                if highlight.should_autoscroll {
12020                    Some(highlight.range.start.to_display_point(snapshot).row())
12021                } else {
12022                    None
12023                }
12024            })
12025            .min()
12026    }
12027
12028    pub fn set_search_within_ranges(
12029        &mut self,
12030        ranges: &[Range<Anchor>],
12031        cx: &mut ViewContext<Self>,
12032    ) {
12033        self.highlight_background::<SearchWithinRange>(
12034            ranges,
12035            |colors| colors.editor_document_highlight_read_background,
12036            cx,
12037        )
12038    }
12039
12040    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12041        self.breadcrumb_header = Some(new_header);
12042    }
12043
12044    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12045        self.clear_background_highlights::<SearchWithinRange>(cx);
12046    }
12047
12048    pub fn highlight_background<T: 'static>(
12049        &mut self,
12050        ranges: &[Range<Anchor>],
12051        color_fetcher: fn(&ThemeColors) -> Hsla,
12052        cx: &mut ViewContext<Self>,
12053    ) {
12054        self.background_highlights
12055            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12056        self.scrollbar_marker_state.dirty = true;
12057        cx.notify();
12058    }
12059
12060    pub fn clear_background_highlights<T: 'static>(
12061        &mut self,
12062        cx: &mut ViewContext<Self>,
12063    ) -> Option<BackgroundHighlight> {
12064        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12065        if !text_highlights.1.is_empty() {
12066            self.scrollbar_marker_state.dirty = true;
12067            cx.notify();
12068        }
12069        Some(text_highlights)
12070    }
12071
12072    pub fn highlight_gutter<T: 'static>(
12073        &mut self,
12074        ranges: &[Range<Anchor>],
12075        color_fetcher: fn(&AppContext) -> Hsla,
12076        cx: &mut ViewContext<Self>,
12077    ) {
12078        self.gutter_highlights
12079            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12080        cx.notify();
12081    }
12082
12083    pub fn clear_gutter_highlights<T: 'static>(
12084        &mut self,
12085        cx: &mut ViewContext<Self>,
12086    ) -> Option<GutterHighlight> {
12087        cx.notify();
12088        self.gutter_highlights.remove(&TypeId::of::<T>())
12089    }
12090
12091    #[cfg(feature = "test-support")]
12092    pub fn all_text_background_highlights(
12093        &mut self,
12094        cx: &mut ViewContext<Self>,
12095    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12096        let snapshot = self.snapshot(cx);
12097        let buffer = &snapshot.buffer_snapshot;
12098        let start = buffer.anchor_before(0);
12099        let end = buffer.anchor_after(buffer.len());
12100        let theme = cx.theme().colors();
12101        self.background_highlights_in_range(start..end, &snapshot, theme)
12102    }
12103
12104    #[cfg(feature = "test-support")]
12105    pub fn search_background_highlights(
12106        &mut self,
12107        cx: &mut ViewContext<Self>,
12108    ) -> Vec<Range<Point>> {
12109        let snapshot = self.buffer().read(cx).snapshot(cx);
12110
12111        let highlights = self
12112            .background_highlights
12113            .get(&TypeId::of::<items::BufferSearchHighlights>());
12114
12115        if let Some((_color, ranges)) = highlights {
12116            ranges
12117                .iter()
12118                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12119                .collect_vec()
12120        } else {
12121            vec![]
12122        }
12123    }
12124
12125    fn document_highlights_for_position<'a>(
12126        &'a self,
12127        position: Anchor,
12128        buffer: &'a MultiBufferSnapshot,
12129    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12130        let read_highlights = self
12131            .background_highlights
12132            .get(&TypeId::of::<DocumentHighlightRead>())
12133            .map(|h| &h.1);
12134        let write_highlights = self
12135            .background_highlights
12136            .get(&TypeId::of::<DocumentHighlightWrite>())
12137            .map(|h| &h.1);
12138        let left_position = position.bias_left(buffer);
12139        let right_position = position.bias_right(buffer);
12140        read_highlights
12141            .into_iter()
12142            .chain(write_highlights)
12143            .flat_map(move |ranges| {
12144                let start_ix = match ranges.binary_search_by(|probe| {
12145                    let cmp = probe.end.cmp(&left_position, buffer);
12146                    if cmp.is_ge() {
12147                        Ordering::Greater
12148                    } else {
12149                        Ordering::Less
12150                    }
12151                }) {
12152                    Ok(i) | Err(i) => i,
12153                };
12154
12155                ranges[start_ix..]
12156                    .iter()
12157                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12158            })
12159    }
12160
12161    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12162        self.background_highlights
12163            .get(&TypeId::of::<T>())
12164            .map_or(false, |(_, highlights)| !highlights.is_empty())
12165    }
12166
12167    pub fn background_highlights_in_range(
12168        &self,
12169        search_range: Range<Anchor>,
12170        display_snapshot: &DisplaySnapshot,
12171        theme: &ThemeColors,
12172    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12173        let mut results = Vec::new();
12174        for (color_fetcher, ranges) in self.background_highlights.values() {
12175            let color = color_fetcher(theme);
12176            let start_ix = match ranges.binary_search_by(|probe| {
12177                let cmp = probe
12178                    .end
12179                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12180                if cmp.is_gt() {
12181                    Ordering::Greater
12182                } else {
12183                    Ordering::Less
12184                }
12185            }) {
12186                Ok(i) | Err(i) => i,
12187            };
12188            for range in &ranges[start_ix..] {
12189                if range
12190                    .start
12191                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12192                    .is_ge()
12193                {
12194                    break;
12195                }
12196
12197                let start = range.start.to_display_point(display_snapshot);
12198                let end = range.end.to_display_point(display_snapshot);
12199                results.push((start..end, color))
12200            }
12201        }
12202        results
12203    }
12204
12205    pub fn background_highlight_row_ranges<T: 'static>(
12206        &self,
12207        search_range: Range<Anchor>,
12208        display_snapshot: &DisplaySnapshot,
12209        count: usize,
12210    ) -> Vec<RangeInclusive<DisplayPoint>> {
12211        let mut results = Vec::new();
12212        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12213            return vec![];
12214        };
12215
12216        let start_ix = match ranges.binary_search_by(|probe| {
12217            let cmp = probe
12218                .end
12219                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12220            if cmp.is_gt() {
12221                Ordering::Greater
12222            } else {
12223                Ordering::Less
12224            }
12225        }) {
12226            Ok(i) | Err(i) => i,
12227        };
12228        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12229            if let (Some(start_display), Some(end_display)) = (start, end) {
12230                results.push(
12231                    start_display.to_display_point(display_snapshot)
12232                        ..=end_display.to_display_point(display_snapshot),
12233                );
12234            }
12235        };
12236        let mut start_row: Option<Point> = None;
12237        let mut end_row: Option<Point> = None;
12238        if ranges.len() > count {
12239            return Vec::new();
12240        }
12241        for range in &ranges[start_ix..] {
12242            if range
12243                .start
12244                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12245                .is_ge()
12246            {
12247                break;
12248            }
12249            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12250            if let Some(current_row) = &end_row {
12251                if end.row == current_row.row {
12252                    continue;
12253                }
12254            }
12255            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12256            if start_row.is_none() {
12257                assert_eq!(end_row, None);
12258                start_row = Some(start);
12259                end_row = Some(end);
12260                continue;
12261            }
12262            if let Some(current_end) = end_row.as_mut() {
12263                if start.row > current_end.row + 1 {
12264                    push_region(start_row, end_row);
12265                    start_row = Some(start);
12266                    end_row = Some(end);
12267                } else {
12268                    // Merge two hunks.
12269                    *current_end = end;
12270                }
12271            } else {
12272                unreachable!();
12273            }
12274        }
12275        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12276        push_region(start_row, end_row);
12277        results
12278    }
12279
12280    pub fn gutter_highlights_in_range(
12281        &self,
12282        search_range: Range<Anchor>,
12283        display_snapshot: &DisplaySnapshot,
12284        cx: &AppContext,
12285    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12286        let mut results = Vec::new();
12287        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12288            let color = color_fetcher(cx);
12289            let start_ix = match ranges.binary_search_by(|probe| {
12290                let cmp = probe
12291                    .end
12292                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12293                if cmp.is_gt() {
12294                    Ordering::Greater
12295                } else {
12296                    Ordering::Less
12297                }
12298            }) {
12299                Ok(i) | Err(i) => i,
12300            };
12301            for range in &ranges[start_ix..] {
12302                if range
12303                    .start
12304                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12305                    .is_ge()
12306                {
12307                    break;
12308                }
12309
12310                let start = range.start.to_display_point(display_snapshot);
12311                let end = range.end.to_display_point(display_snapshot);
12312                results.push((start..end, color))
12313            }
12314        }
12315        results
12316    }
12317
12318    /// Get the text ranges corresponding to the redaction query
12319    pub fn redacted_ranges(
12320        &self,
12321        search_range: Range<Anchor>,
12322        display_snapshot: &DisplaySnapshot,
12323        cx: &WindowContext,
12324    ) -> Vec<Range<DisplayPoint>> {
12325        display_snapshot
12326            .buffer_snapshot
12327            .redacted_ranges(search_range, |file| {
12328                if let Some(file) = file {
12329                    file.is_private()
12330                        && EditorSettings::get(
12331                            Some(SettingsLocation {
12332                                worktree_id: file.worktree_id(cx),
12333                                path: file.path().as_ref(),
12334                            }),
12335                            cx,
12336                        )
12337                        .redact_private_values
12338                } else {
12339                    false
12340                }
12341            })
12342            .map(|range| {
12343                range.start.to_display_point(display_snapshot)
12344                    ..range.end.to_display_point(display_snapshot)
12345            })
12346            .collect()
12347    }
12348
12349    pub fn highlight_text<T: 'static>(
12350        &mut self,
12351        ranges: Vec<Range<Anchor>>,
12352        style: HighlightStyle,
12353        cx: &mut ViewContext<Self>,
12354    ) {
12355        self.display_map.update(cx, |map, _| {
12356            map.highlight_text(TypeId::of::<T>(), ranges, style)
12357        });
12358        cx.notify();
12359    }
12360
12361    pub(crate) fn highlight_inlays<T: 'static>(
12362        &mut self,
12363        highlights: Vec<InlayHighlight>,
12364        style: HighlightStyle,
12365        cx: &mut ViewContext<Self>,
12366    ) {
12367        self.display_map.update(cx, |map, _| {
12368            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12369        });
12370        cx.notify();
12371    }
12372
12373    pub fn text_highlights<'a, T: 'static>(
12374        &'a self,
12375        cx: &'a AppContext,
12376    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12377        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12378    }
12379
12380    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12381        let cleared = self
12382            .display_map
12383            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12384        if cleared {
12385            cx.notify();
12386        }
12387    }
12388
12389    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12390        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12391            && self.focus_handle.is_focused(cx)
12392    }
12393
12394    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12395        self.show_cursor_when_unfocused = is_enabled;
12396        cx.notify();
12397    }
12398
12399    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12400        cx.notify();
12401    }
12402
12403    fn on_buffer_event(
12404        &mut self,
12405        multibuffer: Model<MultiBuffer>,
12406        event: &multi_buffer::Event,
12407        cx: &mut ViewContext<Self>,
12408    ) {
12409        match event {
12410            multi_buffer::Event::Edited {
12411                singleton_buffer_edited,
12412            } => {
12413                self.scrollbar_marker_state.dirty = true;
12414                self.active_indent_guides_state.dirty = true;
12415                self.refresh_active_diagnostics(cx);
12416                self.refresh_code_actions(cx);
12417                if self.has_active_inline_completion(cx) {
12418                    self.update_visible_inline_completion(cx);
12419                }
12420                cx.emit(EditorEvent::BufferEdited);
12421                cx.emit(SearchEvent::MatchesInvalidated);
12422                if *singleton_buffer_edited {
12423                    if let Some(project) = &self.project {
12424                        let project = project.read(cx);
12425                        #[allow(clippy::mutable_key_type)]
12426                        let languages_affected = multibuffer
12427                            .read(cx)
12428                            .all_buffers()
12429                            .into_iter()
12430                            .filter_map(|buffer| {
12431                                let buffer = buffer.read(cx);
12432                                let language = buffer.language()?;
12433                                if project.is_local()
12434                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12435                                {
12436                                    None
12437                                } else {
12438                                    Some(language)
12439                                }
12440                            })
12441                            .cloned()
12442                            .collect::<HashSet<_>>();
12443                        if !languages_affected.is_empty() {
12444                            self.refresh_inlay_hints(
12445                                InlayHintRefreshReason::BufferEdited(languages_affected),
12446                                cx,
12447                            );
12448                        }
12449                    }
12450                }
12451
12452                let Some(project) = &self.project else { return };
12453                let (telemetry, is_via_ssh) = {
12454                    let project = project.read(cx);
12455                    let telemetry = project.client().telemetry().clone();
12456                    let is_via_ssh = project.is_via_ssh();
12457                    (telemetry, is_via_ssh)
12458                };
12459                refresh_linked_ranges(self, cx);
12460                telemetry.log_edit_event("editor", is_via_ssh);
12461            }
12462            multi_buffer::Event::ExcerptsAdded {
12463                buffer,
12464                predecessor,
12465                excerpts,
12466            } => {
12467                self.tasks_update_task = Some(self.refresh_runnables(cx));
12468                cx.emit(EditorEvent::ExcerptsAdded {
12469                    buffer: buffer.clone(),
12470                    predecessor: *predecessor,
12471                    excerpts: excerpts.clone(),
12472                });
12473                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12474            }
12475            multi_buffer::Event::ExcerptsRemoved { ids } => {
12476                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12477                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12478            }
12479            multi_buffer::Event::ExcerptsEdited { ids } => {
12480                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12481            }
12482            multi_buffer::Event::ExcerptsExpanded { ids } => {
12483                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12484            }
12485            multi_buffer::Event::Reparsed(buffer_id) => {
12486                self.tasks_update_task = Some(self.refresh_runnables(cx));
12487
12488                cx.emit(EditorEvent::Reparsed(*buffer_id));
12489            }
12490            multi_buffer::Event::LanguageChanged(buffer_id) => {
12491                linked_editing_ranges::refresh_linked_ranges(self, cx);
12492                cx.emit(EditorEvent::Reparsed(*buffer_id));
12493                cx.notify();
12494            }
12495            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12496            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12497            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12498                cx.emit(EditorEvent::TitleChanged)
12499            }
12500            multi_buffer::Event::DiffBaseChanged => {
12501                self.scrollbar_marker_state.dirty = true;
12502                cx.emit(EditorEvent::DiffBaseChanged);
12503                cx.notify();
12504            }
12505            multi_buffer::Event::DiffUpdated { buffer } => {
12506                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12507                cx.notify();
12508            }
12509            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12510            multi_buffer::Event::DiagnosticsUpdated => {
12511                self.refresh_active_diagnostics(cx);
12512                self.scrollbar_marker_state.dirty = true;
12513                cx.notify();
12514            }
12515            _ => {}
12516        };
12517    }
12518
12519    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12520        cx.notify();
12521    }
12522
12523    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12524        self.tasks_update_task = Some(self.refresh_runnables(cx));
12525        self.refresh_inline_completion(true, false, cx);
12526        self.refresh_inlay_hints(
12527            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12528                self.selections.newest_anchor().head(),
12529                &self.buffer.read(cx).snapshot(cx),
12530                cx,
12531            )),
12532            cx,
12533        );
12534
12535        let old_cursor_shape = self.cursor_shape;
12536
12537        {
12538            let editor_settings = EditorSettings::get_global(cx);
12539            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12540            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12541            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12542        }
12543
12544        if old_cursor_shape != self.cursor_shape {
12545            cx.emit(EditorEvent::CursorShapeChanged);
12546        }
12547
12548        let project_settings = ProjectSettings::get_global(cx);
12549        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12550
12551        if self.mode == EditorMode::Full {
12552            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12553            if self.git_blame_inline_enabled != inline_blame_enabled {
12554                self.toggle_git_blame_inline_internal(false, cx);
12555            }
12556        }
12557
12558        cx.notify();
12559    }
12560
12561    pub fn set_searchable(&mut self, searchable: bool) {
12562        self.searchable = searchable;
12563    }
12564
12565    pub fn searchable(&self) -> bool {
12566        self.searchable
12567    }
12568
12569    fn open_proposed_changes_editor(
12570        &mut self,
12571        _: &OpenProposedChangesEditor,
12572        cx: &mut ViewContext<Self>,
12573    ) {
12574        let Some(workspace) = self.workspace() else {
12575            cx.propagate();
12576            return;
12577        };
12578
12579        let selections = self.selections.all::<usize>(cx);
12580        let buffer = self.buffer.read(cx);
12581        let mut new_selections_by_buffer = HashMap::default();
12582        for selection in selections {
12583            for (buffer, range, _) in
12584                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12585            {
12586                let mut range = range.to_point(buffer.read(cx));
12587                range.start.column = 0;
12588                range.end.column = buffer.read(cx).line_len(range.end.row);
12589                new_selections_by_buffer
12590                    .entry(buffer)
12591                    .or_insert(Vec::new())
12592                    .push(range)
12593            }
12594        }
12595
12596        let proposed_changes_buffers = new_selections_by_buffer
12597            .into_iter()
12598            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12599            .collect::<Vec<_>>();
12600        let proposed_changes_editor = cx.new_view(|cx| {
12601            ProposedChangesEditor::new(
12602                "Proposed changes",
12603                proposed_changes_buffers,
12604                self.project.clone(),
12605                cx,
12606            )
12607        });
12608
12609        cx.window_context().defer(move |cx| {
12610            workspace.update(cx, |workspace, cx| {
12611                workspace.active_pane().update(cx, |pane, cx| {
12612                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12613                });
12614            });
12615        });
12616    }
12617
12618    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12619        self.open_excerpts_common(None, true, cx)
12620    }
12621
12622    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12623        self.open_excerpts_common(None, false, cx)
12624    }
12625
12626    fn open_excerpts_common(
12627        &mut self,
12628        jump_data: Option<JumpData>,
12629        split: bool,
12630        cx: &mut ViewContext<Self>,
12631    ) {
12632        let Some(workspace) = self.workspace() else {
12633            cx.propagate();
12634            return;
12635        };
12636
12637        if self.buffer.read(cx).is_singleton() {
12638            cx.propagate();
12639            return;
12640        }
12641
12642        let mut new_selections_by_buffer = HashMap::default();
12643        match &jump_data {
12644            Some(jump_data) => {
12645                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12646                if let Some(buffer) = multi_buffer_snapshot
12647                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12648                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12649                {
12650                    let buffer_snapshot = buffer.read(cx).snapshot();
12651                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12652                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12653                    } else {
12654                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12655                    };
12656                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12657                    new_selections_by_buffer.insert(
12658                        buffer,
12659                        (
12660                            vec![jump_to_offset..jump_to_offset],
12661                            Some(jump_data.line_offset_from_top),
12662                        ),
12663                    );
12664                }
12665            }
12666            None => {
12667                let selections = self.selections.all::<usize>(cx);
12668                let buffer = self.buffer.read(cx);
12669                for selection in selections {
12670                    for (mut buffer_handle, mut range, _) in
12671                        buffer.range_to_buffer_ranges(selection.range(), cx)
12672                    {
12673                        // When editing branch buffers, jump to the corresponding location
12674                        // in their base buffer.
12675                        let buffer = buffer_handle.read(cx);
12676                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12677                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12678                            buffer_handle = base_buffer;
12679                        }
12680
12681                        if selection.reversed {
12682                            mem::swap(&mut range.start, &mut range.end);
12683                        }
12684                        new_selections_by_buffer
12685                            .entry(buffer_handle)
12686                            .or_insert((Vec::new(), None))
12687                            .0
12688                            .push(range)
12689                    }
12690                }
12691            }
12692        }
12693
12694        if new_selections_by_buffer.is_empty() {
12695            return;
12696        }
12697
12698        // We defer the pane interaction because we ourselves are a workspace item
12699        // and activating a new item causes the pane to call a method on us reentrantly,
12700        // which panics if we're on the stack.
12701        cx.window_context().defer(move |cx| {
12702            workspace.update(cx, |workspace, cx| {
12703                let pane = if split {
12704                    workspace.adjacent_pane(cx)
12705                } else {
12706                    workspace.active_pane().clone()
12707                };
12708
12709                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12710                    let editor =
12711                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12712                    editor.update(cx, |editor, cx| {
12713                        let autoscroll = match scroll_offset {
12714                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12715                            None => Autoscroll::newest(),
12716                        };
12717                        let nav_history = editor.nav_history.take();
12718                        editor.change_selections(Some(autoscroll), cx, |s| {
12719                            s.select_ranges(ranges);
12720                        });
12721                        editor.nav_history = nav_history;
12722                    });
12723                }
12724            })
12725        });
12726    }
12727
12728    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12729        let snapshot = self.buffer.read(cx).read(cx);
12730        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12731        Some(
12732            ranges
12733                .iter()
12734                .map(move |range| {
12735                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12736                })
12737                .collect(),
12738        )
12739    }
12740
12741    fn selection_replacement_ranges(
12742        &self,
12743        range: Range<OffsetUtf16>,
12744        cx: &mut AppContext,
12745    ) -> Vec<Range<OffsetUtf16>> {
12746        let selections = self.selections.all::<OffsetUtf16>(cx);
12747        let newest_selection = selections
12748            .iter()
12749            .max_by_key(|selection| selection.id)
12750            .unwrap();
12751        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12752        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12753        let snapshot = self.buffer.read(cx).read(cx);
12754        selections
12755            .into_iter()
12756            .map(|mut selection| {
12757                selection.start.0 =
12758                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12759                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12760                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12761                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12762            })
12763            .collect()
12764    }
12765
12766    fn report_editor_event(
12767        &self,
12768        operation: &'static str,
12769        file_extension: Option<String>,
12770        cx: &AppContext,
12771    ) {
12772        if cfg!(any(test, feature = "test-support")) {
12773            return;
12774        }
12775
12776        let Some(project) = &self.project else { return };
12777
12778        // If None, we are in a file without an extension
12779        let file = self
12780            .buffer
12781            .read(cx)
12782            .as_singleton()
12783            .and_then(|b| b.read(cx).file());
12784        let file_extension = file_extension.or(file
12785            .as_ref()
12786            .and_then(|file| Path::new(file.file_name(cx)).extension())
12787            .and_then(|e| e.to_str())
12788            .map(|a| a.to_string()));
12789
12790        let vim_mode = cx
12791            .global::<SettingsStore>()
12792            .raw_user_settings()
12793            .get("vim_mode")
12794            == Some(&serde_json::Value::Bool(true));
12795
12796        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12797            == language::language_settings::InlineCompletionProvider::Copilot;
12798        let copilot_enabled_for_language = self
12799            .buffer
12800            .read(cx)
12801            .settings_at(0, cx)
12802            .show_inline_completions;
12803
12804        let project = project.read(cx);
12805        let telemetry = project.client().telemetry().clone();
12806        telemetry.report_editor_event(
12807            file_extension,
12808            vim_mode,
12809            operation,
12810            copilot_enabled,
12811            copilot_enabled_for_language,
12812            project.is_via_ssh(),
12813        )
12814    }
12815
12816    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12817    /// with each line being an array of {text, highlight} objects.
12818    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12819        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12820            return;
12821        };
12822
12823        #[derive(Serialize)]
12824        struct Chunk<'a> {
12825            text: String,
12826            highlight: Option<&'a str>,
12827        }
12828
12829        let snapshot = buffer.read(cx).snapshot();
12830        let range = self
12831            .selected_text_range(false, cx)
12832            .and_then(|selection| {
12833                if selection.range.is_empty() {
12834                    None
12835                } else {
12836                    Some(selection.range)
12837                }
12838            })
12839            .unwrap_or_else(|| 0..snapshot.len());
12840
12841        let chunks = snapshot.chunks(range, true);
12842        let mut lines = Vec::new();
12843        let mut line: VecDeque<Chunk> = VecDeque::new();
12844
12845        let Some(style) = self.style.as_ref() else {
12846            return;
12847        };
12848
12849        for chunk in chunks {
12850            let highlight = chunk
12851                .syntax_highlight_id
12852                .and_then(|id| id.name(&style.syntax));
12853            let mut chunk_lines = chunk.text.split('\n').peekable();
12854            while let Some(text) = chunk_lines.next() {
12855                let mut merged_with_last_token = false;
12856                if let Some(last_token) = line.back_mut() {
12857                    if last_token.highlight == highlight {
12858                        last_token.text.push_str(text);
12859                        merged_with_last_token = true;
12860                    }
12861                }
12862
12863                if !merged_with_last_token {
12864                    line.push_back(Chunk {
12865                        text: text.into(),
12866                        highlight,
12867                    });
12868                }
12869
12870                if chunk_lines.peek().is_some() {
12871                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12872                        line.pop_front();
12873                    }
12874                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12875                        line.pop_back();
12876                    }
12877
12878                    lines.push(mem::take(&mut line));
12879                }
12880            }
12881        }
12882
12883        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12884            return;
12885        };
12886        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12887    }
12888
12889    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12890        &self.inlay_hint_cache
12891    }
12892
12893    pub fn replay_insert_event(
12894        &mut self,
12895        text: &str,
12896        relative_utf16_range: Option<Range<isize>>,
12897        cx: &mut ViewContext<Self>,
12898    ) {
12899        if !self.input_enabled {
12900            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12901            return;
12902        }
12903        if let Some(relative_utf16_range) = relative_utf16_range {
12904            let selections = self.selections.all::<OffsetUtf16>(cx);
12905            self.change_selections(None, cx, |s| {
12906                let new_ranges = selections.into_iter().map(|range| {
12907                    let start = OffsetUtf16(
12908                        range
12909                            .head()
12910                            .0
12911                            .saturating_add_signed(relative_utf16_range.start),
12912                    );
12913                    let end = OffsetUtf16(
12914                        range
12915                            .head()
12916                            .0
12917                            .saturating_add_signed(relative_utf16_range.end),
12918                    );
12919                    start..end
12920                });
12921                s.select_ranges(new_ranges);
12922            });
12923        }
12924
12925        self.handle_input(text, cx);
12926    }
12927
12928    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12929        let Some(provider) = self.semantics_provider.as_ref() else {
12930            return false;
12931        };
12932
12933        let mut supports = false;
12934        self.buffer().read(cx).for_each_buffer(|buffer| {
12935            supports |= provider.supports_inlay_hints(buffer, cx);
12936        });
12937        supports
12938    }
12939
12940    pub fn focus(&self, cx: &mut WindowContext) {
12941        cx.focus(&self.focus_handle)
12942    }
12943
12944    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12945        self.focus_handle.is_focused(cx)
12946    }
12947
12948    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12949        cx.emit(EditorEvent::Focused);
12950
12951        if let Some(descendant) = self
12952            .last_focused_descendant
12953            .take()
12954            .and_then(|descendant| descendant.upgrade())
12955        {
12956            cx.focus(&descendant);
12957        } else {
12958            if let Some(blame) = self.blame.as_ref() {
12959                blame.update(cx, GitBlame::focus)
12960            }
12961
12962            self.blink_manager.update(cx, BlinkManager::enable);
12963            self.show_cursor_names(cx);
12964            self.buffer.update(cx, |buffer, cx| {
12965                buffer.finalize_last_transaction(cx);
12966                if self.leader_peer_id.is_none() {
12967                    buffer.set_active_selections(
12968                        &self.selections.disjoint_anchors(),
12969                        self.selections.line_mode,
12970                        self.cursor_shape,
12971                        cx,
12972                    );
12973                }
12974            });
12975        }
12976    }
12977
12978    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12979        cx.emit(EditorEvent::FocusedIn)
12980    }
12981
12982    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12983        if event.blurred != self.focus_handle {
12984            self.last_focused_descendant = Some(event.blurred);
12985        }
12986    }
12987
12988    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12989        self.blink_manager.update(cx, BlinkManager::disable);
12990        self.buffer
12991            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12992
12993        if let Some(blame) = self.blame.as_ref() {
12994            blame.update(cx, GitBlame::blur)
12995        }
12996        if !self.hover_state.focused(cx) {
12997            hide_hover(self, cx);
12998        }
12999
13000        self.hide_context_menu(cx);
13001        cx.emit(EditorEvent::Blurred);
13002        cx.notify();
13003    }
13004
13005    pub fn register_action<A: Action>(
13006        &mut self,
13007        listener: impl Fn(&A, &mut WindowContext) + 'static,
13008    ) -> Subscription {
13009        let id = self.next_editor_action_id.post_inc();
13010        let listener = Arc::new(listener);
13011        self.editor_actions.borrow_mut().insert(
13012            id,
13013            Box::new(move |cx| {
13014                let cx = cx.window_context();
13015                let listener = listener.clone();
13016                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13017                    let action = action.downcast_ref().unwrap();
13018                    if phase == DispatchPhase::Bubble {
13019                        listener(action, cx)
13020                    }
13021                })
13022            }),
13023        );
13024
13025        let editor_actions = self.editor_actions.clone();
13026        Subscription::new(move || {
13027            editor_actions.borrow_mut().remove(&id);
13028        })
13029    }
13030
13031    pub fn file_header_size(&self) -> u32 {
13032        FILE_HEADER_HEIGHT
13033    }
13034
13035    pub fn revert(
13036        &mut self,
13037        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13038        cx: &mut ViewContext<Self>,
13039    ) {
13040        self.buffer().update(cx, |multi_buffer, cx| {
13041            for (buffer_id, changes) in revert_changes {
13042                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13043                    buffer.update(cx, |buffer, cx| {
13044                        buffer.edit(
13045                            changes.into_iter().map(|(range, text)| {
13046                                (range, text.to_string().map(Arc::<str>::from))
13047                            }),
13048                            None,
13049                            cx,
13050                        );
13051                    });
13052                }
13053            }
13054        });
13055        self.change_selections(None, cx, |selections| selections.refresh());
13056    }
13057
13058    pub fn to_pixel_point(
13059        &mut self,
13060        source: multi_buffer::Anchor,
13061        editor_snapshot: &EditorSnapshot,
13062        cx: &mut ViewContext<Self>,
13063    ) -> Option<gpui::Point<Pixels>> {
13064        let source_point = source.to_display_point(editor_snapshot);
13065        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13066    }
13067
13068    pub fn display_to_pixel_point(
13069        &mut self,
13070        source: DisplayPoint,
13071        editor_snapshot: &EditorSnapshot,
13072        cx: &mut ViewContext<Self>,
13073    ) -> Option<gpui::Point<Pixels>> {
13074        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13075        let text_layout_details = self.text_layout_details(cx);
13076        let scroll_top = text_layout_details
13077            .scroll_anchor
13078            .scroll_position(editor_snapshot)
13079            .y;
13080
13081        if source.row().as_f32() < scroll_top.floor() {
13082            return None;
13083        }
13084        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13085        let source_y = line_height * (source.row().as_f32() - scroll_top);
13086        Some(gpui::Point::new(source_x, source_y))
13087    }
13088
13089    pub fn has_active_completions_menu(&self) -> bool {
13090        self.context_menu.read().as_ref().map_or(false, |menu| {
13091            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13092        })
13093    }
13094
13095    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13096        self.addons
13097            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13098    }
13099
13100    pub fn unregister_addon<T: Addon>(&mut self) {
13101        self.addons.remove(&std::any::TypeId::of::<T>());
13102    }
13103
13104    pub fn addon<T: Addon>(&self) -> Option<&T> {
13105        let type_id = std::any::TypeId::of::<T>();
13106        self.addons
13107            .get(&type_id)
13108            .and_then(|item| item.to_any().downcast_ref::<T>())
13109    }
13110}
13111
13112fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13113    let tab_size = tab_size.get() as usize;
13114    let mut width = offset;
13115
13116    for ch in text.chars() {
13117        width += if ch == '\t' {
13118            tab_size - (width % tab_size)
13119        } else {
13120            1
13121        };
13122    }
13123
13124    width - offset
13125}
13126
13127#[cfg(test)]
13128mod tests {
13129    use super::*;
13130
13131    #[test]
13132    fn test_string_size_with_expanded_tabs() {
13133        let nz = |val| NonZeroU32::new(val).unwrap();
13134        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13135        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13136        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13137        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13138        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13139        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13140        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13141        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13142    }
13143}
13144
13145/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13146struct WordBreakingTokenizer<'a> {
13147    input: &'a str,
13148}
13149
13150impl<'a> WordBreakingTokenizer<'a> {
13151    fn new(input: &'a str) -> Self {
13152        Self { input }
13153    }
13154}
13155
13156fn is_char_ideographic(ch: char) -> bool {
13157    use unicode_script::Script::*;
13158    use unicode_script::UnicodeScript;
13159    matches!(ch.script(), Han | Tangut | Yi)
13160}
13161
13162fn is_grapheme_ideographic(text: &str) -> bool {
13163    text.chars().any(is_char_ideographic)
13164}
13165
13166fn is_grapheme_whitespace(text: &str) -> bool {
13167    text.chars().any(|x| x.is_whitespace())
13168}
13169
13170fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13171    text.chars().next().map_or(false, |ch| {
13172        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13173    })
13174}
13175
13176#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13177struct WordBreakToken<'a> {
13178    token: &'a str,
13179    grapheme_len: usize,
13180    is_whitespace: bool,
13181}
13182
13183impl<'a> Iterator for WordBreakingTokenizer<'a> {
13184    /// Yields a span, the count of graphemes in the token, and whether it was
13185    /// whitespace. Note that it also breaks at word boundaries.
13186    type Item = WordBreakToken<'a>;
13187
13188    fn next(&mut self) -> Option<Self::Item> {
13189        use unicode_segmentation::UnicodeSegmentation;
13190        if self.input.is_empty() {
13191            return None;
13192        }
13193
13194        let mut iter = self.input.graphemes(true).peekable();
13195        let mut offset = 0;
13196        let mut graphemes = 0;
13197        if let Some(first_grapheme) = iter.next() {
13198            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13199            offset += first_grapheme.len();
13200            graphemes += 1;
13201            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13202                if let Some(grapheme) = iter.peek().copied() {
13203                    if should_stay_with_preceding_ideograph(grapheme) {
13204                        offset += grapheme.len();
13205                        graphemes += 1;
13206                    }
13207                }
13208            } else {
13209                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13210                let mut next_word_bound = words.peek().copied();
13211                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13212                    next_word_bound = words.next();
13213                }
13214                while let Some(grapheme) = iter.peek().copied() {
13215                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13216                        break;
13217                    };
13218                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13219                        break;
13220                    };
13221                    offset += grapheme.len();
13222                    graphemes += 1;
13223                    iter.next();
13224                }
13225            }
13226            let token = &self.input[..offset];
13227            self.input = &self.input[offset..];
13228            if is_whitespace {
13229                Some(WordBreakToken {
13230                    token: " ",
13231                    grapheme_len: 1,
13232                    is_whitespace: true,
13233                })
13234            } else {
13235                Some(WordBreakToken {
13236                    token,
13237                    grapheme_len: graphemes,
13238                    is_whitespace: false,
13239                })
13240            }
13241        } else {
13242            None
13243        }
13244    }
13245}
13246
13247#[test]
13248fn test_word_breaking_tokenizer() {
13249    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13250        ("", &[]),
13251        ("  ", &[(" ", 1, true)]),
13252        ("Ʒ", &[("Ʒ", 1, false)]),
13253        ("Ǽ", &[("Ǽ", 1, false)]),
13254        ("", &[("", 1, false)]),
13255        ("⋑⋑", &[("⋑⋑", 2, false)]),
13256        (
13257            "原理,进而",
13258            &[
13259                ("", 1, false),
13260                ("理,", 2, false),
13261                ("", 1, false),
13262                ("", 1, false),
13263            ],
13264        ),
13265        (
13266            "hello world",
13267            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13268        ),
13269        (
13270            "hello, world",
13271            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13272        ),
13273        (
13274            "  hello world",
13275            &[
13276                (" ", 1, true),
13277                ("hello", 5, false),
13278                (" ", 1, true),
13279                ("world", 5, false),
13280            ],
13281        ),
13282        (
13283            "这是什么 \n 钢笔",
13284            &[
13285                ("", 1, false),
13286                ("", 1, false),
13287                ("", 1, false),
13288                ("", 1, false),
13289                (" ", 1, true),
13290                ("", 1, false),
13291                ("", 1, false),
13292            ],
13293        ),
13294        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13295    ];
13296
13297    for (input, result) in tests {
13298        assert_eq!(
13299            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13300            result
13301                .iter()
13302                .copied()
13303                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13304                    token,
13305                    grapheme_len,
13306                    is_whitespace,
13307                })
13308                .collect::<Vec<_>>()
13309        );
13310    }
13311}
13312
13313fn wrap_with_prefix(
13314    line_prefix: String,
13315    unwrapped_text: String,
13316    wrap_column: usize,
13317    tab_size: NonZeroU32,
13318) -> String {
13319    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13320    let mut wrapped_text = String::new();
13321    let mut current_line = line_prefix.clone();
13322
13323    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13324    let mut current_line_len = line_prefix_len;
13325    for WordBreakToken {
13326        token,
13327        grapheme_len,
13328        is_whitespace,
13329    } in tokenizer
13330    {
13331        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13332            wrapped_text.push_str(current_line.trim_end());
13333            wrapped_text.push('\n');
13334            current_line.truncate(line_prefix.len());
13335            current_line_len = line_prefix_len;
13336            if !is_whitespace {
13337                current_line.push_str(token);
13338                current_line_len += grapheme_len;
13339            }
13340        } else if !is_whitespace {
13341            current_line.push_str(token);
13342            current_line_len += grapheme_len;
13343        } else if current_line_len != line_prefix_len {
13344            current_line.push(' ');
13345            current_line_len += 1;
13346        }
13347    }
13348
13349    if !current_line.is_empty() {
13350        wrapped_text.push_str(&current_line);
13351    }
13352    wrapped_text
13353}
13354
13355#[test]
13356fn test_wrap_with_prefix() {
13357    assert_eq!(
13358        wrap_with_prefix(
13359            "# ".to_string(),
13360            "abcdefg".to_string(),
13361            4,
13362            NonZeroU32::new(4).unwrap()
13363        ),
13364        "# abcdefg"
13365    );
13366    assert_eq!(
13367        wrap_with_prefix(
13368            "".to_string(),
13369            "\thello world".to_string(),
13370            8,
13371            NonZeroU32::new(4).unwrap()
13372        ),
13373        "hello\nworld"
13374    );
13375    assert_eq!(
13376        wrap_with_prefix(
13377            "// ".to_string(),
13378            "xx \nyy zz aa bb cc".to_string(),
13379            12,
13380            NonZeroU32::new(4).unwrap()
13381        ),
13382        "// xx yy zz\n// aa bb cc"
13383    );
13384    assert_eq!(
13385        wrap_with_prefix(
13386            String::new(),
13387            "这是什么 \n 钢笔".to_string(),
13388            3,
13389            NonZeroU32::new(4).unwrap()
13390        ),
13391        "这是什\n么 钢\n"
13392    );
13393}
13394
13395fn hunks_for_selections(
13396    multi_buffer_snapshot: &MultiBufferSnapshot,
13397    selections: &[Selection<Anchor>],
13398) -> Vec<MultiBufferDiffHunk> {
13399    let buffer_rows_for_selections = selections.iter().map(|selection| {
13400        let head = selection.head();
13401        let tail = selection.tail();
13402        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13403        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13404        if start > end {
13405            end..start
13406        } else {
13407            start..end
13408        }
13409    });
13410
13411    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13412}
13413
13414pub fn hunks_for_rows(
13415    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13416    multi_buffer_snapshot: &MultiBufferSnapshot,
13417) -> Vec<MultiBufferDiffHunk> {
13418    let mut hunks = Vec::new();
13419    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13420        HashMap::default();
13421    for selected_multi_buffer_rows in rows {
13422        let query_rows =
13423            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13424        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13425            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13426            // when the caret is just above or just below the deleted hunk.
13427            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13428            let related_to_selection = if allow_adjacent {
13429                hunk.row_range.overlaps(&query_rows)
13430                    || hunk.row_range.start == query_rows.end
13431                    || hunk.row_range.end == query_rows.start
13432            } else {
13433                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13434                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13435                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13436                    || selected_multi_buffer_rows.end == hunk.row_range.start
13437            };
13438            if related_to_selection {
13439                if !processed_buffer_rows
13440                    .entry(hunk.buffer_id)
13441                    .or_default()
13442                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13443                {
13444                    continue;
13445                }
13446                hunks.push(hunk);
13447            }
13448        }
13449    }
13450
13451    hunks
13452}
13453
13454pub trait CollaborationHub {
13455    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13456    fn user_participant_indices<'a>(
13457        &self,
13458        cx: &'a AppContext,
13459    ) -> &'a HashMap<u64, ParticipantIndex>;
13460    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13461}
13462
13463impl CollaborationHub for Model<Project> {
13464    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13465        self.read(cx).collaborators()
13466    }
13467
13468    fn user_participant_indices<'a>(
13469        &self,
13470        cx: &'a AppContext,
13471    ) -> &'a HashMap<u64, ParticipantIndex> {
13472        self.read(cx).user_store().read(cx).participant_indices()
13473    }
13474
13475    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13476        let this = self.read(cx);
13477        let user_ids = this.collaborators().values().map(|c| c.user_id);
13478        this.user_store().read_with(cx, |user_store, cx| {
13479            user_store.participant_names(user_ids, cx)
13480        })
13481    }
13482}
13483
13484pub trait SemanticsProvider {
13485    fn hover(
13486        &self,
13487        buffer: &Model<Buffer>,
13488        position: text::Anchor,
13489        cx: &mut AppContext,
13490    ) -> Option<Task<Vec<project::Hover>>>;
13491
13492    fn inlay_hints(
13493        &self,
13494        buffer_handle: Model<Buffer>,
13495        range: Range<text::Anchor>,
13496        cx: &mut AppContext,
13497    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13498
13499    fn resolve_inlay_hint(
13500        &self,
13501        hint: InlayHint,
13502        buffer_handle: Model<Buffer>,
13503        server_id: LanguageServerId,
13504        cx: &mut AppContext,
13505    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13506
13507    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13508
13509    fn document_highlights(
13510        &self,
13511        buffer: &Model<Buffer>,
13512        position: text::Anchor,
13513        cx: &mut AppContext,
13514    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13515
13516    fn definitions(
13517        &self,
13518        buffer: &Model<Buffer>,
13519        position: text::Anchor,
13520        kind: GotoDefinitionKind,
13521        cx: &mut AppContext,
13522    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13523
13524    fn range_for_rename(
13525        &self,
13526        buffer: &Model<Buffer>,
13527        position: text::Anchor,
13528        cx: &mut AppContext,
13529    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13530
13531    fn perform_rename(
13532        &self,
13533        buffer: &Model<Buffer>,
13534        position: text::Anchor,
13535        new_name: String,
13536        cx: &mut AppContext,
13537    ) -> Option<Task<Result<ProjectTransaction>>>;
13538}
13539
13540pub trait CompletionProvider {
13541    fn completions(
13542        &self,
13543        buffer: &Model<Buffer>,
13544        buffer_position: text::Anchor,
13545        trigger: CompletionContext,
13546        cx: &mut ViewContext<Editor>,
13547    ) -> Task<Result<Vec<Completion>>>;
13548
13549    fn resolve_completions(
13550        &self,
13551        buffer: Model<Buffer>,
13552        completion_indices: Vec<usize>,
13553        completions: Arc<RwLock<Box<[Completion]>>>,
13554        cx: &mut ViewContext<Editor>,
13555    ) -> Task<Result<bool>>;
13556
13557    fn apply_additional_edits_for_completion(
13558        &self,
13559        buffer: Model<Buffer>,
13560        completion: Completion,
13561        push_to_history: bool,
13562        cx: &mut ViewContext<Editor>,
13563    ) -> Task<Result<Option<language::Transaction>>>;
13564
13565    fn is_completion_trigger(
13566        &self,
13567        buffer: &Model<Buffer>,
13568        position: language::Anchor,
13569        text: &str,
13570        trigger_in_words: bool,
13571        cx: &mut ViewContext<Editor>,
13572    ) -> bool;
13573
13574    fn sort_completions(&self) -> bool {
13575        true
13576    }
13577}
13578
13579pub trait CodeActionProvider {
13580    fn code_actions(
13581        &self,
13582        buffer: &Model<Buffer>,
13583        range: Range<text::Anchor>,
13584        cx: &mut WindowContext,
13585    ) -> Task<Result<Vec<CodeAction>>>;
13586
13587    fn apply_code_action(
13588        &self,
13589        buffer_handle: Model<Buffer>,
13590        action: CodeAction,
13591        excerpt_id: ExcerptId,
13592        push_to_history: bool,
13593        cx: &mut WindowContext,
13594    ) -> Task<Result<ProjectTransaction>>;
13595}
13596
13597impl CodeActionProvider for Model<Project> {
13598    fn code_actions(
13599        &self,
13600        buffer: &Model<Buffer>,
13601        range: Range<text::Anchor>,
13602        cx: &mut WindowContext,
13603    ) -> Task<Result<Vec<CodeAction>>> {
13604        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13605    }
13606
13607    fn apply_code_action(
13608        &self,
13609        buffer_handle: Model<Buffer>,
13610        action: CodeAction,
13611        _excerpt_id: ExcerptId,
13612        push_to_history: bool,
13613        cx: &mut WindowContext,
13614    ) -> Task<Result<ProjectTransaction>> {
13615        self.update(cx, |project, cx| {
13616            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13617        })
13618    }
13619}
13620
13621fn snippet_completions(
13622    project: &Project,
13623    buffer: &Model<Buffer>,
13624    buffer_position: text::Anchor,
13625    cx: &mut AppContext,
13626) -> Vec<Completion> {
13627    let language = buffer.read(cx).language_at(buffer_position);
13628    let language_name = language.as_ref().map(|language| language.lsp_id());
13629    let snippet_store = project.snippets().read(cx);
13630    let snippets = snippet_store.snippets_for(language_name, cx);
13631
13632    if snippets.is_empty() {
13633        return vec![];
13634    }
13635    let snapshot = buffer.read(cx).text_snapshot();
13636    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13637
13638    let scope = language.map(|language| language.default_scope());
13639    let classifier = CharClassifier::new(scope).for_completion(true);
13640    let mut last_word = chars
13641        .take_while(|c| classifier.is_word(*c))
13642        .collect::<String>();
13643    last_word = last_word.chars().rev().collect();
13644    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13645    let to_lsp = |point: &text::Anchor| {
13646        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13647        point_to_lsp(end)
13648    };
13649    let lsp_end = to_lsp(&buffer_position);
13650    snippets
13651        .into_iter()
13652        .filter_map(|snippet| {
13653            let matching_prefix = snippet
13654                .prefix
13655                .iter()
13656                .find(|prefix| prefix.starts_with(&last_word))?;
13657            let start = as_offset - last_word.len();
13658            let start = snapshot.anchor_before(start);
13659            let range = start..buffer_position;
13660            let lsp_start = to_lsp(&start);
13661            let lsp_range = lsp::Range {
13662                start: lsp_start,
13663                end: lsp_end,
13664            };
13665            Some(Completion {
13666                old_range: range,
13667                new_text: snippet.body.clone(),
13668                label: CodeLabel {
13669                    text: matching_prefix.clone(),
13670                    runs: vec![],
13671                    filter_range: 0..matching_prefix.len(),
13672                },
13673                server_id: LanguageServerId(usize::MAX),
13674                documentation: snippet.description.clone().map(Documentation::SingleLine),
13675                lsp_completion: lsp::CompletionItem {
13676                    label: snippet.prefix.first().unwrap().clone(),
13677                    kind: Some(CompletionItemKind::SNIPPET),
13678                    label_details: snippet.description.as_ref().map(|description| {
13679                        lsp::CompletionItemLabelDetails {
13680                            detail: Some(description.clone()),
13681                            description: None,
13682                        }
13683                    }),
13684                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13685                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13686                        lsp::InsertReplaceEdit {
13687                            new_text: snippet.body.clone(),
13688                            insert: lsp_range,
13689                            replace: lsp_range,
13690                        },
13691                    )),
13692                    filter_text: Some(snippet.body.clone()),
13693                    sort_text: Some(char::MAX.to_string()),
13694                    ..Default::default()
13695                },
13696                confirm: None,
13697            })
13698        })
13699        .collect()
13700}
13701
13702impl CompletionProvider for Model<Project> {
13703    fn completions(
13704        &self,
13705        buffer: &Model<Buffer>,
13706        buffer_position: text::Anchor,
13707        options: CompletionContext,
13708        cx: &mut ViewContext<Editor>,
13709    ) -> Task<Result<Vec<Completion>>> {
13710        self.update(cx, |project, cx| {
13711            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13712            let project_completions = project.completions(buffer, buffer_position, options, cx);
13713            cx.background_executor().spawn(async move {
13714                let mut completions = project_completions.await?;
13715                //let snippets = snippets.into_iter().;
13716                completions.extend(snippets);
13717                Ok(completions)
13718            })
13719        })
13720    }
13721
13722    fn resolve_completions(
13723        &self,
13724        buffer: Model<Buffer>,
13725        completion_indices: Vec<usize>,
13726        completions: Arc<RwLock<Box<[Completion]>>>,
13727        cx: &mut ViewContext<Editor>,
13728    ) -> Task<Result<bool>> {
13729        self.update(cx, |project, cx| {
13730            project.resolve_completions(buffer, completion_indices, completions, cx)
13731        })
13732    }
13733
13734    fn apply_additional_edits_for_completion(
13735        &self,
13736        buffer: Model<Buffer>,
13737        completion: Completion,
13738        push_to_history: bool,
13739        cx: &mut ViewContext<Editor>,
13740    ) -> Task<Result<Option<language::Transaction>>> {
13741        self.update(cx, |project, cx| {
13742            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13743        })
13744    }
13745
13746    fn is_completion_trigger(
13747        &self,
13748        buffer: &Model<Buffer>,
13749        position: language::Anchor,
13750        text: &str,
13751        trigger_in_words: bool,
13752        cx: &mut ViewContext<Editor>,
13753    ) -> bool {
13754        if !EditorSettings::get_global(cx).show_completions_on_input {
13755            return false;
13756        }
13757
13758        let mut chars = text.chars();
13759        let char = if let Some(char) = chars.next() {
13760            char
13761        } else {
13762            return false;
13763        };
13764        if chars.next().is_some() {
13765            return false;
13766        }
13767
13768        let buffer = buffer.read(cx);
13769        let classifier = buffer
13770            .snapshot()
13771            .char_classifier_at(position)
13772            .for_completion(true);
13773        if trigger_in_words && classifier.is_word(char) {
13774            return true;
13775        }
13776
13777        buffer.completion_triggers().contains(text)
13778    }
13779}
13780
13781impl SemanticsProvider for Model<Project> {
13782    fn hover(
13783        &self,
13784        buffer: &Model<Buffer>,
13785        position: text::Anchor,
13786        cx: &mut AppContext,
13787    ) -> Option<Task<Vec<project::Hover>>> {
13788        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13789    }
13790
13791    fn document_highlights(
13792        &self,
13793        buffer: &Model<Buffer>,
13794        position: text::Anchor,
13795        cx: &mut AppContext,
13796    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13797        Some(self.update(cx, |project, cx| {
13798            project.document_highlights(buffer, position, cx)
13799        }))
13800    }
13801
13802    fn definitions(
13803        &self,
13804        buffer: &Model<Buffer>,
13805        position: text::Anchor,
13806        kind: GotoDefinitionKind,
13807        cx: &mut AppContext,
13808    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13809        Some(self.update(cx, |project, cx| match kind {
13810            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13811            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13812            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13813            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13814        }))
13815    }
13816
13817    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13818        // TODO: make this work for remote projects
13819        self.read(cx)
13820            .language_servers_for_buffer(buffer.read(cx), cx)
13821            .any(
13822                |(_, server)| match server.capabilities().inlay_hint_provider {
13823                    Some(lsp::OneOf::Left(enabled)) => enabled,
13824                    Some(lsp::OneOf::Right(_)) => true,
13825                    None => false,
13826                },
13827            )
13828    }
13829
13830    fn inlay_hints(
13831        &self,
13832        buffer_handle: Model<Buffer>,
13833        range: Range<text::Anchor>,
13834        cx: &mut AppContext,
13835    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13836        Some(self.update(cx, |project, cx| {
13837            project.inlay_hints(buffer_handle, range, cx)
13838        }))
13839    }
13840
13841    fn resolve_inlay_hint(
13842        &self,
13843        hint: InlayHint,
13844        buffer_handle: Model<Buffer>,
13845        server_id: LanguageServerId,
13846        cx: &mut AppContext,
13847    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13848        Some(self.update(cx, |project, cx| {
13849            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13850        }))
13851    }
13852
13853    fn range_for_rename(
13854        &self,
13855        buffer: &Model<Buffer>,
13856        position: text::Anchor,
13857        cx: &mut AppContext,
13858    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13859        Some(self.update(cx, |project, cx| {
13860            project.prepare_rename(buffer.clone(), position, cx)
13861        }))
13862    }
13863
13864    fn perform_rename(
13865        &self,
13866        buffer: &Model<Buffer>,
13867        position: text::Anchor,
13868        new_name: String,
13869        cx: &mut AppContext,
13870    ) -> Option<Task<Result<ProjectTransaction>>> {
13871        Some(self.update(cx, |project, cx| {
13872            project.perform_rename(buffer.clone(), position, new_name, cx)
13873        }))
13874    }
13875}
13876
13877fn inlay_hint_settings(
13878    location: Anchor,
13879    snapshot: &MultiBufferSnapshot,
13880    cx: &mut ViewContext<'_, Editor>,
13881) -> InlayHintSettings {
13882    let file = snapshot.file_at(location);
13883    let language = snapshot.language_at(location).map(|l| l.name());
13884    language_settings(language, file, cx).inlay_hints
13885}
13886
13887fn consume_contiguous_rows(
13888    contiguous_row_selections: &mut Vec<Selection<Point>>,
13889    selection: &Selection<Point>,
13890    display_map: &DisplaySnapshot,
13891    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13892) -> (MultiBufferRow, MultiBufferRow) {
13893    contiguous_row_selections.push(selection.clone());
13894    let start_row = MultiBufferRow(selection.start.row);
13895    let mut end_row = ending_row(selection, display_map);
13896
13897    while let Some(next_selection) = selections.peek() {
13898        if next_selection.start.row <= end_row.0 {
13899            end_row = ending_row(next_selection, display_map);
13900            contiguous_row_selections.push(selections.next().unwrap().clone());
13901        } else {
13902            break;
13903        }
13904    }
13905    (start_row, end_row)
13906}
13907
13908fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13909    if next_selection.end.column > 0 || next_selection.is_empty() {
13910        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13911    } else {
13912        MultiBufferRow(next_selection.end.row)
13913    }
13914}
13915
13916impl EditorSnapshot {
13917    pub fn remote_selections_in_range<'a>(
13918        &'a self,
13919        range: &'a Range<Anchor>,
13920        collaboration_hub: &dyn CollaborationHub,
13921        cx: &'a AppContext,
13922    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13923        let participant_names = collaboration_hub.user_names(cx);
13924        let participant_indices = collaboration_hub.user_participant_indices(cx);
13925        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13926        let collaborators_by_replica_id = collaborators_by_peer_id
13927            .iter()
13928            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13929            .collect::<HashMap<_, _>>();
13930        self.buffer_snapshot
13931            .selections_in_range(range, false)
13932            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13933                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13934                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13935                let user_name = participant_names.get(&collaborator.user_id).cloned();
13936                Some(RemoteSelection {
13937                    replica_id,
13938                    selection,
13939                    cursor_shape,
13940                    line_mode,
13941                    participant_index,
13942                    peer_id: collaborator.peer_id,
13943                    user_name,
13944                })
13945            })
13946    }
13947
13948    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13949        self.display_snapshot.buffer_snapshot.language_at(position)
13950    }
13951
13952    pub fn is_focused(&self) -> bool {
13953        self.is_focused
13954    }
13955
13956    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13957        self.placeholder_text.as_ref()
13958    }
13959
13960    pub fn scroll_position(&self) -> gpui::Point<f32> {
13961        self.scroll_anchor.scroll_position(&self.display_snapshot)
13962    }
13963
13964    fn gutter_dimensions(
13965        &self,
13966        font_id: FontId,
13967        font_size: Pixels,
13968        em_width: Pixels,
13969        em_advance: Pixels,
13970        max_line_number_width: Pixels,
13971        cx: &AppContext,
13972    ) -> GutterDimensions {
13973        if !self.show_gutter {
13974            return GutterDimensions::default();
13975        }
13976        let descent = cx.text_system().descent(font_id, font_size);
13977
13978        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13979            matches!(
13980                ProjectSettings::get_global(cx).git.git_gutter,
13981                Some(GitGutterSetting::TrackedFiles)
13982            )
13983        });
13984        let gutter_settings = EditorSettings::get_global(cx).gutter;
13985        let show_line_numbers = self
13986            .show_line_numbers
13987            .unwrap_or(gutter_settings.line_numbers);
13988        let line_gutter_width = if show_line_numbers {
13989            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13990            let min_width_for_number_on_gutter = em_advance * 4.0;
13991            max_line_number_width.max(min_width_for_number_on_gutter)
13992        } else {
13993            0.0.into()
13994        };
13995
13996        let show_code_actions = self
13997            .show_code_actions
13998            .unwrap_or(gutter_settings.code_actions);
13999
14000        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14001
14002        let git_blame_entries_width =
14003            self.git_blame_gutter_max_author_length
14004                .map(|max_author_length| {
14005                    // Length of the author name, but also space for the commit hash,
14006                    // the spacing and the timestamp.
14007                    let max_char_count = max_author_length
14008                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14009                        + 7 // length of commit sha
14010                        + 14 // length of max relative timestamp ("60 minutes ago")
14011                        + 4; // gaps and margins
14012
14013                    em_advance * max_char_count
14014                });
14015
14016        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14017        left_padding += if show_code_actions || show_runnables {
14018            em_width * 3.0
14019        } else if show_git_gutter && show_line_numbers {
14020            em_width * 2.0
14021        } else if show_git_gutter || show_line_numbers {
14022            em_width
14023        } else {
14024            px(0.)
14025        };
14026
14027        let right_padding = if gutter_settings.folds && show_line_numbers {
14028            em_width * 4.0
14029        } else if gutter_settings.folds {
14030            em_width * 3.0
14031        } else if show_line_numbers {
14032            em_width
14033        } else {
14034            px(0.)
14035        };
14036
14037        GutterDimensions {
14038            left_padding,
14039            right_padding,
14040            width: line_gutter_width + left_padding + right_padding,
14041            margin: -descent,
14042            git_blame_entries_width,
14043        }
14044    }
14045
14046    pub fn render_fold_toggle(
14047        &self,
14048        buffer_row: MultiBufferRow,
14049        row_contains_cursor: bool,
14050        editor: View<Editor>,
14051        cx: &mut WindowContext,
14052    ) -> Option<AnyElement> {
14053        let folded = self.is_line_folded(buffer_row);
14054
14055        if let Some(crease) = self
14056            .crease_snapshot
14057            .query_row(buffer_row, &self.buffer_snapshot)
14058        {
14059            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14060                if folded {
14061                    editor.update(cx, |editor, cx| {
14062                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14063                    });
14064                } else {
14065                    editor.update(cx, |editor, cx| {
14066                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14067                    });
14068                }
14069            });
14070
14071            Some((crease.render_toggle)(
14072                buffer_row,
14073                folded,
14074                toggle_callback,
14075                cx,
14076            ))
14077        } else if folded
14078            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
14079        {
14080            Some(
14081                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
14082                    .selected(folded)
14083                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14084                        if folded {
14085                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14086                        } else {
14087                            this.fold_at(&FoldAt { buffer_row }, cx);
14088                        }
14089                    }))
14090                    .into_any_element(),
14091            )
14092        } else {
14093            None
14094        }
14095    }
14096
14097    pub fn render_crease_trailer(
14098        &self,
14099        buffer_row: MultiBufferRow,
14100        cx: &mut WindowContext,
14101    ) -> Option<AnyElement> {
14102        let folded = self.is_line_folded(buffer_row);
14103        let crease = self
14104            .crease_snapshot
14105            .query_row(buffer_row, &self.buffer_snapshot)?;
14106        Some((crease.render_trailer)(buffer_row, folded, cx))
14107    }
14108}
14109
14110impl Deref for EditorSnapshot {
14111    type Target = DisplaySnapshot;
14112
14113    fn deref(&self) -> &Self::Target {
14114        &self.display_snapshot
14115    }
14116}
14117
14118#[derive(Clone, Debug, PartialEq, Eq)]
14119pub enum EditorEvent {
14120    InputIgnored {
14121        text: Arc<str>,
14122    },
14123    InputHandled {
14124        utf16_range_to_replace: Option<Range<isize>>,
14125        text: Arc<str>,
14126    },
14127    ExcerptsAdded {
14128        buffer: Model<Buffer>,
14129        predecessor: ExcerptId,
14130        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14131    },
14132    ExcerptsRemoved {
14133        ids: Vec<ExcerptId>,
14134    },
14135    ExcerptsEdited {
14136        ids: Vec<ExcerptId>,
14137    },
14138    ExcerptsExpanded {
14139        ids: Vec<ExcerptId>,
14140    },
14141    BufferEdited,
14142    Edited {
14143        transaction_id: clock::Lamport,
14144    },
14145    Reparsed(BufferId),
14146    Focused,
14147    FocusedIn,
14148    Blurred,
14149    DirtyChanged,
14150    Saved,
14151    TitleChanged,
14152    DiffBaseChanged,
14153    SelectionsChanged {
14154        local: bool,
14155    },
14156    ScrollPositionChanged {
14157        local: bool,
14158        autoscroll: bool,
14159    },
14160    Closed,
14161    TransactionUndone {
14162        transaction_id: clock::Lamport,
14163    },
14164    TransactionBegun {
14165        transaction_id: clock::Lamport,
14166    },
14167    Reloaded,
14168    CursorShapeChanged,
14169}
14170
14171impl EventEmitter<EditorEvent> for Editor {}
14172
14173impl FocusableView for Editor {
14174    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14175        self.focus_handle.clone()
14176    }
14177}
14178
14179impl Render for Editor {
14180    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14181        let settings = ThemeSettings::get_global(cx);
14182
14183        let mut text_style = match self.mode {
14184            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14185                color: cx.theme().colors().editor_foreground,
14186                font_family: settings.ui_font.family.clone(),
14187                font_features: settings.ui_font.features.clone(),
14188                font_fallbacks: settings.ui_font.fallbacks.clone(),
14189                font_size: rems(0.875).into(),
14190                font_weight: settings.ui_font.weight,
14191                line_height: relative(settings.buffer_line_height.value()),
14192                ..Default::default()
14193            },
14194            EditorMode::Full => TextStyle {
14195                color: cx.theme().colors().editor_foreground,
14196                font_family: settings.buffer_font.family.clone(),
14197                font_features: settings.buffer_font.features.clone(),
14198                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14199                font_size: settings.buffer_font_size(cx).into(),
14200                font_weight: settings.buffer_font.weight,
14201                line_height: relative(settings.buffer_line_height.value()),
14202                ..Default::default()
14203            },
14204        };
14205        if let Some(text_style_refinement) = &self.text_style_refinement {
14206            text_style.refine(text_style_refinement)
14207        }
14208
14209        let background = match self.mode {
14210            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14211            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14212            EditorMode::Full => cx.theme().colors().editor_background,
14213        };
14214
14215        EditorElement::new(
14216            cx.view(),
14217            EditorStyle {
14218                background,
14219                local_player: cx.theme().players().local(),
14220                text: text_style,
14221                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14222                syntax: cx.theme().syntax().clone(),
14223                status: cx.theme().status().clone(),
14224                inlay_hints_style: make_inlay_hints_style(cx),
14225                suggestions_style: HighlightStyle {
14226                    color: Some(cx.theme().status().predictive),
14227                    ..HighlightStyle::default()
14228                },
14229                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14230            },
14231        )
14232    }
14233}
14234
14235impl ViewInputHandler for Editor {
14236    fn text_for_range(
14237        &mut self,
14238        range_utf16: Range<usize>,
14239        cx: &mut ViewContext<Self>,
14240    ) -> Option<String> {
14241        Some(
14242            self.buffer
14243                .read(cx)
14244                .read(cx)
14245                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14246                .collect(),
14247        )
14248    }
14249
14250    fn selected_text_range(
14251        &mut self,
14252        ignore_disabled_input: bool,
14253        cx: &mut ViewContext<Self>,
14254    ) -> Option<UTF16Selection> {
14255        // Prevent the IME menu from appearing when holding down an alphabetic key
14256        // while input is disabled.
14257        if !ignore_disabled_input && !self.input_enabled {
14258            return None;
14259        }
14260
14261        let selection = self.selections.newest::<OffsetUtf16>(cx);
14262        let range = selection.range();
14263
14264        Some(UTF16Selection {
14265            range: range.start.0..range.end.0,
14266            reversed: selection.reversed,
14267        })
14268    }
14269
14270    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14271        let snapshot = self.buffer.read(cx).read(cx);
14272        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14273        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14274    }
14275
14276    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14277        self.clear_highlights::<InputComposition>(cx);
14278        self.ime_transaction.take();
14279    }
14280
14281    fn replace_text_in_range(
14282        &mut self,
14283        range_utf16: Option<Range<usize>>,
14284        text: &str,
14285        cx: &mut ViewContext<Self>,
14286    ) {
14287        if !self.input_enabled {
14288            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14289            return;
14290        }
14291
14292        self.transact(cx, |this, cx| {
14293            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14294                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14295                Some(this.selection_replacement_ranges(range_utf16, cx))
14296            } else {
14297                this.marked_text_ranges(cx)
14298            };
14299
14300            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14301                let newest_selection_id = this.selections.newest_anchor().id;
14302                this.selections
14303                    .all::<OffsetUtf16>(cx)
14304                    .iter()
14305                    .zip(ranges_to_replace.iter())
14306                    .find_map(|(selection, range)| {
14307                        if selection.id == newest_selection_id {
14308                            Some(
14309                                (range.start.0 as isize - selection.head().0 as isize)
14310                                    ..(range.end.0 as isize - selection.head().0 as isize),
14311                            )
14312                        } else {
14313                            None
14314                        }
14315                    })
14316            });
14317
14318            cx.emit(EditorEvent::InputHandled {
14319                utf16_range_to_replace: range_to_replace,
14320                text: text.into(),
14321            });
14322
14323            if let Some(new_selected_ranges) = new_selected_ranges {
14324                this.change_selections(None, cx, |selections| {
14325                    selections.select_ranges(new_selected_ranges)
14326                });
14327                this.backspace(&Default::default(), cx);
14328            }
14329
14330            this.handle_input(text, cx);
14331        });
14332
14333        if let Some(transaction) = self.ime_transaction {
14334            self.buffer.update(cx, |buffer, cx| {
14335                buffer.group_until_transaction(transaction, cx);
14336            });
14337        }
14338
14339        self.unmark_text(cx);
14340    }
14341
14342    fn replace_and_mark_text_in_range(
14343        &mut self,
14344        range_utf16: Option<Range<usize>>,
14345        text: &str,
14346        new_selected_range_utf16: Option<Range<usize>>,
14347        cx: &mut ViewContext<Self>,
14348    ) {
14349        if !self.input_enabled {
14350            return;
14351        }
14352
14353        let transaction = self.transact(cx, |this, cx| {
14354            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14355                let snapshot = this.buffer.read(cx).read(cx);
14356                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14357                    for marked_range in &mut marked_ranges {
14358                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14359                        marked_range.start.0 += relative_range_utf16.start;
14360                        marked_range.start =
14361                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14362                        marked_range.end =
14363                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14364                    }
14365                }
14366                Some(marked_ranges)
14367            } else if let Some(range_utf16) = range_utf16 {
14368                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14369                Some(this.selection_replacement_ranges(range_utf16, cx))
14370            } else {
14371                None
14372            };
14373
14374            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14375                let newest_selection_id = this.selections.newest_anchor().id;
14376                this.selections
14377                    .all::<OffsetUtf16>(cx)
14378                    .iter()
14379                    .zip(ranges_to_replace.iter())
14380                    .find_map(|(selection, range)| {
14381                        if selection.id == newest_selection_id {
14382                            Some(
14383                                (range.start.0 as isize - selection.head().0 as isize)
14384                                    ..(range.end.0 as isize - selection.head().0 as isize),
14385                            )
14386                        } else {
14387                            None
14388                        }
14389                    })
14390            });
14391
14392            cx.emit(EditorEvent::InputHandled {
14393                utf16_range_to_replace: range_to_replace,
14394                text: text.into(),
14395            });
14396
14397            if let Some(ranges) = ranges_to_replace {
14398                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14399            }
14400
14401            let marked_ranges = {
14402                let snapshot = this.buffer.read(cx).read(cx);
14403                this.selections
14404                    .disjoint_anchors()
14405                    .iter()
14406                    .map(|selection| {
14407                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14408                    })
14409                    .collect::<Vec<_>>()
14410            };
14411
14412            if text.is_empty() {
14413                this.unmark_text(cx);
14414            } else {
14415                this.highlight_text::<InputComposition>(
14416                    marked_ranges.clone(),
14417                    HighlightStyle {
14418                        underline: Some(UnderlineStyle {
14419                            thickness: px(1.),
14420                            color: None,
14421                            wavy: false,
14422                        }),
14423                        ..Default::default()
14424                    },
14425                    cx,
14426                );
14427            }
14428
14429            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14430            let use_autoclose = this.use_autoclose;
14431            let use_auto_surround = this.use_auto_surround;
14432            this.set_use_autoclose(false);
14433            this.set_use_auto_surround(false);
14434            this.handle_input(text, cx);
14435            this.set_use_autoclose(use_autoclose);
14436            this.set_use_auto_surround(use_auto_surround);
14437
14438            if let Some(new_selected_range) = new_selected_range_utf16 {
14439                let snapshot = this.buffer.read(cx).read(cx);
14440                let new_selected_ranges = marked_ranges
14441                    .into_iter()
14442                    .map(|marked_range| {
14443                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14444                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14445                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14446                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14447                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14448                    })
14449                    .collect::<Vec<_>>();
14450
14451                drop(snapshot);
14452                this.change_selections(None, cx, |selections| {
14453                    selections.select_ranges(new_selected_ranges)
14454                });
14455            }
14456        });
14457
14458        self.ime_transaction = self.ime_transaction.or(transaction);
14459        if let Some(transaction) = self.ime_transaction {
14460            self.buffer.update(cx, |buffer, cx| {
14461                buffer.group_until_transaction(transaction, cx);
14462            });
14463        }
14464
14465        if self.text_highlights::<InputComposition>(cx).is_none() {
14466            self.ime_transaction.take();
14467        }
14468    }
14469
14470    fn bounds_for_range(
14471        &mut self,
14472        range_utf16: Range<usize>,
14473        element_bounds: gpui::Bounds<Pixels>,
14474        cx: &mut ViewContext<Self>,
14475    ) -> Option<gpui::Bounds<Pixels>> {
14476        let text_layout_details = self.text_layout_details(cx);
14477        let style = &text_layout_details.editor_style;
14478        let font_id = cx.text_system().resolve_font(&style.text.font());
14479        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14480        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14481
14482        let em_width = cx
14483            .text_system()
14484            .typographic_bounds(font_id, font_size, 'm')
14485            .unwrap()
14486            .size
14487            .width;
14488
14489        let snapshot = self.snapshot(cx);
14490        let scroll_position = snapshot.scroll_position();
14491        let scroll_left = scroll_position.x * em_width;
14492
14493        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14494        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14495            + self.gutter_dimensions.width;
14496        let y = line_height * (start.row().as_f32() - scroll_position.y);
14497
14498        Some(Bounds {
14499            origin: element_bounds.origin + point(x, y),
14500            size: size(em_width, line_height),
14501        })
14502    }
14503}
14504
14505trait SelectionExt {
14506    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14507    fn spanned_rows(
14508        &self,
14509        include_end_if_at_line_start: bool,
14510        map: &DisplaySnapshot,
14511    ) -> Range<MultiBufferRow>;
14512}
14513
14514impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14515    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14516        let start = self
14517            .start
14518            .to_point(&map.buffer_snapshot)
14519            .to_display_point(map);
14520        let end = self
14521            .end
14522            .to_point(&map.buffer_snapshot)
14523            .to_display_point(map);
14524        if self.reversed {
14525            end..start
14526        } else {
14527            start..end
14528        }
14529    }
14530
14531    fn spanned_rows(
14532        &self,
14533        include_end_if_at_line_start: bool,
14534        map: &DisplaySnapshot,
14535    ) -> Range<MultiBufferRow> {
14536        let start = self.start.to_point(&map.buffer_snapshot);
14537        let mut end = self.end.to_point(&map.buffer_snapshot);
14538        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14539            end.row -= 1;
14540        }
14541
14542        let buffer_start = map.prev_line_boundary(start).0;
14543        let buffer_end = map.next_line_boundary(end).0;
14544        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14545    }
14546}
14547
14548impl<T: InvalidationRegion> InvalidationStack<T> {
14549    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14550    where
14551        S: Clone + ToOffset,
14552    {
14553        while let Some(region) = self.last() {
14554            let all_selections_inside_invalidation_ranges =
14555                if selections.len() == region.ranges().len() {
14556                    selections
14557                        .iter()
14558                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14559                        .all(|(selection, invalidation_range)| {
14560                            let head = selection.head().to_offset(buffer);
14561                            invalidation_range.start <= head && invalidation_range.end >= head
14562                        })
14563                } else {
14564                    false
14565                };
14566
14567            if all_selections_inside_invalidation_ranges {
14568                break;
14569            } else {
14570                self.pop();
14571            }
14572        }
14573    }
14574}
14575
14576impl<T> Default for InvalidationStack<T> {
14577    fn default() -> Self {
14578        Self(Default::default())
14579    }
14580}
14581
14582impl<T> Deref for InvalidationStack<T> {
14583    type Target = Vec<T>;
14584
14585    fn deref(&self) -> &Self::Target {
14586        &self.0
14587    }
14588}
14589
14590impl<T> DerefMut for InvalidationStack<T> {
14591    fn deref_mut(&mut self) -> &mut Self::Target {
14592        &mut self.0
14593    }
14594}
14595
14596impl InvalidationRegion for SnippetState {
14597    fn ranges(&self) -> &[Range<Anchor>] {
14598        &self.ranges[self.active_index]
14599    }
14600}
14601
14602pub fn diagnostic_block_renderer(
14603    diagnostic: Diagnostic,
14604    max_message_rows: Option<u8>,
14605    allow_closing: bool,
14606    _is_valid: bool,
14607) -> RenderBlock {
14608    let (text_without_backticks, code_ranges) =
14609        highlight_diagnostic_message(&diagnostic, max_message_rows);
14610
14611    Box::new(move |cx: &mut BlockContext| {
14612        let group_id: SharedString = cx.block_id.to_string().into();
14613
14614        let mut text_style = cx.text_style().clone();
14615        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14616        let theme_settings = ThemeSettings::get_global(cx);
14617        text_style.font_family = theme_settings.buffer_font.family.clone();
14618        text_style.font_style = theme_settings.buffer_font.style;
14619        text_style.font_features = theme_settings.buffer_font.features.clone();
14620        text_style.font_weight = theme_settings.buffer_font.weight;
14621
14622        let multi_line_diagnostic = diagnostic.message.contains('\n');
14623
14624        let buttons = |diagnostic: &Diagnostic| {
14625            if multi_line_diagnostic {
14626                v_flex()
14627            } else {
14628                h_flex()
14629            }
14630            .when(allow_closing, |div| {
14631                div.children(diagnostic.is_primary.then(|| {
14632                    IconButton::new("close-block", IconName::XCircle)
14633                        .icon_color(Color::Muted)
14634                        .size(ButtonSize::Compact)
14635                        .style(ButtonStyle::Transparent)
14636                        .visible_on_hover(group_id.clone())
14637                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14638                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14639                }))
14640            })
14641            .child(
14642                IconButton::new("copy-block", IconName::Copy)
14643                    .icon_color(Color::Muted)
14644                    .size(ButtonSize::Compact)
14645                    .style(ButtonStyle::Transparent)
14646                    .visible_on_hover(group_id.clone())
14647                    .on_click({
14648                        let message = diagnostic.message.clone();
14649                        move |_click, cx| {
14650                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14651                        }
14652                    })
14653                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14654            )
14655        };
14656
14657        let icon_size = buttons(&diagnostic)
14658            .into_any_element()
14659            .layout_as_root(AvailableSpace::min_size(), cx);
14660
14661        h_flex()
14662            .id(cx.block_id)
14663            .group(group_id.clone())
14664            .relative()
14665            .size_full()
14666            .pl(cx.gutter_dimensions.width)
14667            .w(cx.max_width - cx.gutter_dimensions.full_width())
14668            .child(
14669                div()
14670                    .flex()
14671                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14672                    .flex_shrink(),
14673            )
14674            .child(buttons(&diagnostic))
14675            .child(div().flex().flex_shrink_0().child(
14676                StyledText::new(text_without_backticks.clone()).with_highlights(
14677                    &text_style,
14678                    code_ranges.iter().map(|range| {
14679                        (
14680                            range.clone(),
14681                            HighlightStyle {
14682                                font_weight: Some(FontWeight::BOLD),
14683                                ..Default::default()
14684                            },
14685                        )
14686                    }),
14687                ),
14688            ))
14689            .into_any_element()
14690    })
14691}
14692
14693pub fn highlight_diagnostic_message(
14694    diagnostic: &Diagnostic,
14695    mut max_message_rows: Option<u8>,
14696) -> (SharedString, Vec<Range<usize>>) {
14697    let mut text_without_backticks = String::new();
14698    let mut code_ranges = Vec::new();
14699
14700    if let Some(source) = &diagnostic.source {
14701        text_without_backticks.push_str(source);
14702        code_ranges.push(0..source.len());
14703        text_without_backticks.push_str(": ");
14704    }
14705
14706    let mut prev_offset = 0;
14707    let mut in_code_block = false;
14708    let has_row_limit = max_message_rows.is_some();
14709    let mut newline_indices = diagnostic
14710        .message
14711        .match_indices('\n')
14712        .filter(|_| has_row_limit)
14713        .map(|(ix, _)| ix)
14714        .fuse()
14715        .peekable();
14716
14717    for (quote_ix, _) in diagnostic
14718        .message
14719        .match_indices('`')
14720        .chain([(diagnostic.message.len(), "")])
14721    {
14722        let mut first_newline_ix = None;
14723        let mut last_newline_ix = None;
14724        while let Some(newline_ix) = newline_indices.peek() {
14725            if *newline_ix < quote_ix {
14726                if first_newline_ix.is_none() {
14727                    first_newline_ix = Some(*newline_ix);
14728                }
14729                last_newline_ix = Some(*newline_ix);
14730
14731                if let Some(rows_left) = &mut max_message_rows {
14732                    if *rows_left == 0 {
14733                        break;
14734                    } else {
14735                        *rows_left -= 1;
14736                    }
14737                }
14738                let _ = newline_indices.next();
14739            } else {
14740                break;
14741            }
14742        }
14743        let prev_len = text_without_backticks.len();
14744        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14745        text_without_backticks.push_str(new_text);
14746        if in_code_block {
14747            code_ranges.push(prev_len..text_without_backticks.len());
14748        }
14749        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14750        in_code_block = !in_code_block;
14751        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14752            text_without_backticks.push_str("...");
14753            break;
14754        }
14755    }
14756
14757    (text_without_backticks.into(), code_ranges)
14758}
14759
14760fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14761    match severity {
14762        DiagnosticSeverity::ERROR => colors.error,
14763        DiagnosticSeverity::WARNING => colors.warning,
14764        DiagnosticSeverity::INFORMATION => colors.info,
14765        DiagnosticSeverity::HINT => colors.info,
14766        _ => colors.ignored,
14767    }
14768}
14769
14770pub fn styled_runs_for_code_label<'a>(
14771    label: &'a CodeLabel,
14772    syntax_theme: &'a theme::SyntaxTheme,
14773) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14774    let fade_out = HighlightStyle {
14775        fade_out: Some(0.35),
14776        ..Default::default()
14777    };
14778
14779    let mut prev_end = label.filter_range.end;
14780    label
14781        .runs
14782        .iter()
14783        .enumerate()
14784        .flat_map(move |(ix, (range, highlight_id))| {
14785            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14786                style
14787            } else {
14788                return Default::default();
14789            };
14790            let mut muted_style = style;
14791            muted_style.highlight(fade_out);
14792
14793            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14794            if range.start >= label.filter_range.end {
14795                if range.start > prev_end {
14796                    runs.push((prev_end..range.start, fade_out));
14797                }
14798                runs.push((range.clone(), muted_style));
14799            } else if range.end <= label.filter_range.end {
14800                runs.push((range.clone(), style));
14801            } else {
14802                runs.push((range.start..label.filter_range.end, style));
14803                runs.push((label.filter_range.end..range.end, muted_style));
14804            }
14805            prev_end = cmp::max(prev_end, range.end);
14806
14807            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14808                runs.push((prev_end..label.text.len(), fade_out));
14809            }
14810
14811            runs
14812        })
14813}
14814
14815pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14816    let mut prev_index = 0;
14817    let mut prev_codepoint: Option<char> = None;
14818    text.char_indices()
14819        .chain([(text.len(), '\0')])
14820        .filter_map(move |(index, codepoint)| {
14821            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14822            let is_boundary = index == text.len()
14823                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14824                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14825            if is_boundary {
14826                let chunk = &text[prev_index..index];
14827                prev_index = index;
14828                Some(chunk)
14829            } else {
14830                None
14831            }
14832        })
14833}
14834
14835pub trait RangeToAnchorExt: Sized {
14836    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14837
14838    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14839        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14840        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14841    }
14842}
14843
14844impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14845    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14846        let start_offset = self.start.to_offset(snapshot);
14847        let end_offset = self.end.to_offset(snapshot);
14848        if start_offset == end_offset {
14849            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14850        } else {
14851            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14852        }
14853    }
14854}
14855
14856pub trait RowExt {
14857    fn as_f32(&self) -> f32;
14858
14859    fn next_row(&self) -> Self;
14860
14861    fn previous_row(&self) -> Self;
14862
14863    fn minus(&self, other: Self) -> u32;
14864}
14865
14866impl RowExt for DisplayRow {
14867    fn as_f32(&self) -> f32 {
14868        self.0 as f32
14869    }
14870
14871    fn next_row(&self) -> Self {
14872        Self(self.0 + 1)
14873    }
14874
14875    fn previous_row(&self) -> Self {
14876        Self(self.0.saturating_sub(1))
14877    }
14878
14879    fn minus(&self, other: Self) -> u32 {
14880        self.0 - other.0
14881    }
14882}
14883
14884impl RowExt for MultiBufferRow {
14885    fn as_f32(&self) -> f32 {
14886        self.0 as f32
14887    }
14888
14889    fn next_row(&self) -> Self {
14890        Self(self.0 + 1)
14891    }
14892
14893    fn previous_row(&self) -> Self {
14894        Self(self.0.saturating_sub(1))
14895    }
14896
14897    fn minus(&self, other: Self) -> u32 {
14898        self.0 - other.0
14899    }
14900}
14901
14902trait RowRangeExt {
14903    type Row;
14904
14905    fn len(&self) -> usize;
14906
14907    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14908}
14909
14910impl RowRangeExt for Range<MultiBufferRow> {
14911    type Row = MultiBufferRow;
14912
14913    fn len(&self) -> usize {
14914        (self.end.0 - self.start.0) as usize
14915    }
14916
14917    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14918        (self.start.0..self.end.0).map(MultiBufferRow)
14919    }
14920}
14921
14922impl RowRangeExt for Range<DisplayRow> {
14923    type Row = DisplayRow;
14924
14925    fn len(&self) -> usize {
14926        (self.end.0 - self.start.0) as usize
14927    }
14928
14929    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14930        (self.start.0..self.end.0).map(DisplayRow)
14931    }
14932}
14933
14934fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14935    if hunk.diff_base_byte_range.is_empty() {
14936        DiffHunkStatus::Added
14937    } else if hunk.row_range.is_empty() {
14938        DiffHunkStatus::Removed
14939    } else {
14940        DiffHunkStatus::Modified
14941    }
14942}
14943
14944/// If select range has more than one line, we
14945/// just point the cursor to range.start.
14946fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14947    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14948        range
14949    } else {
14950        range.start..range.start
14951    }
14952}
14953
14954const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);