editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod debounced_delay;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31mod inline_completion_provider;
   32pub mod items;
   33mod linked_editing_ranges;
   34mod lsp_ext;
   35mod mouse_context_menu;
   36pub mod movement;
   37mod persistence;
   38mod proposed_changes_editor;
   39mod rust_analyzer_ext;
   40pub mod scroll;
   41mod selections_collection;
   42pub mod tasks;
   43
   44#[cfg(test)]
   45mod editor_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50use ::git::diff::DiffHunkStatus;
   51pub(crate) use actions::*;
   52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use debounced_delay::DebouncedDelay;
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::{StringMatch, StringMatchCandidate};
   73use git::blame::GitBlame;
   74use gpui::{
   75    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   76    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   77    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   78    FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   79    ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   80    ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
   81    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   82    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   83};
   84use highlight_matching_bracket::refresh_matching_bracket_highlights;
   85use hover_popover::{hide_hover, HoverState};
   86pub(crate) use hunk_diff::HoveredHunk;
   87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   88use indent_guides::ActiveIndentGuidesState;
   89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   90pub use inline_completion_provider::*;
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  100use linked_editing_ranges::refresh_linked_ranges;
  101pub use proposed_changes_editor::{
  102    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  103};
  104use similar::{ChangeTag, TextDiff};
  105use std::iter::Peekable;
  106use task::{ResolvedTask, TaskTemplate, TaskVariables};
  107
  108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  109pub use lsp::CompletionContext;
  110use lsp::{
  111    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  112    LanguageServerId, LanguageServerName,
  113};
  114use mouse_context_menu::MouseContextMenu;
  115use movement::TextLayoutDetails;
  116pub use multi_buffer::{
  117    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  118    ToPoint,
  119};
  120use multi_buffer::{
  121    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  122};
  123use ordered_float::OrderedFloat;
  124use parking_lot::{Mutex, RwLock};
  125use project::{
  126    lsp_store::{FormatTarget, FormatTrigger},
  127    project_settings::{GitGutterSetting, ProjectSettings},
  128    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  129    LocationLink, Project, ProjectTransaction, TaskSourceKind,
  130};
  131use rand::prelude::*;
  132use rpc::{proto::*, ErrorExt};
  133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  134use selections_collection::{
  135    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  136};
  137use serde::{Deserialize, Serialize};
  138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  139use smallvec::SmallVec;
  140use snippet::Snippet;
  141use std::{
  142    any::TypeId,
  143    borrow::Cow,
  144    cell::RefCell,
  145    cmp::{self, Ordering, Reverse},
  146    mem,
  147    num::NonZeroU32,
  148    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  149    path::{Path, PathBuf},
  150    rc::Rc,
  151    sync::Arc,
  152    time::{Duration, Instant},
  153};
  154pub use sum_tree::Bias;
  155use sum_tree::TreeMap;
  156use text::{BufferId, OffsetUtf16, Rope};
  157use theme::{
  158    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  159    ThemeColors, ThemeSettings,
  160};
  161use ui::{
  162    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  163    ListItem, Popover, PopoverMenuHandle, Tooltip,
  164};
  165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  166use workspace::item::{ItemHandle, PreviewTabsSettings};
  167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  168use workspace::{
  169    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  170};
  171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  172
  173use crate::hover_links::find_url;
  174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  175
  176pub const FILE_HEADER_HEIGHT: u32 = 2;
  177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  181const MAX_LINE_LEN: usize = 1024;
  182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  185#[doc(hidden)]
  186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  187#[doc(hidden)]
  188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub fn render_parsed_markdown(
  194    element_id: impl Into<ElementId>,
  195    parsed: &language::ParsedMarkdown,
  196    editor_style: &EditorStyle,
  197    workspace: Option<WeakView<Workspace>>,
  198    cx: &mut WindowContext,
  199) -> InteractiveText {
  200    let code_span_background_color = cx
  201        .theme()
  202        .colors()
  203        .editor_document_highlight_read_background;
  204
  205    let highlights = gpui::combine_highlights(
  206        parsed.highlights.iter().filter_map(|(range, highlight)| {
  207            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  208            Some((range.clone(), highlight))
  209        }),
  210        parsed
  211            .regions
  212            .iter()
  213            .zip(&parsed.region_ranges)
  214            .filter_map(|(region, range)| {
  215                if region.code {
  216                    Some((
  217                        range.clone(),
  218                        HighlightStyle {
  219                            background_color: Some(code_span_background_color),
  220                            ..Default::default()
  221                        },
  222                    ))
  223                } else {
  224                    None
  225                }
  226            }),
  227    );
  228
  229    let mut links = Vec::new();
  230    let mut link_ranges = Vec::new();
  231    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  232        if let Some(link) = region.link.clone() {
  233            links.push(link);
  234            link_ranges.push(range.clone());
  235        }
  236    }
  237
  238    InteractiveText::new(
  239        element_id,
  240        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  241    )
  242    .on_click(link_ranges, move |clicked_range_ix, cx| {
  243        match &links[clicked_range_ix] {
  244            markdown::Link::Web { url } => cx.open_url(url),
  245            markdown::Link::Path { path } => {
  246                if let Some(workspace) = &workspace {
  247                    _ = workspace.update(cx, |workspace, cx| {
  248                        workspace.open_abs_path(path.clone(), false, cx).detach();
  249                    });
  250                }
  251            }
  252        }
  253    })
  254}
  255
  256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  257pub(crate) enum InlayId {
  258    Suggestion(usize),
  259    Hint(usize),
  260}
  261
  262impl InlayId {
  263    fn id(&self) -> usize {
  264        match self {
  265            Self::Suggestion(id) => *id,
  266            Self::Hint(id) => *id,
  267        }
  268    }
  269}
  270
  271enum DiffRowHighlight {}
  272enum DocumentHighlightRead {}
  273enum DocumentHighlightWrite {}
  274enum InputComposition {}
  275
  276#[derive(Copy, Clone, PartialEq, Eq)]
  277pub enum Direction {
  278    Prev,
  279    Next,
  280}
  281
  282#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  283pub enum Navigated {
  284    Yes,
  285    No,
  286}
  287
  288impl Navigated {
  289    pub fn from_bool(yes: bool) -> Navigated {
  290        if yes {
  291            Navigated::Yes
  292        } else {
  293            Navigated::No
  294        }
  295    }
  296}
  297
  298pub fn init_settings(cx: &mut AppContext) {
  299    EditorSettings::register(cx);
  300}
  301
  302pub fn init(cx: &mut AppContext) {
  303    init_settings(cx);
  304
  305    workspace::register_project_item::<Editor>(cx);
  306    workspace::FollowableViewRegistry::register::<Editor>(cx);
  307    workspace::register_serializable_item::<Editor>(cx);
  308
  309    cx.observe_new_views(
  310        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  311            workspace.register_action(Editor::new_file);
  312            workspace.register_action(Editor::new_file_vertical);
  313            workspace.register_action(Editor::new_file_horizontal);
  314        },
  315    )
  316    .detach();
  317
  318    cx.on_action(move |_: &workspace::NewFile, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  322                Editor::new_file(workspace, &Default::default(), cx)
  323            })
  324            .detach();
  325        }
  326    });
  327    cx.on_action(move |_: &workspace::NewWindow, cx| {
  328        let app_state = workspace::AppState::global(cx);
  329        if let Some(app_state) = app_state.upgrade() {
  330            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  331                Editor::new_file(workspace, &Default::default(), cx)
  332            })
  333            .detach();
  334        }
  335    });
  336}
  337
  338pub struct SearchWithinRange;
  339
  340trait InvalidationRegion {
  341    fn ranges(&self) -> &[Range<Anchor>];
  342}
  343
  344#[derive(Clone, Debug, PartialEq)]
  345pub enum SelectPhase {
  346    Begin {
  347        position: DisplayPoint,
  348        add: bool,
  349        click_count: usize,
  350    },
  351    BeginColumnar {
  352        position: DisplayPoint,
  353        reset: bool,
  354        goal_column: u32,
  355    },
  356    Extend {
  357        position: DisplayPoint,
  358        click_count: usize,
  359    },
  360    Update {
  361        position: DisplayPoint,
  362        goal_column: u32,
  363        scroll_delta: gpui::Point<f32>,
  364    },
  365    End,
  366}
  367
  368#[derive(Clone, Debug)]
  369pub enum SelectMode {
  370    Character,
  371    Word(Range<Anchor>),
  372    Line(Range<Anchor>),
  373    All,
  374}
  375
  376#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  377pub enum EditorMode {
  378    SingleLine { auto_width: bool },
  379    AutoHeight { max_lines: usize },
  380    Full,
  381}
  382
  383#[derive(Copy, Clone, Debug)]
  384pub enum SoftWrap {
  385    /// Prefer not to wrap at all.
  386    ///
  387    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  388    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  389    GitDiff,
  390    /// Prefer a single line generally, unless an overly long line is encountered.
  391    None,
  392    /// Soft wrap lines that exceed the editor width.
  393    EditorWidth,
  394    /// Soft wrap lines at the preferred line length.
  395    Column(u32),
  396    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  397    Bounded(u32),
  398}
  399
  400#[derive(Clone)]
  401pub struct EditorStyle {
  402    pub background: Hsla,
  403    pub local_player: PlayerColor,
  404    pub text: TextStyle,
  405    pub scrollbar_width: Pixels,
  406    pub syntax: Arc<SyntaxTheme>,
  407    pub status: StatusColors,
  408    pub inlay_hints_style: HighlightStyle,
  409    pub suggestions_style: HighlightStyle,
  410    pub unnecessary_code_fade: f32,
  411}
  412
  413impl Default for EditorStyle {
  414    fn default() -> Self {
  415        Self {
  416            background: Hsla::default(),
  417            local_player: PlayerColor::default(),
  418            text: TextStyle::default(),
  419            scrollbar_width: Pixels::default(),
  420            syntax: Default::default(),
  421            // HACK: Status colors don't have a real default.
  422            // We should look into removing the status colors from the editor
  423            // style and retrieve them directly from the theme.
  424            status: StatusColors::dark(),
  425            inlay_hints_style: HighlightStyle::default(),
  426            suggestions_style: HighlightStyle::default(),
  427            unnecessary_code_fade: Default::default(),
  428        }
  429    }
  430}
  431
  432pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  433    let show_background = language_settings::language_settings(None, None, cx)
  434        .inlay_hints
  435        .show_background;
  436
  437    HighlightStyle {
  438        color: Some(cx.theme().status().hint),
  439        background_color: show_background.then(|| cx.theme().status().hint_background),
  440        ..HighlightStyle::default()
  441    }
  442}
  443
  444type CompletionId = usize;
  445
  446#[derive(Clone, Debug)]
  447struct CompletionState {
  448    // render_inlay_ids represents the inlay hints that are inserted
  449    // for rendering the inline completions. They may be discontinuous
  450    // in the event that the completion provider returns some intersection
  451    // with the existing content.
  452    render_inlay_ids: Vec<InlayId>,
  453    // text is the resulting rope that is inserted when the user accepts a completion.
  454    text: Rope,
  455    // position is the position of the cursor when the completion was triggered.
  456    position: multi_buffer::Anchor,
  457    // delete_range is the range of text that this completion state covers.
  458    // if the completion is accepted, this range should be deleted.
  459    delete_range: Option<Range<multi_buffer::Anchor>>,
  460}
  461
  462#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  463struct EditorActionId(usize);
  464
  465impl EditorActionId {
  466    pub fn post_inc(&mut self) -> Self {
  467        let answer = self.0;
  468
  469        *self = Self(answer + 1);
  470
  471        Self(answer)
  472    }
  473}
  474
  475// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  476// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  477
  478type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  479type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  480
  481#[derive(Default)]
  482struct ScrollbarMarkerState {
  483    scrollbar_size: Size<Pixels>,
  484    dirty: bool,
  485    markers: Arc<[PaintQuad]>,
  486    pending_refresh: Option<Task<Result<()>>>,
  487}
  488
  489impl ScrollbarMarkerState {
  490    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  491        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  492    }
  493}
  494
  495#[derive(Clone, Debug)]
  496struct RunnableTasks {
  497    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  498    offset: MultiBufferOffset,
  499    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  500    column: u32,
  501    // Values of all named captures, including those starting with '_'
  502    extra_variables: HashMap<String, String>,
  503    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  504    context_range: Range<BufferOffset>,
  505}
  506
  507impl RunnableTasks {
  508    fn resolve<'a>(
  509        &'a self,
  510        cx: &'a task::TaskContext,
  511    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  512        self.templates.iter().filter_map(|(kind, template)| {
  513            template
  514                .resolve_task(&kind.to_id_base(), cx)
  515                .map(|task| (kind.clone(), task))
  516        })
  517    }
  518}
  519
  520#[derive(Clone)]
  521struct ResolvedTasks {
  522    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  523    position: Anchor,
  524}
  525#[derive(Copy, Clone, Debug)]
  526struct MultiBufferOffset(usize);
  527#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  528struct BufferOffset(usize);
  529
  530// Addons allow storing per-editor state in other crates (e.g. Vim)
  531pub trait Addon: 'static {
  532    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  533
  534    fn to_any(&self) -> &dyn std::any::Any;
  535}
  536
  537#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  538pub enum IsVimMode {
  539    Yes,
  540    No,
  541}
  542
  543pub trait ActiveLineTrailerProvider {
  544    fn render_active_line_trailer(
  545        &mut self,
  546        style: &EditorStyle,
  547        focus_handle: &FocusHandle,
  548        cx: &mut WindowContext,
  549    ) -> Option<AnyElement>;
  550}
  551
  552/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  553///
  554/// See the [module level documentation](self) for more information.
  555pub struct Editor {
  556    focus_handle: FocusHandle,
  557    last_focused_descendant: Option<WeakFocusHandle>,
  558    /// The text buffer being edited
  559    buffer: Model<MultiBuffer>,
  560    /// Map of how text in the buffer should be displayed.
  561    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  562    pub display_map: Model<DisplayMap>,
  563    pub selections: SelectionsCollection,
  564    pub scroll_manager: ScrollManager,
  565    /// When inline assist editors are linked, they all render cursors because
  566    /// typing enters text into each of them, even the ones that aren't focused.
  567    pub(crate) show_cursor_when_unfocused: bool,
  568    columnar_selection_tail: Option<Anchor>,
  569    add_selections_state: Option<AddSelectionsState>,
  570    select_next_state: Option<SelectNextState>,
  571    select_prev_state: Option<SelectNextState>,
  572    selection_history: SelectionHistory,
  573    autoclose_regions: Vec<AutocloseRegion>,
  574    snippet_stack: InvalidationStack<SnippetState>,
  575    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  576    ime_transaction: Option<TransactionId>,
  577    active_diagnostics: Option<ActiveDiagnosticGroup>,
  578    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  579
  580    project: Option<Model<Project>>,
  581    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  582    completion_provider: Option<Box<dyn CompletionProvider>>,
  583    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  584    blink_manager: Model<BlinkManager>,
  585    show_cursor_names: bool,
  586    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  587    pub show_local_selections: bool,
  588    mode: EditorMode,
  589    show_breadcrumbs: bool,
  590    show_gutter: bool,
  591    show_line_numbers: Option<bool>,
  592    use_relative_line_numbers: Option<bool>,
  593    show_git_diff_gutter: Option<bool>,
  594    show_code_actions: Option<bool>,
  595    show_runnables: Option<bool>,
  596    show_wrap_guides: Option<bool>,
  597    show_indent_guides: Option<bool>,
  598    placeholder_text: Option<Arc<str>>,
  599    highlight_order: usize,
  600    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  601    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  602    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  603    scrollbar_marker_state: ScrollbarMarkerState,
  604    active_indent_guides_state: ActiveIndentGuidesState,
  605    nav_history: Option<ItemNavHistory>,
  606    context_menu: RwLock<Option<ContextMenu>>,
  607    mouse_context_menu: Option<MouseContextMenu>,
  608    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  609    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  610    signature_help_state: SignatureHelpState,
  611    auto_signature_help: Option<bool>,
  612    find_all_references_task_sources: Vec<Anchor>,
  613    next_completion_id: CompletionId,
  614    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  615    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  616    code_actions_task: Option<Task<Result<()>>>,
  617    document_highlights_task: Option<Task<()>>,
  618    linked_editing_range_task: Option<Task<Option<()>>>,
  619    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  620    pending_rename: Option<RenameState>,
  621    searchable: bool,
  622    cursor_shape: CursorShape,
  623    current_line_highlight: Option<CurrentLineHighlight>,
  624    collapse_matches: bool,
  625    autoindent_mode: Option<AutoindentMode>,
  626    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  627    input_enabled: bool,
  628    use_modal_editing: bool,
  629    read_only: bool,
  630    leader_peer_id: Option<PeerId>,
  631    remote_id: Option<ViewId>,
  632    hover_state: HoverState,
  633    gutter_hovered: bool,
  634    hovered_link_state: Option<HoveredLinkState>,
  635    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  636    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  637    active_inline_completion: Option<CompletionState>,
  638    // enable_inline_completions is a switch that Vim can use to disable
  639    // inline completions based on its mode.
  640    enable_inline_completions: bool,
  641    show_inline_completions_override: Option<bool>,
  642    inlay_hint_cache: InlayHintCache,
  643    expanded_hunks: ExpandedHunks,
  644    next_inlay_id: usize,
  645    _subscriptions: Vec<Subscription>,
  646    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  647    gutter_dimensions: GutterDimensions,
  648    style: Option<EditorStyle>,
  649    text_style_refinement: Option<TextStyleRefinement>,
  650    next_editor_action_id: EditorActionId,
  651    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  652    use_autoclose: bool,
  653    use_auto_surround: bool,
  654    auto_replace_emoji_shortcode: bool,
  655    show_git_blame_gutter: bool,
  656    show_git_blame_inline: bool,
  657    show_git_blame_inline_delay_task: Option<Task<()>>,
  658    git_blame_inline_enabled: bool,
  659    serialize_dirty_buffers: bool,
  660    show_selection_menu: Option<bool>,
  661    blame: Option<Model<GitBlame>>,
  662    blame_subscription: Option<Subscription>,
  663    custom_context_menu: Option<
  664        Box<
  665            dyn 'static
  666                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  667        >,
  668    >,
  669    last_bounds: Option<Bounds<Pixels>>,
  670    expect_bounds_change: Option<Bounds<Pixels>>,
  671    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  672    tasks_update_task: Option<Task<()>>,
  673    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  674    breadcrumb_header: Option<String>,
  675    focused_block: Option<FocusedBlock>,
  676    next_scroll_position: NextScrollCursorCenterTopBottom,
  677    addons: HashMap<TypeId, Box<dyn Addon>>,
  678    _scroll_cursor_center_top_bottom_task: Task<()>,
  679    active_line_trailer_provider: Option<Box<dyn ActiveLineTrailerProvider>>,
  680}
  681
  682#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  683enum NextScrollCursorCenterTopBottom {
  684    #[default]
  685    Center,
  686    Top,
  687    Bottom,
  688}
  689
  690impl NextScrollCursorCenterTopBottom {
  691    fn next(&self) -> Self {
  692        match self {
  693            Self::Center => Self::Top,
  694            Self::Top => Self::Bottom,
  695            Self::Bottom => Self::Center,
  696        }
  697    }
  698}
  699
  700#[derive(Clone)]
  701pub struct EditorSnapshot {
  702    pub mode: EditorMode,
  703    show_gutter: bool,
  704    show_line_numbers: Option<bool>,
  705    show_git_diff_gutter: Option<bool>,
  706    show_code_actions: Option<bool>,
  707    show_runnables: Option<bool>,
  708    git_blame_gutter_max_author_length: Option<usize>,
  709    pub display_snapshot: DisplaySnapshot,
  710    pub placeholder_text: Option<Arc<str>>,
  711    is_focused: bool,
  712    scroll_anchor: ScrollAnchor,
  713    ongoing_scroll: OngoingScroll,
  714    current_line_highlight: CurrentLineHighlight,
  715    gutter_hovered: bool,
  716}
  717
  718const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  719
  720#[derive(Default, Debug, Clone, Copy)]
  721pub struct GutterDimensions {
  722    pub left_padding: Pixels,
  723    pub right_padding: Pixels,
  724    pub width: Pixels,
  725    pub margin: Pixels,
  726    pub git_blame_entries_width: Option<Pixels>,
  727}
  728
  729impl GutterDimensions {
  730    /// The full width of the space taken up by the gutter.
  731    pub fn full_width(&self) -> Pixels {
  732        self.margin + self.width
  733    }
  734
  735    /// The width of the space reserved for the fold indicators,
  736    /// use alongside 'justify_end' and `gutter_width` to
  737    /// right align content with the line numbers
  738    pub fn fold_area_width(&self) -> Pixels {
  739        self.margin + self.right_padding
  740    }
  741}
  742
  743#[derive(Debug)]
  744pub struct RemoteSelection {
  745    pub replica_id: ReplicaId,
  746    pub selection: Selection<Anchor>,
  747    pub cursor_shape: CursorShape,
  748    pub peer_id: PeerId,
  749    pub line_mode: bool,
  750    pub participant_index: Option<ParticipantIndex>,
  751    pub user_name: Option<SharedString>,
  752}
  753
  754#[derive(Clone, Debug)]
  755struct SelectionHistoryEntry {
  756    selections: Arc<[Selection<Anchor>]>,
  757    select_next_state: Option<SelectNextState>,
  758    select_prev_state: Option<SelectNextState>,
  759    add_selections_state: Option<AddSelectionsState>,
  760}
  761
  762enum SelectionHistoryMode {
  763    Normal,
  764    Undoing,
  765    Redoing,
  766}
  767
  768#[derive(Clone, PartialEq, Eq, Hash)]
  769struct HoveredCursor {
  770    replica_id: u16,
  771    selection_id: usize,
  772}
  773
  774impl Default for SelectionHistoryMode {
  775    fn default() -> Self {
  776        Self::Normal
  777    }
  778}
  779
  780#[derive(Default)]
  781struct SelectionHistory {
  782    #[allow(clippy::type_complexity)]
  783    selections_by_transaction:
  784        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  785    mode: SelectionHistoryMode,
  786    undo_stack: VecDeque<SelectionHistoryEntry>,
  787    redo_stack: VecDeque<SelectionHistoryEntry>,
  788}
  789
  790impl SelectionHistory {
  791    fn insert_transaction(
  792        &mut self,
  793        transaction_id: TransactionId,
  794        selections: Arc<[Selection<Anchor>]>,
  795    ) {
  796        self.selections_by_transaction
  797            .insert(transaction_id, (selections, None));
  798    }
  799
  800    #[allow(clippy::type_complexity)]
  801    fn transaction(
  802        &self,
  803        transaction_id: TransactionId,
  804    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  805        self.selections_by_transaction.get(&transaction_id)
  806    }
  807
  808    #[allow(clippy::type_complexity)]
  809    fn transaction_mut(
  810        &mut self,
  811        transaction_id: TransactionId,
  812    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  813        self.selections_by_transaction.get_mut(&transaction_id)
  814    }
  815
  816    fn push(&mut self, entry: SelectionHistoryEntry) {
  817        if !entry.selections.is_empty() {
  818            match self.mode {
  819                SelectionHistoryMode::Normal => {
  820                    self.push_undo(entry);
  821                    self.redo_stack.clear();
  822                }
  823                SelectionHistoryMode::Undoing => self.push_redo(entry),
  824                SelectionHistoryMode::Redoing => self.push_undo(entry),
  825            }
  826        }
  827    }
  828
  829    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  830        if self
  831            .undo_stack
  832            .back()
  833            .map_or(true, |e| e.selections != entry.selections)
  834        {
  835            self.undo_stack.push_back(entry);
  836            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  837                self.undo_stack.pop_front();
  838            }
  839        }
  840    }
  841
  842    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  843        if self
  844            .redo_stack
  845            .back()
  846            .map_or(true, |e| e.selections != entry.selections)
  847        {
  848            self.redo_stack.push_back(entry);
  849            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  850                self.redo_stack.pop_front();
  851            }
  852        }
  853    }
  854}
  855
  856struct RowHighlight {
  857    index: usize,
  858    range: Range<Anchor>,
  859    color: Hsla,
  860    should_autoscroll: bool,
  861}
  862
  863#[derive(Clone, Debug)]
  864struct AddSelectionsState {
  865    above: bool,
  866    stack: Vec<usize>,
  867}
  868
  869#[derive(Clone)]
  870struct SelectNextState {
  871    query: AhoCorasick,
  872    wordwise: bool,
  873    done: bool,
  874}
  875
  876impl std::fmt::Debug for SelectNextState {
  877    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  878        f.debug_struct(std::any::type_name::<Self>())
  879            .field("wordwise", &self.wordwise)
  880            .field("done", &self.done)
  881            .finish()
  882    }
  883}
  884
  885#[derive(Debug)]
  886struct AutocloseRegion {
  887    selection_id: usize,
  888    range: Range<Anchor>,
  889    pair: BracketPair,
  890}
  891
  892#[derive(Debug)]
  893struct SnippetState {
  894    ranges: Vec<Vec<Range<Anchor>>>,
  895    active_index: usize,
  896    choices: Vec<Option<Vec<String>>>,
  897}
  898
  899#[doc(hidden)]
  900pub struct RenameState {
  901    pub range: Range<Anchor>,
  902    pub old_name: Arc<str>,
  903    pub editor: View<Editor>,
  904    block_id: CustomBlockId,
  905}
  906
  907struct InvalidationStack<T>(Vec<T>);
  908
  909struct RegisteredInlineCompletionProvider {
  910    provider: Arc<dyn InlineCompletionProviderHandle>,
  911    _subscription: Subscription,
  912}
  913
  914enum ContextMenu {
  915    Completions(CompletionsMenu),
  916    CodeActions(CodeActionsMenu),
  917}
  918
  919impl ContextMenu {
  920    fn select_first(
  921        &mut self,
  922        provider: Option<&dyn CompletionProvider>,
  923        cx: &mut ViewContext<Editor>,
  924    ) -> bool {
  925        if self.visible() {
  926            match self {
  927                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  928                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  929            }
  930            true
  931        } else {
  932            false
  933        }
  934    }
  935
  936    fn select_prev(
  937        &mut self,
  938        provider: Option<&dyn CompletionProvider>,
  939        cx: &mut ViewContext<Editor>,
  940    ) -> bool {
  941        if self.visible() {
  942            match self {
  943                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  944                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  945            }
  946            true
  947        } else {
  948            false
  949        }
  950    }
  951
  952    fn select_next(
  953        &mut self,
  954        provider: Option<&dyn CompletionProvider>,
  955        cx: &mut ViewContext<Editor>,
  956    ) -> bool {
  957        if self.visible() {
  958            match self {
  959                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  960                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  961            }
  962            true
  963        } else {
  964            false
  965        }
  966    }
  967
  968    fn select_last(
  969        &mut self,
  970        provider: Option<&dyn CompletionProvider>,
  971        cx: &mut ViewContext<Editor>,
  972    ) -> bool {
  973        if self.visible() {
  974            match self {
  975                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  976                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  977            }
  978            true
  979        } else {
  980            false
  981        }
  982    }
  983
  984    fn visible(&self) -> bool {
  985        match self {
  986            ContextMenu::Completions(menu) => menu.visible(),
  987            ContextMenu::CodeActions(menu) => menu.visible(),
  988        }
  989    }
  990
  991    fn render(
  992        &self,
  993        cursor_position: DisplayPoint,
  994        style: &EditorStyle,
  995        max_height: Pixels,
  996        workspace: Option<WeakView<Workspace>>,
  997        cx: &mut ViewContext<Editor>,
  998    ) -> (ContextMenuOrigin, AnyElement) {
  999        match self {
 1000            ContextMenu::Completions(menu) => (
 1001                ContextMenuOrigin::EditorPoint(cursor_position),
 1002                menu.render(style, max_height, workspace, cx),
 1003            ),
 1004            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
 1005        }
 1006    }
 1007}
 1008
 1009enum ContextMenuOrigin {
 1010    EditorPoint(DisplayPoint),
 1011    GutterIndicator(DisplayRow),
 1012}
 1013
 1014#[derive(Clone, Debug)]
 1015struct CompletionsMenu {
 1016    id: CompletionId,
 1017    sort_completions: bool,
 1018    initial_position: Anchor,
 1019    buffer: Model<Buffer>,
 1020    completions: Arc<RwLock<Box<[Completion]>>>,
 1021    match_candidates: Arc<[StringMatchCandidate]>,
 1022    matches: Arc<[StringMatch]>,
 1023    selected_item: usize,
 1024    scroll_handle: UniformListScrollHandle,
 1025    selected_completion_documentation_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
 1026}
 1027
 1028impl CompletionsMenu {
 1029    fn new(
 1030        id: CompletionId,
 1031        sort_completions: bool,
 1032        initial_position: Anchor,
 1033        buffer: Model<Buffer>,
 1034        completions: Box<[Completion]>,
 1035    ) -> Self {
 1036        let match_candidates = completions
 1037            .iter()
 1038            .enumerate()
 1039            .map(|(id, completion)| StringMatchCandidate::new(id, completion.label.text.clone()))
 1040            .collect();
 1041
 1042        Self {
 1043            id,
 1044            sort_completions,
 1045            initial_position,
 1046            buffer,
 1047            completions: Arc::new(RwLock::new(completions)),
 1048            match_candidates,
 1049            matches: Vec::new().into(),
 1050            selected_item: 0,
 1051            scroll_handle: UniformListScrollHandle::new(),
 1052            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1053                DebouncedDelay::new(),
 1054            ))),
 1055        }
 1056    }
 1057
 1058    fn new_snippet_choices(
 1059        id: CompletionId,
 1060        sort_completions: bool,
 1061        choices: &Vec<String>,
 1062        selection: Range<Anchor>,
 1063        buffer: Model<Buffer>,
 1064    ) -> Self {
 1065        let completions = choices
 1066            .iter()
 1067            .map(|choice| Completion {
 1068                old_range: selection.start.text_anchor..selection.end.text_anchor,
 1069                new_text: choice.to_string(),
 1070                label: CodeLabel {
 1071                    text: choice.to_string(),
 1072                    runs: Default::default(),
 1073                    filter_range: Default::default(),
 1074                },
 1075                server_id: LanguageServerId(usize::MAX),
 1076                documentation: None,
 1077                lsp_completion: Default::default(),
 1078                confirm: None,
 1079            })
 1080            .collect();
 1081
 1082        let match_candidates = choices
 1083            .iter()
 1084            .enumerate()
 1085            .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
 1086            .collect();
 1087        let matches = choices
 1088            .iter()
 1089            .enumerate()
 1090            .map(|(id, completion)| StringMatch {
 1091                candidate_id: id,
 1092                score: 1.,
 1093                positions: vec![],
 1094                string: completion.clone(),
 1095            })
 1096            .collect();
 1097        Self {
 1098            id,
 1099            sort_completions,
 1100            initial_position: selection.start,
 1101            buffer,
 1102            completions: Arc::new(RwLock::new(completions)),
 1103            match_candidates,
 1104            matches,
 1105            selected_item: 0,
 1106            scroll_handle: UniformListScrollHandle::new(),
 1107            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1108                DebouncedDelay::new(),
 1109            ))),
 1110        }
 1111    }
 1112
 1113    fn suppress_documentation_resolution(mut self) -> Self {
 1114        self.selected_completion_documentation_resolve_debounce
 1115            .take();
 1116        self
 1117    }
 1118
 1119    fn select_first(
 1120        &mut self,
 1121        provider: Option<&dyn CompletionProvider>,
 1122        cx: &mut ViewContext<Editor>,
 1123    ) {
 1124        self.selected_item = 0;
 1125        self.scroll_handle
 1126            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1127        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1128        cx.notify();
 1129    }
 1130
 1131    fn select_prev(
 1132        &mut self,
 1133        provider: Option<&dyn CompletionProvider>,
 1134        cx: &mut ViewContext<Editor>,
 1135    ) {
 1136        if self.selected_item > 0 {
 1137            self.selected_item -= 1;
 1138        } else {
 1139            self.selected_item = self.matches.len() - 1;
 1140        }
 1141        self.scroll_handle
 1142            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1143        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1144        cx.notify();
 1145    }
 1146
 1147    fn select_next(
 1148        &mut self,
 1149        provider: Option<&dyn CompletionProvider>,
 1150        cx: &mut ViewContext<Editor>,
 1151    ) {
 1152        if self.selected_item + 1 < self.matches.len() {
 1153            self.selected_item += 1;
 1154        } else {
 1155            self.selected_item = 0;
 1156        }
 1157        self.scroll_handle
 1158            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1159        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1160        cx.notify();
 1161    }
 1162
 1163    fn select_last(
 1164        &mut self,
 1165        provider: Option<&dyn CompletionProvider>,
 1166        cx: &mut ViewContext<Editor>,
 1167    ) {
 1168        self.selected_item = self.matches.len() - 1;
 1169        self.scroll_handle
 1170            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1171        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1172        cx.notify();
 1173    }
 1174
 1175    fn pre_resolve_completion_documentation(
 1176        buffer: Model<Buffer>,
 1177        completions: Arc<RwLock<Box<[Completion]>>>,
 1178        matches: Arc<[StringMatch]>,
 1179        editor: &Editor,
 1180        cx: &mut ViewContext<Editor>,
 1181    ) -> Task<()> {
 1182        let settings = EditorSettings::get_global(cx);
 1183        if !settings.show_completion_documentation {
 1184            return Task::ready(());
 1185        }
 1186
 1187        let Some(provider) = editor.completion_provider.as_ref() else {
 1188            return Task::ready(());
 1189        };
 1190
 1191        let resolve_task = provider.resolve_completions(
 1192            buffer,
 1193            matches.iter().map(|m| m.candidate_id).collect(),
 1194            completions.clone(),
 1195            cx,
 1196        );
 1197
 1198        cx.spawn(move |this, mut cx| async move {
 1199            if let Some(true) = resolve_task.await.log_err() {
 1200                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1201            }
 1202        })
 1203    }
 1204
 1205    fn attempt_resolve_selected_completion_documentation(
 1206        &mut self,
 1207        provider: Option<&dyn CompletionProvider>,
 1208        cx: &mut ViewContext<Editor>,
 1209    ) {
 1210        let settings = EditorSettings::get_global(cx);
 1211        if !settings.show_completion_documentation {
 1212            return;
 1213        }
 1214
 1215        let completion_index = self.matches[self.selected_item].candidate_id;
 1216        let Some(provider) = provider else {
 1217            return;
 1218        };
 1219        let Some(documentation_resolve) = self
 1220            .selected_completion_documentation_resolve_debounce
 1221            .as_ref()
 1222        else {
 1223            return;
 1224        };
 1225
 1226        let resolve_task = provider.resolve_completions(
 1227            self.buffer.clone(),
 1228            vec![completion_index],
 1229            self.completions.clone(),
 1230            cx,
 1231        );
 1232
 1233        let delay_ms =
 1234            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1235        let delay = Duration::from_millis(delay_ms);
 1236
 1237        documentation_resolve.lock().fire_new(delay, cx, |_, cx| {
 1238            cx.spawn(move |this, mut cx| async move {
 1239                if let Some(true) = resolve_task.await.log_err() {
 1240                    this.update(&mut cx, |_, cx| cx.notify()).ok();
 1241                }
 1242            })
 1243        });
 1244    }
 1245
 1246    fn visible(&self) -> bool {
 1247        !self.matches.is_empty()
 1248    }
 1249
 1250    fn render(
 1251        &self,
 1252        style: &EditorStyle,
 1253        max_height: Pixels,
 1254        workspace: Option<WeakView<Workspace>>,
 1255        cx: &mut ViewContext<Editor>,
 1256    ) -> AnyElement {
 1257        let settings = EditorSettings::get_global(cx);
 1258        let show_completion_documentation = settings.show_completion_documentation;
 1259
 1260        let widest_completion_ix = self
 1261            .matches
 1262            .iter()
 1263            .enumerate()
 1264            .max_by_key(|(_, mat)| {
 1265                let completions = self.completions.read();
 1266                let completion = &completions[mat.candidate_id];
 1267                let documentation = &completion.documentation;
 1268
 1269                let mut len = completion.label.text.chars().count();
 1270                if let Some(Documentation::SingleLine(text)) = documentation {
 1271                    if show_completion_documentation {
 1272                        len += text.chars().count();
 1273                    }
 1274                }
 1275
 1276                len
 1277            })
 1278            .map(|(ix, _)| ix);
 1279
 1280        let completions = self.completions.clone();
 1281        let matches = self.matches.clone();
 1282        let selected_item = self.selected_item;
 1283        let style = style.clone();
 1284
 1285        let multiline_docs = if show_completion_documentation {
 1286            let mat = &self.matches[selected_item];
 1287            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1288                Some(Documentation::MultiLinePlainText(text)) => {
 1289                    Some(div().child(SharedString::from(text.clone())))
 1290                }
 1291                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1292                    Some(div().child(render_parsed_markdown(
 1293                        "completions_markdown",
 1294                        parsed,
 1295                        &style,
 1296                        workspace,
 1297                        cx,
 1298                    )))
 1299                }
 1300                _ => None,
 1301            };
 1302            multiline_docs.map(|div| {
 1303                div.id("multiline_docs")
 1304                    .max_h(max_height)
 1305                    .flex_1()
 1306                    .px_1p5()
 1307                    .py_1()
 1308                    .min_w(px(260.))
 1309                    .max_w(px(640.))
 1310                    .w(px(500.))
 1311                    .overflow_y_scroll()
 1312                    .occlude()
 1313            })
 1314        } else {
 1315            None
 1316        };
 1317
 1318        let list = uniform_list(
 1319            cx.view().clone(),
 1320            "completions",
 1321            matches.len(),
 1322            move |_editor, range, cx| {
 1323                let start_ix = range.start;
 1324                let completions_guard = completions.read();
 1325
 1326                matches[range]
 1327                    .iter()
 1328                    .enumerate()
 1329                    .map(|(ix, mat)| {
 1330                        let item_ix = start_ix + ix;
 1331                        let candidate_id = mat.candidate_id;
 1332                        let completion = &completions_guard[candidate_id];
 1333
 1334                        let documentation = if show_completion_documentation {
 1335                            &completion.documentation
 1336                        } else {
 1337                            &None
 1338                        };
 1339
 1340                        let highlights = gpui::combine_highlights(
 1341                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1342                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1343                                |(range, mut highlight)| {
 1344                                    // Ignore font weight for syntax highlighting, as we'll use it
 1345                                    // for fuzzy matches.
 1346                                    highlight.font_weight = None;
 1347
 1348                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1349                                        highlight.strikethrough = Some(StrikethroughStyle {
 1350                                            thickness: 1.0.into(),
 1351                                            ..Default::default()
 1352                                        });
 1353                                        highlight.color = Some(cx.theme().colors().text_muted);
 1354                                    }
 1355
 1356                                    (range, highlight)
 1357                                },
 1358                            ),
 1359                        );
 1360                        let completion_label = StyledText::new(completion.label.text.clone())
 1361                            .with_highlights(&style.text, highlights);
 1362                        let documentation_label =
 1363                            if let Some(Documentation::SingleLine(text)) = documentation {
 1364                                if text.trim().is_empty() {
 1365                                    None
 1366                                } else {
 1367                                    Some(
 1368                                        Label::new(text.clone())
 1369                                            .ml_4()
 1370                                            .size(LabelSize::Small)
 1371                                            .color(Color::Muted),
 1372                                    )
 1373                                }
 1374                            } else {
 1375                                None
 1376                            };
 1377
 1378                        let color_swatch = completion
 1379                            .color()
 1380                            .map(|color| div().size_4().bg(color).rounded_sm());
 1381
 1382                        div().min_w(px(220.)).max_w(px(540.)).child(
 1383                            ListItem::new(mat.candidate_id)
 1384                                .inset(true)
 1385                                .selected(item_ix == selected_item)
 1386                                .on_click(cx.listener(move |editor, _event, cx| {
 1387                                    cx.stop_propagation();
 1388                                    if let Some(task) = editor.confirm_completion(
 1389                                        &ConfirmCompletion {
 1390                                            item_ix: Some(item_ix),
 1391                                        },
 1392                                        cx,
 1393                                    ) {
 1394                                        task.detach_and_log_err(cx)
 1395                                    }
 1396                                }))
 1397                                .start_slot::<Div>(color_swatch)
 1398                                .child(h_flex().overflow_hidden().child(completion_label))
 1399                                .end_slot::<Label>(documentation_label),
 1400                        )
 1401                    })
 1402                    .collect()
 1403            },
 1404        )
 1405        .occlude()
 1406        .max_h(max_height)
 1407        .track_scroll(self.scroll_handle.clone())
 1408        .with_width_from_item(widest_completion_ix)
 1409        .with_sizing_behavior(ListSizingBehavior::Infer);
 1410
 1411        Popover::new()
 1412            .child(list)
 1413            .when_some(multiline_docs, |popover, multiline_docs| {
 1414                popover.aside(multiline_docs)
 1415            })
 1416            .into_any_element()
 1417    }
 1418
 1419    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1420        let mut matches = if let Some(query) = query {
 1421            fuzzy::match_strings(
 1422                &self.match_candidates,
 1423                query,
 1424                query.chars().any(|c| c.is_uppercase()),
 1425                100,
 1426                &Default::default(),
 1427                executor,
 1428            )
 1429            .await
 1430        } else {
 1431            self.match_candidates
 1432                .iter()
 1433                .enumerate()
 1434                .map(|(candidate_id, candidate)| StringMatch {
 1435                    candidate_id,
 1436                    score: Default::default(),
 1437                    positions: Default::default(),
 1438                    string: candidate.string.clone(),
 1439                })
 1440                .collect()
 1441        };
 1442
 1443        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1444        if let Some(query) = query {
 1445            if let Some(query_start) = query.chars().next() {
 1446                matches.retain(|string_match| {
 1447                    split_words(&string_match.string).any(|word| {
 1448                        // Check that the first codepoint of the word as lowercase matches the first
 1449                        // codepoint of the query as lowercase
 1450                        word.chars()
 1451                            .flat_map(|codepoint| codepoint.to_lowercase())
 1452                            .zip(query_start.to_lowercase())
 1453                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1454                    })
 1455                });
 1456            }
 1457        }
 1458
 1459        let completions = self.completions.read();
 1460        if self.sort_completions {
 1461            matches.sort_unstable_by_key(|mat| {
 1462                // We do want to strike a balance here between what the language server tells us
 1463                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1464                // `Creat` and there is a local variable called `CreateComponent`).
 1465                // So what we do is: we bucket all matches into two buckets
 1466                // - Strong matches
 1467                // - Weak matches
 1468                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1469                // and the Weak matches are the rest.
 1470                //
 1471                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1472                // matches, we prefer language-server sort_text first.
 1473                //
 1474                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1475                // Rest of the matches(weak) can be sorted as language-server expects.
 1476
 1477                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1478                enum MatchScore<'a> {
 1479                    Strong {
 1480                        score: Reverse<OrderedFloat<f64>>,
 1481                        sort_text: Option<&'a str>,
 1482                        sort_key: (usize, &'a str),
 1483                    },
 1484                    Weak {
 1485                        sort_text: Option<&'a str>,
 1486                        score: Reverse<OrderedFloat<f64>>,
 1487                        sort_key: (usize, &'a str),
 1488                    },
 1489                }
 1490
 1491                let completion = &completions[mat.candidate_id];
 1492                let sort_key = completion.sort_key();
 1493                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1494                let score = Reverse(OrderedFloat(mat.score));
 1495
 1496                if mat.score >= 0.2 {
 1497                    MatchScore::Strong {
 1498                        score,
 1499                        sort_text,
 1500                        sort_key,
 1501                    }
 1502                } else {
 1503                    MatchScore::Weak {
 1504                        sort_text,
 1505                        score,
 1506                        sort_key,
 1507                    }
 1508                }
 1509            });
 1510        }
 1511
 1512        for mat in &mut matches {
 1513            let completion = &completions[mat.candidate_id];
 1514            mat.string.clone_from(&completion.label.text);
 1515            for position in &mut mat.positions {
 1516                *position += completion.label.filter_range.start;
 1517            }
 1518        }
 1519        drop(completions);
 1520
 1521        self.matches = matches.into();
 1522        self.selected_item = 0;
 1523    }
 1524}
 1525
 1526#[derive(Clone)]
 1527struct AvailableCodeAction {
 1528    excerpt_id: ExcerptId,
 1529    action: CodeAction,
 1530    provider: Arc<dyn CodeActionProvider>,
 1531}
 1532
 1533#[derive(Clone)]
 1534struct CodeActionContents {
 1535    tasks: Option<Arc<ResolvedTasks>>,
 1536    actions: Option<Arc<[AvailableCodeAction]>>,
 1537}
 1538
 1539impl CodeActionContents {
 1540    fn len(&self) -> usize {
 1541        match (&self.tasks, &self.actions) {
 1542            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1543            (Some(tasks), None) => tasks.templates.len(),
 1544            (None, Some(actions)) => actions.len(),
 1545            (None, None) => 0,
 1546        }
 1547    }
 1548
 1549    fn is_empty(&self) -> bool {
 1550        match (&self.tasks, &self.actions) {
 1551            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1552            (Some(tasks), None) => tasks.templates.is_empty(),
 1553            (None, Some(actions)) => actions.is_empty(),
 1554            (None, None) => true,
 1555        }
 1556    }
 1557
 1558    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1559        self.tasks
 1560            .iter()
 1561            .flat_map(|tasks| {
 1562                tasks
 1563                    .templates
 1564                    .iter()
 1565                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1566            })
 1567            .chain(self.actions.iter().flat_map(|actions| {
 1568                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1569                    excerpt_id: available.excerpt_id,
 1570                    action: available.action.clone(),
 1571                    provider: available.provider.clone(),
 1572                })
 1573            }))
 1574    }
 1575    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1576        match (&self.tasks, &self.actions) {
 1577            (Some(tasks), Some(actions)) => {
 1578                if index < tasks.templates.len() {
 1579                    tasks
 1580                        .templates
 1581                        .get(index)
 1582                        .cloned()
 1583                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1584                } else {
 1585                    actions.get(index - tasks.templates.len()).map(|available| {
 1586                        CodeActionsItem::CodeAction {
 1587                            excerpt_id: available.excerpt_id,
 1588                            action: available.action.clone(),
 1589                            provider: available.provider.clone(),
 1590                        }
 1591                    })
 1592                }
 1593            }
 1594            (Some(tasks), None) => tasks
 1595                .templates
 1596                .get(index)
 1597                .cloned()
 1598                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1599            (None, Some(actions)) => {
 1600                actions
 1601                    .get(index)
 1602                    .map(|available| CodeActionsItem::CodeAction {
 1603                        excerpt_id: available.excerpt_id,
 1604                        action: available.action.clone(),
 1605                        provider: available.provider.clone(),
 1606                    })
 1607            }
 1608            (None, None) => None,
 1609        }
 1610    }
 1611}
 1612
 1613#[allow(clippy::large_enum_variant)]
 1614#[derive(Clone)]
 1615enum CodeActionsItem {
 1616    Task(TaskSourceKind, ResolvedTask),
 1617    CodeAction {
 1618        excerpt_id: ExcerptId,
 1619        action: CodeAction,
 1620        provider: Arc<dyn CodeActionProvider>,
 1621    },
 1622}
 1623
 1624impl CodeActionsItem {
 1625    fn as_task(&self) -> Option<&ResolvedTask> {
 1626        let Self::Task(_, task) = self else {
 1627            return None;
 1628        };
 1629        Some(task)
 1630    }
 1631    fn as_code_action(&self) -> Option<&CodeAction> {
 1632        let Self::CodeAction { action, .. } = self else {
 1633            return None;
 1634        };
 1635        Some(action)
 1636    }
 1637    fn label(&self) -> String {
 1638        match self {
 1639            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1640            Self::Task(_, task) => task.resolved_label.clone(),
 1641        }
 1642    }
 1643}
 1644
 1645struct CodeActionsMenu {
 1646    actions: CodeActionContents,
 1647    buffer: Model<Buffer>,
 1648    selected_item: usize,
 1649    scroll_handle: UniformListScrollHandle,
 1650    deployed_from_indicator: Option<DisplayRow>,
 1651}
 1652
 1653impl CodeActionsMenu {
 1654    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1655        self.selected_item = 0;
 1656        self.scroll_handle
 1657            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1658        cx.notify()
 1659    }
 1660
 1661    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1662        if self.selected_item > 0 {
 1663            self.selected_item -= 1;
 1664        } else {
 1665            self.selected_item = self.actions.len() - 1;
 1666        }
 1667        self.scroll_handle
 1668            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1669        cx.notify();
 1670    }
 1671
 1672    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1673        if self.selected_item + 1 < self.actions.len() {
 1674            self.selected_item += 1;
 1675        } else {
 1676            self.selected_item = 0;
 1677        }
 1678        self.scroll_handle
 1679            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1680        cx.notify();
 1681    }
 1682
 1683    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1684        self.selected_item = self.actions.len() - 1;
 1685        self.scroll_handle
 1686            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1687        cx.notify()
 1688    }
 1689
 1690    fn visible(&self) -> bool {
 1691        !self.actions.is_empty()
 1692    }
 1693
 1694    fn render(
 1695        &self,
 1696        cursor_position: DisplayPoint,
 1697        _style: &EditorStyle,
 1698        max_height: Pixels,
 1699        cx: &mut ViewContext<Editor>,
 1700    ) -> (ContextMenuOrigin, AnyElement) {
 1701        let actions = self.actions.clone();
 1702        let selected_item = self.selected_item;
 1703        let element = uniform_list(
 1704            cx.view().clone(),
 1705            "code_actions_menu",
 1706            self.actions.len(),
 1707            move |_this, range, cx| {
 1708                actions
 1709                    .iter()
 1710                    .skip(range.start)
 1711                    .take(range.end - range.start)
 1712                    .enumerate()
 1713                    .map(|(ix, action)| {
 1714                        let item_ix = range.start + ix;
 1715                        let selected = selected_item == item_ix;
 1716                        let colors = cx.theme().colors();
 1717                        div()
 1718                            .px_1()
 1719                            .rounded_md()
 1720                            .text_color(colors.text)
 1721                            .when(selected, |style| {
 1722                                style
 1723                                    .bg(colors.element_active)
 1724                                    .text_color(colors.text_accent)
 1725                            })
 1726                            .hover(|style| {
 1727                                style
 1728                                    .bg(colors.element_hover)
 1729                                    .text_color(colors.text_accent)
 1730                            })
 1731                            .whitespace_nowrap()
 1732                            .when_some(action.as_code_action(), |this, action| {
 1733                                this.on_mouse_down(
 1734                                    MouseButton::Left,
 1735                                    cx.listener(move |editor, _, cx| {
 1736                                        cx.stop_propagation();
 1737                                        if let Some(task) = editor.confirm_code_action(
 1738                                            &ConfirmCodeAction {
 1739                                                item_ix: Some(item_ix),
 1740                                            },
 1741                                            cx,
 1742                                        ) {
 1743                                            task.detach_and_log_err(cx)
 1744                                        }
 1745                                    }),
 1746                                )
 1747                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1748                                .child(SharedString::from(action.lsp_action.title.clone()))
 1749                            })
 1750                            .when_some(action.as_task(), |this, task| {
 1751                                this.on_mouse_down(
 1752                                    MouseButton::Left,
 1753                                    cx.listener(move |editor, _, cx| {
 1754                                        cx.stop_propagation();
 1755                                        if let Some(task) = editor.confirm_code_action(
 1756                                            &ConfirmCodeAction {
 1757                                                item_ix: Some(item_ix),
 1758                                            },
 1759                                            cx,
 1760                                        ) {
 1761                                            task.detach_and_log_err(cx)
 1762                                        }
 1763                                    }),
 1764                                )
 1765                                .child(SharedString::from(task.resolved_label.clone()))
 1766                            })
 1767                    })
 1768                    .collect()
 1769            },
 1770        )
 1771        .elevation_1(cx)
 1772        .p_1()
 1773        .max_h(max_height)
 1774        .occlude()
 1775        .track_scroll(self.scroll_handle.clone())
 1776        .with_width_from_item(
 1777            self.actions
 1778                .iter()
 1779                .enumerate()
 1780                .max_by_key(|(_, action)| match action {
 1781                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1782                    CodeActionsItem::CodeAction { action, .. } => {
 1783                        action.lsp_action.title.chars().count()
 1784                    }
 1785                })
 1786                .map(|(ix, _)| ix),
 1787        )
 1788        .with_sizing_behavior(ListSizingBehavior::Infer)
 1789        .into_any_element();
 1790
 1791        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1792            ContextMenuOrigin::GutterIndicator(row)
 1793        } else {
 1794            ContextMenuOrigin::EditorPoint(cursor_position)
 1795        };
 1796
 1797        (cursor_position, element)
 1798    }
 1799}
 1800
 1801#[derive(Debug)]
 1802struct ActiveDiagnosticGroup {
 1803    primary_range: Range<Anchor>,
 1804    primary_message: String,
 1805    group_id: usize,
 1806    blocks: HashMap<CustomBlockId, Diagnostic>,
 1807    is_valid: bool,
 1808}
 1809
 1810#[derive(Serialize, Deserialize, Clone, Debug)]
 1811pub struct ClipboardSelection {
 1812    pub len: usize,
 1813    pub is_entire_line: bool,
 1814    pub first_line_indent: u32,
 1815}
 1816
 1817#[derive(Debug)]
 1818pub(crate) struct NavigationData {
 1819    cursor_anchor: Anchor,
 1820    cursor_position: Point,
 1821    scroll_anchor: ScrollAnchor,
 1822    scroll_top_row: u32,
 1823}
 1824
 1825#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1826pub enum GotoDefinitionKind {
 1827    Symbol,
 1828    Declaration,
 1829    Type,
 1830    Implementation,
 1831}
 1832
 1833#[derive(Debug, Clone)]
 1834enum InlayHintRefreshReason {
 1835    Toggle(bool),
 1836    SettingsChange(InlayHintSettings),
 1837    NewLinesShown,
 1838    BufferEdited(HashSet<Arc<Language>>),
 1839    RefreshRequested,
 1840    ExcerptsRemoved(Vec<ExcerptId>),
 1841}
 1842
 1843impl InlayHintRefreshReason {
 1844    fn description(&self) -> &'static str {
 1845        match self {
 1846            Self::Toggle(_) => "toggle",
 1847            Self::SettingsChange(_) => "settings change",
 1848            Self::NewLinesShown => "new lines shown",
 1849            Self::BufferEdited(_) => "buffer edited",
 1850            Self::RefreshRequested => "refresh requested",
 1851            Self::ExcerptsRemoved(_) => "excerpts removed",
 1852        }
 1853    }
 1854}
 1855
 1856pub(crate) struct FocusedBlock {
 1857    id: BlockId,
 1858    focus_handle: WeakFocusHandle,
 1859}
 1860
 1861#[derive(Clone)]
 1862struct JumpData {
 1863    excerpt_id: ExcerptId,
 1864    position: Point,
 1865    anchor: text::Anchor,
 1866    path: Option<project::ProjectPath>,
 1867    line_offset_from_top: u32,
 1868}
 1869
 1870impl Editor {
 1871    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1872        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1873        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1874        Self::new(
 1875            EditorMode::SingleLine { auto_width: false },
 1876            buffer,
 1877            None,
 1878            false,
 1879            cx,
 1880        )
 1881    }
 1882
 1883    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1884        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1885        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1886        Self::new(EditorMode::Full, buffer, None, false, cx)
 1887    }
 1888
 1889    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1890        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1891        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1892        Self::new(
 1893            EditorMode::SingleLine { auto_width: true },
 1894            buffer,
 1895            None,
 1896            false,
 1897            cx,
 1898        )
 1899    }
 1900
 1901    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1902        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1903        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1904        Self::new(
 1905            EditorMode::AutoHeight { max_lines },
 1906            buffer,
 1907            None,
 1908            false,
 1909            cx,
 1910        )
 1911    }
 1912
 1913    pub fn for_buffer(
 1914        buffer: Model<Buffer>,
 1915        project: Option<Model<Project>>,
 1916        cx: &mut ViewContext<Self>,
 1917    ) -> Self {
 1918        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1919        Self::new(EditorMode::Full, buffer, project, false, cx)
 1920    }
 1921
 1922    pub fn for_multibuffer(
 1923        buffer: Model<MultiBuffer>,
 1924        project: Option<Model<Project>>,
 1925        show_excerpt_controls: bool,
 1926        cx: &mut ViewContext<Self>,
 1927    ) -> Self {
 1928        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1929    }
 1930
 1931    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1932        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1933        let mut clone = Self::new(
 1934            self.mode,
 1935            self.buffer.clone(),
 1936            self.project.clone(),
 1937            show_excerpt_controls,
 1938            cx,
 1939        );
 1940        self.display_map.update(cx, |display_map, cx| {
 1941            let snapshot = display_map.snapshot(cx);
 1942            clone.display_map.update(cx, |display_map, cx| {
 1943                display_map.set_state(&snapshot, cx);
 1944            });
 1945        });
 1946        clone.selections.clone_state(&self.selections);
 1947        clone.scroll_manager.clone_state(&self.scroll_manager);
 1948        clone.searchable = self.searchable;
 1949        clone
 1950    }
 1951
 1952    pub fn new(
 1953        mode: EditorMode,
 1954        buffer: Model<MultiBuffer>,
 1955        project: Option<Model<Project>>,
 1956        show_excerpt_controls: bool,
 1957        cx: &mut ViewContext<Self>,
 1958    ) -> Self {
 1959        let style = cx.text_style();
 1960        let font_size = style.font_size.to_pixels(cx.rem_size());
 1961        let editor = cx.view().downgrade();
 1962        let fold_placeholder = FoldPlaceholder {
 1963            constrain_width: true,
 1964            render: Arc::new(move |fold_id, fold_range, cx| {
 1965                let editor = editor.clone();
 1966                div()
 1967                    .id(fold_id)
 1968                    .bg(cx.theme().colors().ghost_element_background)
 1969                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1970                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1971                    .rounded_sm()
 1972                    .size_full()
 1973                    .cursor_pointer()
 1974                    .child("")
 1975                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1976                    .on_click(move |_, cx| {
 1977                        editor
 1978                            .update(cx, |editor, cx| {
 1979                                editor.unfold_ranges(
 1980                                    &[fold_range.start..fold_range.end],
 1981                                    true,
 1982                                    false,
 1983                                    cx,
 1984                                );
 1985                                cx.stop_propagation();
 1986                            })
 1987                            .ok();
 1988                    })
 1989                    .into_any()
 1990            }),
 1991            merge_adjacent: true,
 1992            ..Default::default()
 1993        };
 1994        let display_map = cx.new_model(|cx| {
 1995            DisplayMap::new(
 1996                buffer.clone(),
 1997                style.font(),
 1998                font_size,
 1999                None,
 2000                show_excerpt_controls,
 2001                FILE_HEADER_HEIGHT,
 2002                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 2003                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 2004                fold_placeholder,
 2005                cx,
 2006            )
 2007        });
 2008
 2009        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 2010
 2011        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 2012
 2013        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 2014            .then(|| language_settings::SoftWrap::None);
 2015
 2016        let mut project_subscriptions = Vec::new();
 2017        if mode == EditorMode::Full {
 2018            if let Some(project) = project.as_ref() {
 2019                if buffer.read(cx).is_singleton() {
 2020                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 2021                        cx.emit(EditorEvent::TitleChanged);
 2022                    }));
 2023                }
 2024                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 2025                    if let project::Event::RefreshInlayHints = event {
 2026                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 2027                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 2028                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 2029                            let focus_handle = editor.focus_handle(cx);
 2030                            if focus_handle.is_focused(cx) {
 2031                                let snapshot = buffer.read(cx).snapshot();
 2032                                for (range, snippet) in snippet_edits {
 2033                                    let editor_range =
 2034                                        language::range_from_lsp(*range).to_offset(&snapshot);
 2035                                    editor
 2036                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 2037                                        .ok();
 2038                                }
 2039                            }
 2040                        }
 2041                    }
 2042                }));
 2043                if let Some(task_inventory) = project
 2044                    .read(cx)
 2045                    .task_store()
 2046                    .read(cx)
 2047                    .task_inventory()
 2048                    .cloned()
 2049                {
 2050                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 2051                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 2052                    }));
 2053                }
 2054            }
 2055        }
 2056
 2057        let inlay_hint_settings = inlay_hint_settings(
 2058            selections.newest_anchor().head(),
 2059            &buffer.read(cx).snapshot(cx),
 2060            cx,
 2061        );
 2062        let focus_handle = cx.focus_handle();
 2063        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 2064        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 2065            .detach();
 2066        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 2067            .detach();
 2068        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 2069
 2070        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 2071            Some(false)
 2072        } else {
 2073            None
 2074        };
 2075
 2076        let mut code_action_providers = Vec::new();
 2077        if let Some(project) = project.clone() {
 2078            code_action_providers.push(Arc::new(project) as Arc<_>);
 2079        }
 2080
 2081        let mut this = Self {
 2082            focus_handle,
 2083            show_cursor_when_unfocused: false,
 2084            last_focused_descendant: None,
 2085            buffer: buffer.clone(),
 2086            display_map: display_map.clone(),
 2087            selections,
 2088            scroll_manager: ScrollManager::new(cx),
 2089            columnar_selection_tail: None,
 2090            add_selections_state: None,
 2091            select_next_state: None,
 2092            select_prev_state: None,
 2093            selection_history: Default::default(),
 2094            autoclose_regions: Default::default(),
 2095            snippet_stack: Default::default(),
 2096            select_larger_syntax_node_stack: Vec::new(),
 2097            ime_transaction: Default::default(),
 2098            active_diagnostics: None,
 2099            soft_wrap_mode_override,
 2100            completion_provider: project.clone().map(|project| Box::new(project) as _),
 2101            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 2102            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 2103            project,
 2104            blink_manager: blink_manager.clone(),
 2105            show_local_selections: true,
 2106            mode,
 2107            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2108            show_gutter: mode == EditorMode::Full,
 2109            show_line_numbers: None,
 2110            use_relative_line_numbers: None,
 2111            show_git_diff_gutter: None,
 2112            show_code_actions: None,
 2113            show_runnables: None,
 2114            show_wrap_guides: None,
 2115            show_indent_guides,
 2116            placeholder_text: None,
 2117            highlight_order: 0,
 2118            highlighted_rows: HashMap::default(),
 2119            background_highlights: Default::default(),
 2120            gutter_highlights: TreeMap::default(),
 2121            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2122            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2123            nav_history: None,
 2124            context_menu: RwLock::new(None),
 2125            mouse_context_menu: None,
 2126            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2127            completion_tasks: Default::default(),
 2128            signature_help_state: SignatureHelpState::default(),
 2129            auto_signature_help: None,
 2130            find_all_references_task_sources: Vec::new(),
 2131            next_completion_id: 0,
 2132            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2133            next_inlay_id: 0,
 2134            code_action_providers,
 2135            available_code_actions: Default::default(),
 2136            code_actions_task: Default::default(),
 2137            document_highlights_task: Default::default(),
 2138            linked_editing_range_task: Default::default(),
 2139            pending_rename: Default::default(),
 2140            searchable: true,
 2141            cursor_shape: EditorSettings::get_global(cx)
 2142                .cursor_shape
 2143                .unwrap_or_default(),
 2144            current_line_highlight: None,
 2145            autoindent_mode: Some(AutoindentMode::EachLine),
 2146            collapse_matches: false,
 2147            workspace: None,
 2148            input_enabled: true,
 2149            use_modal_editing: mode == EditorMode::Full,
 2150            read_only: false,
 2151            use_autoclose: true,
 2152            use_auto_surround: true,
 2153            auto_replace_emoji_shortcode: false,
 2154            leader_peer_id: None,
 2155            remote_id: None,
 2156            hover_state: Default::default(),
 2157            hovered_link_state: Default::default(),
 2158            inline_completion_provider: None,
 2159            active_inline_completion: None,
 2160            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2161            expanded_hunks: ExpandedHunks::default(),
 2162            gutter_hovered: false,
 2163            pixel_position_of_newest_cursor: None,
 2164            last_bounds: None,
 2165            expect_bounds_change: None,
 2166            gutter_dimensions: GutterDimensions::default(),
 2167            style: None,
 2168            show_cursor_names: false,
 2169            hovered_cursors: Default::default(),
 2170            next_editor_action_id: EditorActionId::default(),
 2171            editor_actions: Rc::default(),
 2172            show_inline_completions_override: None,
 2173            enable_inline_completions: true,
 2174            custom_context_menu: None,
 2175            show_git_blame_gutter: false,
 2176            show_git_blame_inline: false,
 2177            show_selection_menu: None,
 2178            show_git_blame_inline_delay_task: None,
 2179            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2180            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2181                .session
 2182                .restore_unsaved_buffers,
 2183            blame: None,
 2184            blame_subscription: None,
 2185            tasks: Default::default(),
 2186            _subscriptions: vec![
 2187                cx.observe(&buffer, Self::on_buffer_changed),
 2188                cx.subscribe(&buffer, Self::on_buffer_event),
 2189                cx.observe(&display_map, Self::on_display_map_changed),
 2190                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2191                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2192                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2193                cx.observe_window_activation(|editor, cx| {
 2194                    let active = cx.is_window_active();
 2195                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2196                        if active {
 2197                            blink_manager.enable(cx);
 2198                        } else {
 2199                            blink_manager.disable(cx);
 2200                        }
 2201                    });
 2202                }),
 2203            ],
 2204            tasks_update_task: None,
 2205            linked_edit_ranges: Default::default(),
 2206            previous_search_ranges: None,
 2207            breadcrumb_header: None,
 2208            focused_block: None,
 2209            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2210            addons: HashMap::default(),
 2211            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2212            text_style_refinement: None,
 2213            active_line_trailer_provider: None,
 2214        };
 2215        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2216        this._subscriptions.extend(project_subscriptions);
 2217
 2218        this.end_selection(cx);
 2219        this.scroll_manager.show_scrollbar(cx);
 2220
 2221        if mode == EditorMode::Full {
 2222            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2223            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2224
 2225            if this.git_blame_inline_enabled {
 2226                this.git_blame_inline_enabled = true;
 2227                this.start_git_blame_inline(false, cx);
 2228            }
 2229        }
 2230
 2231        this.report_editor_event("open", None, cx);
 2232        this
 2233    }
 2234
 2235    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2236        self.mouse_context_menu
 2237            .as_ref()
 2238            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2239    }
 2240
 2241    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2242        let mut key_context = KeyContext::new_with_defaults();
 2243        key_context.add("Editor");
 2244        let mode = match self.mode {
 2245            EditorMode::SingleLine { .. } => "single_line",
 2246            EditorMode::AutoHeight { .. } => "auto_height",
 2247            EditorMode::Full => "full",
 2248        };
 2249
 2250        if EditorSettings::jupyter_enabled(cx) {
 2251            key_context.add("jupyter");
 2252        }
 2253
 2254        key_context.set("mode", mode);
 2255        if self.pending_rename.is_some() {
 2256            key_context.add("renaming");
 2257        }
 2258        if self.context_menu_visible() {
 2259            match self.context_menu.read().as_ref() {
 2260                Some(ContextMenu::Completions(_)) => {
 2261                    key_context.add("menu");
 2262                    key_context.add("showing_completions")
 2263                }
 2264                Some(ContextMenu::CodeActions(_)) => {
 2265                    key_context.add("menu");
 2266                    key_context.add("showing_code_actions")
 2267                }
 2268                None => {}
 2269            }
 2270        }
 2271
 2272        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2273        if !self.focus_handle(cx).contains_focused(cx)
 2274            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2275        {
 2276            for addon in self.addons.values() {
 2277                addon.extend_key_context(&mut key_context, cx)
 2278            }
 2279        }
 2280
 2281        if let Some(extension) = self
 2282            .buffer
 2283            .read(cx)
 2284            .as_singleton()
 2285            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2286        {
 2287            key_context.set("extension", extension.to_string());
 2288        }
 2289
 2290        if self.has_active_inline_completion(cx) {
 2291            key_context.add("copilot_suggestion");
 2292            key_context.add("inline_completion");
 2293        }
 2294
 2295        key_context
 2296    }
 2297
 2298    pub fn new_file(
 2299        workspace: &mut Workspace,
 2300        _: &workspace::NewFile,
 2301        cx: &mut ViewContext<Workspace>,
 2302    ) {
 2303        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2304            "Failed to create buffer",
 2305            cx,
 2306            |e, _| match e.error_code() {
 2307                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2308                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2309                e.error_tag("required").unwrap_or("the latest version")
 2310            )),
 2311                _ => None,
 2312            },
 2313        );
 2314    }
 2315
 2316    pub fn new_in_workspace(
 2317        workspace: &mut Workspace,
 2318        cx: &mut ViewContext<Workspace>,
 2319    ) -> Task<Result<View<Editor>>> {
 2320        let project = workspace.project().clone();
 2321        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2322
 2323        cx.spawn(|workspace, mut cx| async move {
 2324            let buffer = create.await?;
 2325            workspace.update(&mut cx, |workspace, cx| {
 2326                let editor =
 2327                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2328                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2329                editor
 2330            })
 2331        })
 2332    }
 2333
 2334    fn new_file_vertical(
 2335        workspace: &mut Workspace,
 2336        _: &workspace::NewFileSplitVertical,
 2337        cx: &mut ViewContext<Workspace>,
 2338    ) {
 2339        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2340    }
 2341
 2342    fn new_file_horizontal(
 2343        workspace: &mut Workspace,
 2344        _: &workspace::NewFileSplitHorizontal,
 2345        cx: &mut ViewContext<Workspace>,
 2346    ) {
 2347        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2348    }
 2349
 2350    fn new_file_in_direction(
 2351        workspace: &mut Workspace,
 2352        direction: SplitDirection,
 2353        cx: &mut ViewContext<Workspace>,
 2354    ) {
 2355        let project = workspace.project().clone();
 2356        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2357
 2358        cx.spawn(|workspace, mut cx| async move {
 2359            let buffer = create.await?;
 2360            workspace.update(&mut cx, move |workspace, cx| {
 2361                workspace.split_item(
 2362                    direction,
 2363                    Box::new(
 2364                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2365                    ),
 2366                    cx,
 2367                )
 2368            })?;
 2369            anyhow::Ok(())
 2370        })
 2371        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2372            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2373                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2374                e.error_tag("required").unwrap_or("the latest version")
 2375            )),
 2376            _ => None,
 2377        });
 2378    }
 2379
 2380    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2381        self.leader_peer_id
 2382    }
 2383
 2384    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2385        &self.buffer
 2386    }
 2387
 2388    pub fn workspace(&self) -> Option<View<Workspace>> {
 2389        self.workspace.as_ref()?.0.upgrade()
 2390    }
 2391
 2392    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2393        self.buffer().read(cx).title(cx)
 2394    }
 2395
 2396    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2397        let git_blame_gutter_max_author_length = self
 2398            .render_git_blame_gutter(cx)
 2399            .then(|| {
 2400                if let Some(blame) = self.blame.as_ref() {
 2401                    let max_author_length =
 2402                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2403                    Some(max_author_length)
 2404                } else {
 2405                    None
 2406                }
 2407            })
 2408            .flatten();
 2409
 2410        EditorSnapshot {
 2411            mode: self.mode,
 2412            show_gutter: self.show_gutter,
 2413            show_line_numbers: self.show_line_numbers,
 2414            show_git_diff_gutter: self.show_git_diff_gutter,
 2415            show_code_actions: self.show_code_actions,
 2416            show_runnables: self.show_runnables,
 2417            git_blame_gutter_max_author_length,
 2418            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2419            scroll_anchor: self.scroll_manager.anchor(),
 2420            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2421            placeholder_text: self.placeholder_text.clone(),
 2422            is_focused: self.focus_handle.is_focused(cx),
 2423            current_line_highlight: self
 2424                .current_line_highlight
 2425                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2426            gutter_hovered: self.gutter_hovered,
 2427        }
 2428    }
 2429
 2430    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2431        self.buffer.read(cx).language_at(point, cx)
 2432    }
 2433
 2434    pub fn file_at<T: ToOffset>(
 2435        &self,
 2436        point: T,
 2437        cx: &AppContext,
 2438    ) -> Option<Arc<dyn language::File>> {
 2439        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2440    }
 2441
 2442    pub fn active_excerpt(
 2443        &self,
 2444        cx: &AppContext,
 2445    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2446        self.buffer
 2447            .read(cx)
 2448            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2449    }
 2450
 2451    pub fn mode(&self) -> EditorMode {
 2452        self.mode
 2453    }
 2454
 2455    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2456        self.collaboration_hub.as_deref()
 2457    }
 2458
 2459    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2460        self.collaboration_hub = Some(hub);
 2461    }
 2462
 2463    pub fn set_custom_context_menu(
 2464        &mut self,
 2465        f: impl 'static
 2466            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2467    ) {
 2468        self.custom_context_menu = Some(Box::new(f))
 2469    }
 2470
 2471    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2472        self.completion_provider = provider;
 2473    }
 2474
 2475    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2476        self.semantics_provider.clone()
 2477    }
 2478
 2479    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2480        self.semantics_provider = provider;
 2481    }
 2482
 2483    pub fn set_inline_completion_provider<T>(
 2484        &mut self,
 2485        provider: Option<Model<T>>,
 2486        cx: &mut ViewContext<Self>,
 2487    ) where
 2488        T: InlineCompletionProvider,
 2489    {
 2490        self.inline_completion_provider =
 2491            provider.map(|provider| RegisteredInlineCompletionProvider {
 2492                _subscription: cx.observe(&provider, |this, _, cx| {
 2493                    if this.focus_handle.is_focused(cx) {
 2494                        this.update_visible_inline_completion(cx);
 2495                    }
 2496                }),
 2497                provider: Arc::new(provider),
 2498            });
 2499        self.refresh_inline_completion(false, false, cx);
 2500    }
 2501
 2502    pub fn set_active_line_trailer_provider<T>(
 2503        &mut self,
 2504        provider: Option<T>,
 2505        _cx: &mut ViewContext<Self>,
 2506    ) where
 2507        T: ActiveLineTrailerProvider + 'static,
 2508    {
 2509        self.active_line_trailer_provider = provider.map(|provider| Box::new(provider) as Box<_>);
 2510    }
 2511
 2512    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2513        self.placeholder_text.as_deref()
 2514    }
 2515
 2516    pub fn set_placeholder_text(
 2517        &mut self,
 2518        placeholder_text: impl Into<Arc<str>>,
 2519        cx: &mut ViewContext<Self>,
 2520    ) {
 2521        let placeholder_text = Some(placeholder_text.into());
 2522        if self.placeholder_text != placeholder_text {
 2523            self.placeholder_text = placeholder_text;
 2524            cx.notify();
 2525        }
 2526    }
 2527
 2528    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2529        self.cursor_shape = cursor_shape;
 2530
 2531        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2532        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2533
 2534        cx.notify();
 2535    }
 2536
 2537    pub fn set_current_line_highlight(
 2538        &mut self,
 2539        current_line_highlight: Option<CurrentLineHighlight>,
 2540    ) {
 2541        self.current_line_highlight = current_line_highlight;
 2542    }
 2543
 2544    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2545        self.collapse_matches = collapse_matches;
 2546    }
 2547
 2548    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2549        if self.collapse_matches {
 2550            return range.start..range.start;
 2551        }
 2552        range.clone()
 2553    }
 2554
 2555    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2556        if self.display_map.read(cx).clip_at_line_ends != clip {
 2557            self.display_map
 2558                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2559        }
 2560    }
 2561
 2562    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2563        self.input_enabled = input_enabled;
 2564    }
 2565
 2566    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2567        self.enable_inline_completions = enabled;
 2568    }
 2569
 2570    pub fn set_autoindent(&mut self, autoindent: bool) {
 2571        if autoindent {
 2572            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2573        } else {
 2574            self.autoindent_mode = None;
 2575        }
 2576    }
 2577
 2578    pub fn read_only(&self, cx: &AppContext) -> bool {
 2579        self.read_only || self.buffer.read(cx).read_only()
 2580    }
 2581
 2582    pub fn set_read_only(&mut self, read_only: bool) {
 2583        self.read_only = read_only;
 2584    }
 2585
 2586    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2587        self.use_autoclose = autoclose;
 2588    }
 2589
 2590    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2591        self.use_auto_surround = auto_surround;
 2592    }
 2593
 2594    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2595        self.auto_replace_emoji_shortcode = auto_replace;
 2596    }
 2597
 2598    pub fn toggle_inline_completions(
 2599        &mut self,
 2600        _: &ToggleInlineCompletions,
 2601        cx: &mut ViewContext<Self>,
 2602    ) {
 2603        if self.show_inline_completions_override.is_some() {
 2604            self.set_show_inline_completions(None, cx);
 2605        } else {
 2606            let cursor = self.selections.newest_anchor().head();
 2607            if let Some((buffer, cursor_buffer_position)) =
 2608                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2609            {
 2610                let show_inline_completions =
 2611                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2612                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2613            }
 2614        }
 2615    }
 2616
 2617    pub fn set_show_inline_completions(
 2618        &mut self,
 2619        show_inline_completions: Option<bool>,
 2620        cx: &mut ViewContext<Self>,
 2621    ) {
 2622        self.show_inline_completions_override = show_inline_completions;
 2623        self.refresh_inline_completion(false, true, cx);
 2624    }
 2625
 2626    fn should_show_inline_completions(
 2627        &self,
 2628        buffer: &Model<Buffer>,
 2629        buffer_position: language::Anchor,
 2630        cx: &AppContext,
 2631    ) -> bool {
 2632        if !self.snippet_stack.is_empty() {
 2633            return false;
 2634        }
 2635
 2636        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2637            return false;
 2638        }
 2639
 2640        if let Some(provider) = self.inline_completion_provider() {
 2641            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2642                show_inline_completions
 2643            } else {
 2644                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2645            }
 2646        } else {
 2647            false
 2648        }
 2649    }
 2650
 2651    fn inline_completions_disabled_in_scope(
 2652        &self,
 2653        buffer: &Model<Buffer>,
 2654        buffer_position: language::Anchor,
 2655        cx: &AppContext,
 2656    ) -> bool {
 2657        let snapshot = buffer.read(cx).snapshot();
 2658        let settings = snapshot.settings_at(buffer_position, cx);
 2659
 2660        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2661            return false;
 2662        };
 2663
 2664        scope.override_name().map_or(false, |scope_name| {
 2665            settings
 2666                .inline_completions_disabled_in
 2667                .iter()
 2668                .any(|s| s == scope_name)
 2669        })
 2670    }
 2671
 2672    pub fn set_use_modal_editing(&mut self, to: bool) {
 2673        self.use_modal_editing = to;
 2674    }
 2675
 2676    pub fn use_modal_editing(&self) -> bool {
 2677        self.use_modal_editing
 2678    }
 2679
 2680    fn selections_did_change(
 2681        &mut self,
 2682        local: bool,
 2683        old_cursor_position: &Anchor,
 2684        show_completions: bool,
 2685        cx: &mut ViewContext<Self>,
 2686    ) {
 2687        cx.invalidate_character_coordinates();
 2688
 2689        // Copy selections to primary selection buffer
 2690        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2691        if local {
 2692            let selections = self.selections.all::<usize>(cx);
 2693            let buffer_handle = self.buffer.read(cx).read(cx);
 2694
 2695            let mut text = String::new();
 2696            for (index, selection) in selections.iter().enumerate() {
 2697                let text_for_selection = buffer_handle
 2698                    .text_for_range(selection.start..selection.end)
 2699                    .collect::<String>();
 2700
 2701                text.push_str(&text_for_selection);
 2702                if index != selections.len() - 1 {
 2703                    text.push('\n');
 2704                }
 2705            }
 2706
 2707            if !text.is_empty() {
 2708                cx.write_to_primary(ClipboardItem::new_string(text));
 2709            }
 2710        }
 2711
 2712        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2713            self.buffer.update(cx, |buffer, cx| {
 2714                buffer.set_active_selections(
 2715                    &self.selections.disjoint_anchors(),
 2716                    self.selections.line_mode,
 2717                    self.cursor_shape,
 2718                    cx,
 2719                )
 2720            });
 2721        }
 2722        let display_map = self
 2723            .display_map
 2724            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2725        let buffer = &display_map.buffer_snapshot;
 2726        self.add_selections_state = None;
 2727        self.select_next_state = None;
 2728        self.select_prev_state = None;
 2729        self.select_larger_syntax_node_stack.clear();
 2730        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2731        self.snippet_stack
 2732            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2733        self.take_rename(false, cx);
 2734
 2735        let new_cursor_position = self.selections.newest_anchor().head();
 2736
 2737        self.push_to_nav_history(
 2738            *old_cursor_position,
 2739            Some(new_cursor_position.to_point(buffer)),
 2740            cx,
 2741        );
 2742
 2743        if local {
 2744            let new_cursor_position = self.selections.newest_anchor().head();
 2745            let mut context_menu = self.context_menu.write();
 2746            let completion_menu = match context_menu.as_ref() {
 2747                Some(ContextMenu::Completions(menu)) => Some(menu),
 2748
 2749                _ => {
 2750                    *context_menu = None;
 2751                    None
 2752                }
 2753            };
 2754
 2755            if let Some(completion_menu) = completion_menu {
 2756                let cursor_position = new_cursor_position.to_offset(buffer);
 2757                let (word_range, kind) =
 2758                    buffer.surrounding_word(completion_menu.initial_position, true);
 2759                if kind == Some(CharKind::Word)
 2760                    && word_range.to_inclusive().contains(&cursor_position)
 2761                {
 2762                    let mut completion_menu = completion_menu.clone();
 2763                    drop(context_menu);
 2764
 2765                    let query = Self::completion_query(buffer, cursor_position);
 2766                    cx.spawn(move |this, mut cx| async move {
 2767                        completion_menu
 2768                            .filter(query.as_deref(), cx.background_executor().clone())
 2769                            .await;
 2770
 2771                        this.update(&mut cx, |this, cx| {
 2772                            let mut context_menu = this.context_menu.write();
 2773                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2774                                return;
 2775                            };
 2776
 2777                            if menu.id > completion_menu.id {
 2778                                return;
 2779                            }
 2780
 2781                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2782                            drop(context_menu);
 2783                            cx.notify();
 2784                        })
 2785                    })
 2786                    .detach();
 2787
 2788                    if show_completions {
 2789                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2790                    }
 2791                } else {
 2792                    drop(context_menu);
 2793                    self.hide_context_menu(cx);
 2794                }
 2795            } else {
 2796                drop(context_menu);
 2797            }
 2798
 2799            hide_hover(self, cx);
 2800
 2801            if old_cursor_position.to_display_point(&display_map).row()
 2802                != new_cursor_position.to_display_point(&display_map).row()
 2803            {
 2804                self.available_code_actions.take();
 2805            }
 2806            self.refresh_code_actions(cx);
 2807            self.refresh_document_highlights(cx);
 2808            refresh_matching_bracket_highlights(self, cx);
 2809            self.discard_inline_completion(false, cx);
 2810            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2811            if self.git_blame_inline_enabled {
 2812                self.start_inline_blame_timer(cx);
 2813            }
 2814        }
 2815
 2816        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2817        cx.emit(EditorEvent::SelectionsChanged { local });
 2818
 2819        if self.selections.disjoint_anchors().len() == 1 {
 2820            cx.emit(SearchEvent::ActiveMatchChanged)
 2821        }
 2822        cx.notify();
 2823    }
 2824
 2825    pub fn change_selections<R>(
 2826        &mut self,
 2827        autoscroll: Option<Autoscroll>,
 2828        cx: &mut ViewContext<Self>,
 2829        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2830    ) -> R {
 2831        self.change_selections_inner(autoscroll, true, cx, change)
 2832    }
 2833
 2834    pub fn change_selections_inner<R>(
 2835        &mut self,
 2836        autoscroll: Option<Autoscroll>,
 2837        request_completions: bool,
 2838        cx: &mut ViewContext<Self>,
 2839        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2840    ) -> R {
 2841        let old_cursor_position = self.selections.newest_anchor().head();
 2842        self.push_to_selection_history();
 2843
 2844        let (changed, result) = self.selections.change_with(cx, change);
 2845
 2846        if changed {
 2847            if let Some(autoscroll) = autoscroll {
 2848                self.request_autoscroll(autoscroll, cx);
 2849            }
 2850            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2851
 2852            if self.should_open_signature_help_automatically(
 2853                &old_cursor_position,
 2854                self.signature_help_state.backspace_pressed(),
 2855                cx,
 2856            ) {
 2857                self.show_signature_help(&ShowSignatureHelp, cx);
 2858            }
 2859            self.signature_help_state.set_backspace_pressed(false);
 2860        }
 2861
 2862        result
 2863    }
 2864
 2865    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2866    where
 2867        I: IntoIterator<Item = (Range<S>, T)>,
 2868        S: ToOffset,
 2869        T: Into<Arc<str>>,
 2870    {
 2871        if self.read_only(cx) {
 2872            return;
 2873        }
 2874
 2875        self.buffer
 2876            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2877    }
 2878
 2879    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2880    where
 2881        I: IntoIterator<Item = (Range<S>, T)>,
 2882        S: ToOffset,
 2883        T: Into<Arc<str>>,
 2884    {
 2885        if self.read_only(cx) {
 2886            return;
 2887        }
 2888
 2889        self.buffer.update(cx, |buffer, cx| {
 2890            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2891        });
 2892    }
 2893
 2894    pub fn edit_with_block_indent<I, S, T>(
 2895        &mut self,
 2896        edits: I,
 2897        original_indent_columns: Vec<u32>,
 2898        cx: &mut ViewContext<Self>,
 2899    ) where
 2900        I: IntoIterator<Item = (Range<S>, T)>,
 2901        S: ToOffset,
 2902        T: Into<Arc<str>>,
 2903    {
 2904        if self.read_only(cx) {
 2905            return;
 2906        }
 2907
 2908        self.buffer.update(cx, |buffer, cx| {
 2909            buffer.edit(
 2910                edits,
 2911                Some(AutoindentMode::Block {
 2912                    original_indent_columns,
 2913                }),
 2914                cx,
 2915            )
 2916        });
 2917    }
 2918
 2919    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2920        self.hide_context_menu(cx);
 2921
 2922        match phase {
 2923            SelectPhase::Begin {
 2924                position,
 2925                add,
 2926                click_count,
 2927            } => self.begin_selection(position, add, click_count, cx),
 2928            SelectPhase::BeginColumnar {
 2929                position,
 2930                goal_column,
 2931                reset,
 2932            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2933            SelectPhase::Extend {
 2934                position,
 2935                click_count,
 2936            } => self.extend_selection(position, click_count, cx),
 2937            SelectPhase::Update {
 2938                position,
 2939                goal_column,
 2940                scroll_delta,
 2941            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2942            SelectPhase::End => self.end_selection(cx),
 2943        }
 2944    }
 2945
 2946    fn extend_selection(
 2947        &mut self,
 2948        position: DisplayPoint,
 2949        click_count: usize,
 2950        cx: &mut ViewContext<Self>,
 2951    ) {
 2952        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2953        let tail = self.selections.newest::<usize>(cx).tail();
 2954        self.begin_selection(position, false, click_count, cx);
 2955
 2956        let position = position.to_offset(&display_map, Bias::Left);
 2957        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2958
 2959        let mut pending_selection = self
 2960            .selections
 2961            .pending_anchor()
 2962            .expect("extend_selection not called with pending selection");
 2963        if position >= tail {
 2964            pending_selection.start = tail_anchor;
 2965        } else {
 2966            pending_selection.end = tail_anchor;
 2967            pending_selection.reversed = true;
 2968        }
 2969
 2970        let mut pending_mode = self.selections.pending_mode().unwrap();
 2971        match &mut pending_mode {
 2972            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2973            _ => {}
 2974        }
 2975
 2976        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2977            s.set_pending(pending_selection, pending_mode)
 2978        });
 2979    }
 2980
 2981    fn begin_selection(
 2982        &mut self,
 2983        position: DisplayPoint,
 2984        add: bool,
 2985        click_count: usize,
 2986        cx: &mut ViewContext<Self>,
 2987    ) {
 2988        if !self.focus_handle.is_focused(cx) {
 2989            self.last_focused_descendant = None;
 2990            cx.focus(&self.focus_handle);
 2991        }
 2992
 2993        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2994        let buffer = &display_map.buffer_snapshot;
 2995        let newest_selection = self.selections.newest_anchor().clone();
 2996        let position = display_map.clip_point(position, Bias::Left);
 2997
 2998        let start;
 2999        let end;
 3000        let mode;
 3001        let auto_scroll;
 3002        match click_count {
 3003            1 => {
 3004                start = buffer.anchor_before(position.to_point(&display_map));
 3005                end = start;
 3006                mode = SelectMode::Character;
 3007                auto_scroll = true;
 3008            }
 3009            2 => {
 3010                let range = movement::surrounding_word(&display_map, position);
 3011                start = buffer.anchor_before(range.start.to_point(&display_map));
 3012                end = buffer.anchor_before(range.end.to_point(&display_map));
 3013                mode = SelectMode::Word(start..end);
 3014                auto_scroll = true;
 3015            }
 3016            3 => {
 3017                let position = display_map
 3018                    .clip_point(position, Bias::Left)
 3019                    .to_point(&display_map);
 3020                let line_start = display_map.prev_line_boundary(position).0;
 3021                let next_line_start = buffer.clip_point(
 3022                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3023                    Bias::Left,
 3024                );
 3025                start = buffer.anchor_before(line_start);
 3026                end = buffer.anchor_before(next_line_start);
 3027                mode = SelectMode::Line(start..end);
 3028                auto_scroll = true;
 3029            }
 3030            _ => {
 3031                start = buffer.anchor_before(0);
 3032                end = buffer.anchor_before(buffer.len());
 3033                mode = SelectMode::All;
 3034                auto_scroll = false;
 3035            }
 3036        }
 3037
 3038        let point_to_delete: Option<usize> = {
 3039            let selected_points: Vec<Selection<Point>> =
 3040                self.selections.disjoint_in_range(start..end, cx);
 3041
 3042            if !add || click_count > 1 {
 3043                None
 3044            } else if !selected_points.is_empty() {
 3045                Some(selected_points[0].id)
 3046            } else {
 3047                let clicked_point_already_selected =
 3048                    self.selections.disjoint.iter().find(|selection| {
 3049                        selection.start.to_point(buffer) == start.to_point(buffer)
 3050                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3051                    });
 3052
 3053                clicked_point_already_selected.map(|selection| selection.id)
 3054            }
 3055        };
 3056
 3057        let selections_count = self.selections.count();
 3058
 3059        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 3060            if let Some(point_to_delete) = point_to_delete {
 3061                s.delete(point_to_delete);
 3062
 3063                if selections_count == 1 {
 3064                    s.set_pending_anchor_range(start..end, mode);
 3065                }
 3066            } else {
 3067                if !add {
 3068                    s.clear_disjoint();
 3069                } else if click_count > 1 {
 3070                    s.delete(newest_selection.id)
 3071                }
 3072
 3073                s.set_pending_anchor_range(start..end, mode);
 3074            }
 3075        });
 3076    }
 3077
 3078    fn begin_columnar_selection(
 3079        &mut self,
 3080        position: DisplayPoint,
 3081        goal_column: u32,
 3082        reset: bool,
 3083        cx: &mut ViewContext<Self>,
 3084    ) {
 3085        if !self.focus_handle.is_focused(cx) {
 3086            self.last_focused_descendant = None;
 3087            cx.focus(&self.focus_handle);
 3088        }
 3089
 3090        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3091
 3092        if reset {
 3093            let pointer_position = display_map
 3094                .buffer_snapshot
 3095                .anchor_before(position.to_point(&display_map));
 3096
 3097            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 3098                s.clear_disjoint();
 3099                s.set_pending_anchor_range(
 3100                    pointer_position..pointer_position,
 3101                    SelectMode::Character,
 3102                );
 3103            });
 3104        }
 3105
 3106        let tail = self.selections.newest::<Point>(cx).tail();
 3107        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3108
 3109        if !reset {
 3110            self.select_columns(
 3111                tail.to_display_point(&display_map),
 3112                position,
 3113                goal_column,
 3114                &display_map,
 3115                cx,
 3116            );
 3117        }
 3118    }
 3119
 3120    fn update_selection(
 3121        &mut self,
 3122        position: DisplayPoint,
 3123        goal_column: u32,
 3124        scroll_delta: gpui::Point<f32>,
 3125        cx: &mut ViewContext<Self>,
 3126    ) {
 3127        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3128
 3129        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3130            let tail = tail.to_display_point(&display_map);
 3131            self.select_columns(tail, position, goal_column, &display_map, cx);
 3132        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3133            let buffer = self.buffer.read(cx).snapshot(cx);
 3134            let head;
 3135            let tail;
 3136            let mode = self.selections.pending_mode().unwrap();
 3137            match &mode {
 3138                SelectMode::Character => {
 3139                    head = position.to_point(&display_map);
 3140                    tail = pending.tail().to_point(&buffer);
 3141                }
 3142                SelectMode::Word(original_range) => {
 3143                    let original_display_range = original_range.start.to_display_point(&display_map)
 3144                        ..original_range.end.to_display_point(&display_map);
 3145                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3146                        ..original_display_range.end.to_point(&display_map);
 3147                    if movement::is_inside_word(&display_map, position)
 3148                        || original_display_range.contains(&position)
 3149                    {
 3150                        let word_range = movement::surrounding_word(&display_map, position);
 3151                        if word_range.start < original_display_range.start {
 3152                            head = word_range.start.to_point(&display_map);
 3153                        } else {
 3154                            head = word_range.end.to_point(&display_map);
 3155                        }
 3156                    } else {
 3157                        head = position.to_point(&display_map);
 3158                    }
 3159
 3160                    if head <= original_buffer_range.start {
 3161                        tail = original_buffer_range.end;
 3162                    } else {
 3163                        tail = original_buffer_range.start;
 3164                    }
 3165                }
 3166                SelectMode::Line(original_range) => {
 3167                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3168
 3169                    let position = display_map
 3170                        .clip_point(position, Bias::Left)
 3171                        .to_point(&display_map);
 3172                    let line_start = display_map.prev_line_boundary(position).0;
 3173                    let next_line_start = buffer.clip_point(
 3174                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3175                        Bias::Left,
 3176                    );
 3177
 3178                    if line_start < original_range.start {
 3179                        head = line_start
 3180                    } else {
 3181                        head = next_line_start
 3182                    }
 3183
 3184                    if head <= original_range.start {
 3185                        tail = original_range.end;
 3186                    } else {
 3187                        tail = original_range.start;
 3188                    }
 3189                }
 3190                SelectMode::All => {
 3191                    return;
 3192                }
 3193            };
 3194
 3195            if head < tail {
 3196                pending.start = buffer.anchor_before(head);
 3197                pending.end = buffer.anchor_before(tail);
 3198                pending.reversed = true;
 3199            } else {
 3200                pending.start = buffer.anchor_before(tail);
 3201                pending.end = buffer.anchor_before(head);
 3202                pending.reversed = false;
 3203            }
 3204
 3205            self.change_selections(None, cx, |s| {
 3206                s.set_pending(pending, mode);
 3207            });
 3208        } else {
 3209            log::error!("update_selection dispatched with no pending selection");
 3210            return;
 3211        }
 3212
 3213        self.apply_scroll_delta(scroll_delta, cx);
 3214        cx.notify();
 3215    }
 3216
 3217    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3218        self.columnar_selection_tail.take();
 3219        if self.selections.pending_anchor().is_some() {
 3220            let selections = self.selections.all::<usize>(cx);
 3221            self.change_selections(None, cx, |s| {
 3222                s.select(selections);
 3223                s.clear_pending();
 3224            });
 3225        }
 3226    }
 3227
 3228    fn select_columns(
 3229        &mut self,
 3230        tail: DisplayPoint,
 3231        head: DisplayPoint,
 3232        goal_column: u32,
 3233        display_map: &DisplaySnapshot,
 3234        cx: &mut ViewContext<Self>,
 3235    ) {
 3236        let start_row = cmp::min(tail.row(), head.row());
 3237        let end_row = cmp::max(tail.row(), head.row());
 3238        let start_column = cmp::min(tail.column(), goal_column);
 3239        let end_column = cmp::max(tail.column(), goal_column);
 3240        let reversed = start_column < tail.column();
 3241
 3242        let selection_ranges = (start_row.0..=end_row.0)
 3243            .map(DisplayRow)
 3244            .filter_map(|row| {
 3245                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3246                    let start = display_map
 3247                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3248                        .to_point(display_map);
 3249                    let end = display_map
 3250                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3251                        .to_point(display_map);
 3252                    if reversed {
 3253                        Some(end..start)
 3254                    } else {
 3255                        Some(start..end)
 3256                    }
 3257                } else {
 3258                    None
 3259                }
 3260            })
 3261            .collect::<Vec<_>>();
 3262
 3263        self.change_selections(None, cx, |s| {
 3264            s.select_ranges(selection_ranges);
 3265        });
 3266        cx.notify();
 3267    }
 3268
 3269    pub fn has_pending_nonempty_selection(&self) -> bool {
 3270        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3271            Some(Selection { start, end, .. }) => start != end,
 3272            None => false,
 3273        };
 3274
 3275        pending_nonempty_selection
 3276            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3277    }
 3278
 3279    pub fn has_pending_selection(&self) -> bool {
 3280        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3281    }
 3282
 3283    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3284        if self.clear_expanded_diff_hunks(cx) {
 3285            cx.notify();
 3286            return;
 3287        }
 3288        if self.dismiss_menus_and_popups(true, cx) {
 3289            return;
 3290        }
 3291
 3292        if self.mode == EditorMode::Full
 3293            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3294        {
 3295            return;
 3296        }
 3297
 3298        cx.propagate();
 3299    }
 3300
 3301    pub fn dismiss_menus_and_popups(
 3302        &mut self,
 3303        should_report_inline_completion_event: bool,
 3304        cx: &mut ViewContext<Self>,
 3305    ) -> bool {
 3306        if self.take_rename(false, cx).is_some() {
 3307            return true;
 3308        }
 3309
 3310        if hide_hover(self, cx) {
 3311            return true;
 3312        }
 3313
 3314        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3315            return true;
 3316        }
 3317
 3318        if self.hide_context_menu(cx).is_some() {
 3319            return true;
 3320        }
 3321
 3322        if self.mouse_context_menu.take().is_some() {
 3323            return true;
 3324        }
 3325
 3326        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3327            return true;
 3328        }
 3329
 3330        if self.snippet_stack.pop().is_some() {
 3331            return true;
 3332        }
 3333
 3334        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3335            self.dismiss_diagnostics(cx);
 3336            return true;
 3337        }
 3338
 3339        false
 3340    }
 3341
 3342    fn linked_editing_ranges_for(
 3343        &self,
 3344        selection: Range<text::Anchor>,
 3345        cx: &AppContext,
 3346    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3347        if self.linked_edit_ranges.is_empty() {
 3348            return None;
 3349        }
 3350        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3351            selection.end.buffer_id.and_then(|end_buffer_id| {
 3352                if selection.start.buffer_id != Some(end_buffer_id) {
 3353                    return None;
 3354                }
 3355                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3356                let snapshot = buffer.read(cx).snapshot();
 3357                self.linked_edit_ranges
 3358                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3359                    .map(|ranges| (ranges, snapshot, buffer))
 3360            })?;
 3361        use text::ToOffset as TO;
 3362        // find offset from the start of current range to current cursor position
 3363        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3364
 3365        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3366        let start_difference = start_offset - start_byte_offset;
 3367        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3368        let end_difference = end_offset - start_byte_offset;
 3369        // Current range has associated linked ranges.
 3370        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3371        for range in linked_ranges.iter() {
 3372            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3373            let end_offset = start_offset + end_difference;
 3374            let start_offset = start_offset + start_difference;
 3375            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3376                continue;
 3377            }
 3378            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3379                if s.start.buffer_id != selection.start.buffer_id
 3380                    || s.end.buffer_id != selection.end.buffer_id
 3381                {
 3382                    return false;
 3383                }
 3384                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3385                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3386            }) {
 3387                continue;
 3388            }
 3389            let start = buffer_snapshot.anchor_after(start_offset);
 3390            let end = buffer_snapshot.anchor_after(end_offset);
 3391            linked_edits
 3392                .entry(buffer.clone())
 3393                .or_default()
 3394                .push(start..end);
 3395        }
 3396        Some(linked_edits)
 3397    }
 3398
 3399    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3400        let text: Arc<str> = text.into();
 3401
 3402        if self.read_only(cx) {
 3403            return;
 3404        }
 3405
 3406        let selections = self.selections.all_adjusted(cx);
 3407        let mut bracket_inserted = false;
 3408        let mut edits = Vec::new();
 3409        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3410        let mut new_selections = Vec::with_capacity(selections.len());
 3411        let mut new_autoclose_regions = Vec::new();
 3412        let snapshot = self.buffer.read(cx).read(cx);
 3413
 3414        for (selection, autoclose_region) in
 3415            self.selections_with_autoclose_regions(selections, &snapshot)
 3416        {
 3417            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3418                // Determine if the inserted text matches the opening or closing
 3419                // bracket of any of this language's bracket pairs.
 3420                let mut bracket_pair = None;
 3421                let mut is_bracket_pair_start = false;
 3422                let mut is_bracket_pair_end = false;
 3423                if !text.is_empty() {
 3424                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3425                    //  and they are removing the character that triggered IME popup.
 3426                    for (pair, enabled) in scope.brackets() {
 3427                        if !pair.close && !pair.surround {
 3428                            continue;
 3429                        }
 3430
 3431                        if enabled && pair.start.ends_with(text.as_ref()) {
 3432                            let prefix_len = pair.start.len() - text.len();
 3433                            let preceding_text_matches_prefix = prefix_len == 0
 3434                                || (selection.start.column >= (prefix_len as u32)
 3435                                    && snapshot.contains_str_at(
 3436                                        Point::new(
 3437                                            selection.start.row,
 3438                                            selection.start.column - (prefix_len as u32),
 3439                                        ),
 3440                                        &pair.start[..prefix_len],
 3441                                    ));
 3442                            if preceding_text_matches_prefix {
 3443                                bracket_pair = Some(pair.clone());
 3444                                is_bracket_pair_start = true;
 3445                                break;
 3446                            }
 3447                        }
 3448                        if pair.end.as_str() == text.as_ref() {
 3449                            bracket_pair = Some(pair.clone());
 3450                            is_bracket_pair_end = true;
 3451                            break;
 3452                        }
 3453                    }
 3454                }
 3455
 3456                if let Some(bracket_pair) = bracket_pair {
 3457                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3458                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3459                    let auto_surround =
 3460                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3461                    if selection.is_empty() {
 3462                        if is_bracket_pair_start {
 3463                            // If the inserted text is a suffix of an opening bracket and the
 3464                            // selection is preceded by the rest of the opening bracket, then
 3465                            // insert the closing bracket.
 3466                            let following_text_allows_autoclose = snapshot
 3467                                .chars_at(selection.start)
 3468                                .next()
 3469                                .map_or(true, |c| scope.should_autoclose_before(c));
 3470
 3471                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3472                                && bracket_pair.start.len() == 1
 3473                            {
 3474                                let target = bracket_pair.start.chars().next().unwrap();
 3475                                let current_line_count = snapshot
 3476                                    .reversed_chars_at(selection.start)
 3477                                    .take_while(|&c| c != '\n')
 3478                                    .filter(|&c| c == target)
 3479                                    .count();
 3480                                current_line_count % 2 == 1
 3481                            } else {
 3482                                false
 3483                            };
 3484
 3485                            if autoclose
 3486                                && bracket_pair.close
 3487                                && following_text_allows_autoclose
 3488                                && !is_closing_quote
 3489                            {
 3490                                let anchor = snapshot.anchor_before(selection.end);
 3491                                new_selections.push((selection.map(|_| anchor), text.len()));
 3492                                new_autoclose_regions.push((
 3493                                    anchor,
 3494                                    text.len(),
 3495                                    selection.id,
 3496                                    bracket_pair.clone(),
 3497                                ));
 3498                                edits.push((
 3499                                    selection.range(),
 3500                                    format!("{}{}", text, bracket_pair.end).into(),
 3501                                ));
 3502                                bracket_inserted = true;
 3503                                continue;
 3504                            }
 3505                        }
 3506
 3507                        if let Some(region) = autoclose_region {
 3508                            // If the selection is followed by an auto-inserted closing bracket,
 3509                            // then don't insert that closing bracket again; just move the selection
 3510                            // past the closing bracket.
 3511                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3512                                && text.as_ref() == region.pair.end.as_str();
 3513                            if should_skip {
 3514                                let anchor = snapshot.anchor_after(selection.end);
 3515                                new_selections
 3516                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3517                                continue;
 3518                            }
 3519                        }
 3520
 3521                        let always_treat_brackets_as_autoclosed = snapshot
 3522                            .settings_at(selection.start, cx)
 3523                            .always_treat_brackets_as_autoclosed;
 3524                        if always_treat_brackets_as_autoclosed
 3525                            && is_bracket_pair_end
 3526                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3527                        {
 3528                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3529                            // and the inserted text is a closing bracket and the selection is followed
 3530                            // by the closing bracket then move the selection past the closing bracket.
 3531                            let anchor = snapshot.anchor_after(selection.end);
 3532                            new_selections.push((selection.map(|_| anchor), text.len()));
 3533                            continue;
 3534                        }
 3535                    }
 3536                    // If an opening bracket is 1 character long and is typed while
 3537                    // text is selected, then surround that text with the bracket pair.
 3538                    else if auto_surround
 3539                        && bracket_pair.surround
 3540                        && is_bracket_pair_start
 3541                        && bracket_pair.start.chars().count() == 1
 3542                    {
 3543                        edits.push((selection.start..selection.start, text.clone()));
 3544                        edits.push((
 3545                            selection.end..selection.end,
 3546                            bracket_pair.end.as_str().into(),
 3547                        ));
 3548                        bracket_inserted = true;
 3549                        new_selections.push((
 3550                            Selection {
 3551                                id: selection.id,
 3552                                start: snapshot.anchor_after(selection.start),
 3553                                end: snapshot.anchor_before(selection.end),
 3554                                reversed: selection.reversed,
 3555                                goal: selection.goal,
 3556                            },
 3557                            0,
 3558                        ));
 3559                        continue;
 3560                    }
 3561                }
 3562            }
 3563
 3564            if self.auto_replace_emoji_shortcode
 3565                && selection.is_empty()
 3566                && text.as_ref().ends_with(':')
 3567            {
 3568                if let Some(possible_emoji_short_code) =
 3569                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3570                {
 3571                    if !possible_emoji_short_code.is_empty() {
 3572                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3573                            let emoji_shortcode_start = Point::new(
 3574                                selection.start.row,
 3575                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3576                            );
 3577
 3578                            // Remove shortcode from buffer
 3579                            edits.push((
 3580                                emoji_shortcode_start..selection.start,
 3581                                "".to_string().into(),
 3582                            ));
 3583                            new_selections.push((
 3584                                Selection {
 3585                                    id: selection.id,
 3586                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3587                                    end: snapshot.anchor_before(selection.start),
 3588                                    reversed: selection.reversed,
 3589                                    goal: selection.goal,
 3590                                },
 3591                                0,
 3592                            ));
 3593
 3594                            // Insert emoji
 3595                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3596                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3597                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3598
 3599                            continue;
 3600                        }
 3601                    }
 3602                }
 3603            }
 3604
 3605            // If not handling any auto-close operation, then just replace the selected
 3606            // text with the given input and move the selection to the end of the
 3607            // newly inserted text.
 3608            let anchor = snapshot.anchor_after(selection.end);
 3609            if !self.linked_edit_ranges.is_empty() {
 3610                let start_anchor = snapshot.anchor_before(selection.start);
 3611
 3612                let is_word_char = text.chars().next().map_or(true, |char| {
 3613                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3614                    classifier.is_word(char)
 3615                });
 3616
 3617                if is_word_char {
 3618                    if let Some(ranges) = self
 3619                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3620                    {
 3621                        for (buffer, edits) in ranges {
 3622                            linked_edits
 3623                                .entry(buffer.clone())
 3624                                .or_default()
 3625                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3626                        }
 3627                    }
 3628                }
 3629            }
 3630
 3631            new_selections.push((selection.map(|_| anchor), 0));
 3632            edits.push((selection.start..selection.end, text.clone()));
 3633        }
 3634
 3635        drop(snapshot);
 3636
 3637        self.transact(cx, |this, cx| {
 3638            this.buffer.update(cx, |buffer, cx| {
 3639                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3640            });
 3641            for (buffer, edits) in linked_edits {
 3642                buffer.update(cx, |buffer, cx| {
 3643                    let snapshot = buffer.snapshot();
 3644                    let edits = edits
 3645                        .into_iter()
 3646                        .map(|(range, text)| {
 3647                            use text::ToPoint as TP;
 3648                            let end_point = TP::to_point(&range.end, &snapshot);
 3649                            let start_point = TP::to_point(&range.start, &snapshot);
 3650                            (start_point..end_point, text)
 3651                        })
 3652                        .sorted_by_key(|(range, _)| range.start)
 3653                        .collect::<Vec<_>>();
 3654                    buffer.edit(edits, None, cx);
 3655                })
 3656            }
 3657            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3658            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3659            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3660            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3661                .zip(new_selection_deltas)
 3662                .map(|(selection, delta)| Selection {
 3663                    id: selection.id,
 3664                    start: selection.start + delta,
 3665                    end: selection.end + delta,
 3666                    reversed: selection.reversed,
 3667                    goal: SelectionGoal::None,
 3668                })
 3669                .collect::<Vec<_>>();
 3670
 3671            let mut i = 0;
 3672            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3673                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3674                let start = map.buffer_snapshot.anchor_before(position);
 3675                let end = map.buffer_snapshot.anchor_after(position);
 3676                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3677                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3678                        Ordering::Less => i += 1,
 3679                        Ordering::Greater => break,
 3680                        Ordering::Equal => {
 3681                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3682                                Ordering::Less => i += 1,
 3683                                Ordering::Equal => break,
 3684                                Ordering::Greater => break,
 3685                            }
 3686                        }
 3687                    }
 3688                }
 3689                this.autoclose_regions.insert(
 3690                    i,
 3691                    AutocloseRegion {
 3692                        selection_id,
 3693                        range: start..end,
 3694                        pair,
 3695                    },
 3696                );
 3697            }
 3698
 3699            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3700            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3701                s.select(new_selections)
 3702            });
 3703
 3704            if !bracket_inserted {
 3705                if let Some(on_type_format_task) =
 3706                    this.trigger_on_type_formatting(text.to_string(), cx)
 3707                {
 3708                    on_type_format_task.detach_and_log_err(cx);
 3709                }
 3710            }
 3711
 3712            let editor_settings = EditorSettings::get_global(cx);
 3713            if bracket_inserted
 3714                && (editor_settings.auto_signature_help
 3715                    || editor_settings.show_signature_help_after_edits)
 3716            {
 3717                this.show_signature_help(&ShowSignatureHelp, cx);
 3718            }
 3719
 3720            let trigger_in_words = !had_active_inline_completion;
 3721            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3722            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3723            this.refresh_inline_completion(true, false, cx);
 3724        });
 3725    }
 3726
 3727    fn find_possible_emoji_shortcode_at_position(
 3728        snapshot: &MultiBufferSnapshot,
 3729        position: Point,
 3730    ) -> Option<String> {
 3731        let mut chars = Vec::new();
 3732        let mut found_colon = false;
 3733        for char in snapshot.reversed_chars_at(position).take(100) {
 3734            // Found a possible emoji shortcode in the middle of the buffer
 3735            if found_colon {
 3736                if char.is_whitespace() {
 3737                    chars.reverse();
 3738                    return Some(chars.iter().collect());
 3739                }
 3740                // If the previous character is not a whitespace, we are in the middle of a word
 3741                // and we only want to complete the shortcode if the word is made up of other emojis
 3742                let mut containing_word = String::new();
 3743                for ch in snapshot
 3744                    .reversed_chars_at(position)
 3745                    .skip(chars.len() + 1)
 3746                    .take(100)
 3747                {
 3748                    if ch.is_whitespace() {
 3749                        break;
 3750                    }
 3751                    containing_word.push(ch);
 3752                }
 3753                let containing_word = containing_word.chars().rev().collect::<String>();
 3754                if util::word_consists_of_emojis(containing_word.as_str()) {
 3755                    chars.reverse();
 3756                    return Some(chars.iter().collect());
 3757                }
 3758            }
 3759
 3760            if char.is_whitespace() || !char.is_ascii() {
 3761                return None;
 3762            }
 3763            if char == ':' {
 3764                found_colon = true;
 3765            } else {
 3766                chars.push(char);
 3767            }
 3768        }
 3769        // Found a possible emoji shortcode at the beginning of the buffer
 3770        chars.reverse();
 3771        Some(chars.iter().collect())
 3772    }
 3773
 3774    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3775        self.transact(cx, |this, cx| {
 3776            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3777                let selections = this.selections.all::<usize>(cx);
 3778                let multi_buffer = this.buffer.read(cx);
 3779                let buffer = multi_buffer.snapshot(cx);
 3780                selections
 3781                    .iter()
 3782                    .map(|selection| {
 3783                        let start_point = selection.start.to_point(&buffer);
 3784                        let mut indent =
 3785                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3786                        indent.len = cmp::min(indent.len, start_point.column);
 3787                        let start = selection.start;
 3788                        let end = selection.end;
 3789                        let selection_is_empty = start == end;
 3790                        let language_scope = buffer.language_scope_at(start);
 3791                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3792                            &language_scope
 3793                        {
 3794                            let leading_whitespace_len = buffer
 3795                                .reversed_chars_at(start)
 3796                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3797                                .map(|c| c.len_utf8())
 3798                                .sum::<usize>();
 3799
 3800                            let trailing_whitespace_len = buffer
 3801                                .chars_at(end)
 3802                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3803                                .map(|c| c.len_utf8())
 3804                                .sum::<usize>();
 3805
 3806                            let insert_extra_newline =
 3807                                language.brackets().any(|(pair, enabled)| {
 3808                                    let pair_start = pair.start.trim_end();
 3809                                    let pair_end = pair.end.trim_start();
 3810
 3811                                    enabled
 3812                                        && pair.newline
 3813                                        && buffer.contains_str_at(
 3814                                            end + trailing_whitespace_len,
 3815                                            pair_end,
 3816                                        )
 3817                                        && buffer.contains_str_at(
 3818                                            (start - leading_whitespace_len)
 3819                                                .saturating_sub(pair_start.len()),
 3820                                            pair_start,
 3821                                        )
 3822                                });
 3823
 3824                            // Comment extension on newline is allowed only for cursor selections
 3825                            let comment_delimiter = maybe!({
 3826                                if !selection_is_empty {
 3827                                    return None;
 3828                                }
 3829
 3830                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3831                                    return None;
 3832                                }
 3833
 3834                                let delimiters = language.line_comment_prefixes();
 3835                                let max_len_of_delimiter =
 3836                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3837                                let (snapshot, range) =
 3838                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3839
 3840                                let mut index_of_first_non_whitespace = 0;
 3841                                let comment_candidate = snapshot
 3842                                    .chars_for_range(range)
 3843                                    .skip_while(|c| {
 3844                                        let should_skip = c.is_whitespace();
 3845                                        if should_skip {
 3846                                            index_of_first_non_whitespace += 1;
 3847                                        }
 3848                                        should_skip
 3849                                    })
 3850                                    .take(max_len_of_delimiter)
 3851                                    .collect::<String>();
 3852                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3853                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3854                                })?;
 3855                                let cursor_is_placed_after_comment_marker =
 3856                                    index_of_first_non_whitespace + comment_prefix.len()
 3857                                        <= start_point.column as usize;
 3858                                if cursor_is_placed_after_comment_marker {
 3859                                    Some(comment_prefix.clone())
 3860                                } else {
 3861                                    None
 3862                                }
 3863                            });
 3864                            (comment_delimiter, insert_extra_newline)
 3865                        } else {
 3866                            (None, false)
 3867                        };
 3868
 3869                        let capacity_for_delimiter = comment_delimiter
 3870                            .as_deref()
 3871                            .map(str::len)
 3872                            .unwrap_or_default();
 3873                        let mut new_text =
 3874                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3875                        new_text.push('\n');
 3876                        new_text.extend(indent.chars());
 3877                        if let Some(delimiter) = &comment_delimiter {
 3878                            new_text.push_str(delimiter);
 3879                        }
 3880                        if insert_extra_newline {
 3881                            new_text = new_text.repeat(2);
 3882                        }
 3883
 3884                        let anchor = buffer.anchor_after(end);
 3885                        let new_selection = selection.map(|_| anchor);
 3886                        (
 3887                            (start..end, new_text),
 3888                            (insert_extra_newline, new_selection),
 3889                        )
 3890                    })
 3891                    .unzip()
 3892            };
 3893
 3894            this.edit_with_autoindent(edits, cx);
 3895            let buffer = this.buffer.read(cx).snapshot(cx);
 3896            let new_selections = selection_fixup_info
 3897                .into_iter()
 3898                .map(|(extra_newline_inserted, new_selection)| {
 3899                    let mut cursor = new_selection.end.to_point(&buffer);
 3900                    if extra_newline_inserted {
 3901                        cursor.row -= 1;
 3902                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3903                    }
 3904                    new_selection.map(|_| cursor)
 3905                })
 3906                .collect();
 3907
 3908            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3909            this.refresh_inline_completion(true, false, cx);
 3910        });
 3911    }
 3912
 3913    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3914        let buffer = self.buffer.read(cx);
 3915        let snapshot = buffer.snapshot(cx);
 3916
 3917        let mut edits = Vec::new();
 3918        let mut rows = Vec::new();
 3919
 3920        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3921            let cursor = selection.head();
 3922            let row = cursor.row;
 3923
 3924            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3925
 3926            let newline = "\n".to_string();
 3927            edits.push((start_of_line..start_of_line, newline));
 3928
 3929            rows.push(row + rows_inserted as u32);
 3930        }
 3931
 3932        self.transact(cx, |editor, cx| {
 3933            editor.edit(edits, cx);
 3934
 3935            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3936                let mut index = 0;
 3937                s.move_cursors_with(|map, _, _| {
 3938                    let row = rows[index];
 3939                    index += 1;
 3940
 3941                    let point = Point::new(row, 0);
 3942                    let boundary = map.next_line_boundary(point).1;
 3943                    let clipped = map.clip_point(boundary, Bias::Left);
 3944
 3945                    (clipped, SelectionGoal::None)
 3946                });
 3947            });
 3948
 3949            let mut indent_edits = Vec::new();
 3950            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3951            for row in rows {
 3952                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3953                for (row, indent) in indents {
 3954                    if indent.len == 0 {
 3955                        continue;
 3956                    }
 3957
 3958                    let text = match indent.kind {
 3959                        IndentKind::Space => " ".repeat(indent.len as usize),
 3960                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3961                    };
 3962                    let point = Point::new(row.0, 0);
 3963                    indent_edits.push((point..point, text));
 3964                }
 3965            }
 3966            editor.edit(indent_edits, cx);
 3967        });
 3968    }
 3969
 3970    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3971        let buffer = self.buffer.read(cx);
 3972        let snapshot = buffer.snapshot(cx);
 3973
 3974        let mut edits = Vec::new();
 3975        let mut rows = Vec::new();
 3976        let mut rows_inserted = 0;
 3977
 3978        for selection in self.selections.all_adjusted(cx) {
 3979            let cursor = selection.head();
 3980            let row = cursor.row;
 3981
 3982            let point = Point::new(row + 1, 0);
 3983            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3984
 3985            let newline = "\n".to_string();
 3986            edits.push((start_of_line..start_of_line, newline));
 3987
 3988            rows_inserted += 1;
 3989            rows.push(row + rows_inserted);
 3990        }
 3991
 3992        self.transact(cx, |editor, cx| {
 3993            editor.edit(edits, cx);
 3994
 3995            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3996                let mut index = 0;
 3997                s.move_cursors_with(|map, _, _| {
 3998                    let row = rows[index];
 3999                    index += 1;
 4000
 4001                    let point = Point::new(row, 0);
 4002                    let boundary = map.next_line_boundary(point).1;
 4003                    let clipped = map.clip_point(boundary, Bias::Left);
 4004
 4005                    (clipped, SelectionGoal::None)
 4006                });
 4007            });
 4008
 4009            let mut indent_edits = Vec::new();
 4010            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4011            for row in rows {
 4012                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4013                for (row, indent) in indents {
 4014                    if indent.len == 0 {
 4015                        continue;
 4016                    }
 4017
 4018                    let text = match indent.kind {
 4019                        IndentKind::Space => " ".repeat(indent.len as usize),
 4020                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4021                    };
 4022                    let point = Point::new(row.0, 0);
 4023                    indent_edits.push((point..point, text));
 4024                }
 4025            }
 4026            editor.edit(indent_edits, cx);
 4027        });
 4028    }
 4029
 4030    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 4031        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4032            original_indent_columns: Vec::new(),
 4033        });
 4034        self.insert_with_autoindent_mode(text, autoindent, cx);
 4035    }
 4036
 4037    fn insert_with_autoindent_mode(
 4038        &mut self,
 4039        text: &str,
 4040        autoindent_mode: Option<AutoindentMode>,
 4041        cx: &mut ViewContext<Self>,
 4042    ) {
 4043        if self.read_only(cx) {
 4044            return;
 4045        }
 4046
 4047        let text: Arc<str> = text.into();
 4048        self.transact(cx, |this, cx| {
 4049            let old_selections = this.selections.all_adjusted(cx);
 4050            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4051                let anchors = {
 4052                    let snapshot = buffer.read(cx);
 4053                    old_selections
 4054                        .iter()
 4055                        .map(|s| {
 4056                            let anchor = snapshot.anchor_after(s.head());
 4057                            s.map(|_| anchor)
 4058                        })
 4059                        .collect::<Vec<_>>()
 4060                };
 4061                buffer.edit(
 4062                    old_selections
 4063                        .iter()
 4064                        .map(|s| (s.start..s.end, text.clone())),
 4065                    autoindent_mode,
 4066                    cx,
 4067                );
 4068                anchors
 4069            });
 4070
 4071            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4072                s.select_anchors(selection_anchors);
 4073            })
 4074        });
 4075    }
 4076
 4077    fn trigger_completion_on_input(
 4078        &mut self,
 4079        text: &str,
 4080        trigger_in_words: bool,
 4081        cx: &mut ViewContext<Self>,
 4082    ) {
 4083        if self.is_completion_trigger(text, trigger_in_words, cx) {
 4084            self.show_completions(
 4085                &ShowCompletions {
 4086                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4087                },
 4088                cx,
 4089            );
 4090        } else {
 4091            self.hide_context_menu(cx);
 4092        }
 4093    }
 4094
 4095    fn is_completion_trigger(
 4096        &self,
 4097        text: &str,
 4098        trigger_in_words: bool,
 4099        cx: &mut ViewContext<Self>,
 4100    ) -> bool {
 4101        let position = self.selections.newest_anchor().head();
 4102        let multibuffer = self.buffer.read(cx);
 4103        let Some(buffer) = position
 4104            .buffer_id
 4105            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4106        else {
 4107            return false;
 4108        };
 4109
 4110        if let Some(completion_provider) = &self.completion_provider {
 4111            completion_provider.is_completion_trigger(
 4112                &buffer,
 4113                position.text_anchor,
 4114                text,
 4115                trigger_in_words,
 4116                cx,
 4117            )
 4118        } else {
 4119            false
 4120        }
 4121    }
 4122
 4123    /// If any empty selections is touching the start of its innermost containing autoclose
 4124    /// region, expand it to select the brackets.
 4125    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4126        let selections = self.selections.all::<usize>(cx);
 4127        let buffer = self.buffer.read(cx).read(cx);
 4128        let new_selections = self
 4129            .selections_with_autoclose_regions(selections, &buffer)
 4130            .map(|(mut selection, region)| {
 4131                if !selection.is_empty() {
 4132                    return selection;
 4133                }
 4134
 4135                if let Some(region) = region {
 4136                    let mut range = region.range.to_offset(&buffer);
 4137                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4138                        range.start -= region.pair.start.len();
 4139                        if buffer.contains_str_at(range.start, &region.pair.start)
 4140                            && buffer.contains_str_at(range.end, &region.pair.end)
 4141                        {
 4142                            range.end += region.pair.end.len();
 4143                            selection.start = range.start;
 4144                            selection.end = range.end;
 4145
 4146                            return selection;
 4147                        }
 4148                    }
 4149                }
 4150
 4151                let always_treat_brackets_as_autoclosed = buffer
 4152                    .settings_at(selection.start, cx)
 4153                    .always_treat_brackets_as_autoclosed;
 4154
 4155                if !always_treat_brackets_as_autoclosed {
 4156                    return selection;
 4157                }
 4158
 4159                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4160                    for (pair, enabled) in scope.brackets() {
 4161                        if !enabled || !pair.close {
 4162                            continue;
 4163                        }
 4164
 4165                        if buffer.contains_str_at(selection.start, &pair.end) {
 4166                            let pair_start_len = pair.start.len();
 4167                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 4168                            {
 4169                                selection.start -= pair_start_len;
 4170                                selection.end += pair.end.len();
 4171
 4172                                return selection;
 4173                            }
 4174                        }
 4175                    }
 4176                }
 4177
 4178                selection
 4179            })
 4180            .collect();
 4181
 4182        drop(buffer);
 4183        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4184    }
 4185
 4186    /// Iterate the given selections, and for each one, find the smallest surrounding
 4187    /// autoclose region. This uses the ordering of the selections and the autoclose
 4188    /// regions to avoid repeated comparisons.
 4189    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4190        &'a self,
 4191        selections: impl IntoIterator<Item = Selection<D>>,
 4192        buffer: &'a MultiBufferSnapshot,
 4193    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4194        let mut i = 0;
 4195        let mut regions = self.autoclose_regions.as_slice();
 4196        selections.into_iter().map(move |selection| {
 4197            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4198
 4199            let mut enclosing = None;
 4200            while let Some(pair_state) = regions.get(i) {
 4201                if pair_state.range.end.to_offset(buffer) < range.start {
 4202                    regions = &regions[i + 1..];
 4203                    i = 0;
 4204                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4205                    break;
 4206                } else {
 4207                    if pair_state.selection_id == selection.id {
 4208                        enclosing = Some(pair_state);
 4209                    }
 4210                    i += 1;
 4211                }
 4212            }
 4213
 4214            (selection, enclosing)
 4215        })
 4216    }
 4217
 4218    /// Remove any autoclose regions that no longer contain their selection.
 4219    fn invalidate_autoclose_regions(
 4220        &mut self,
 4221        mut selections: &[Selection<Anchor>],
 4222        buffer: &MultiBufferSnapshot,
 4223    ) {
 4224        self.autoclose_regions.retain(|state| {
 4225            let mut i = 0;
 4226            while let Some(selection) = selections.get(i) {
 4227                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4228                    selections = &selections[1..];
 4229                    continue;
 4230                }
 4231                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4232                    break;
 4233                }
 4234                if selection.id == state.selection_id {
 4235                    return true;
 4236                } else {
 4237                    i += 1;
 4238                }
 4239            }
 4240            false
 4241        });
 4242    }
 4243
 4244    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4245        let offset = position.to_offset(buffer);
 4246        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4247        if offset > word_range.start && kind == Some(CharKind::Word) {
 4248            Some(
 4249                buffer
 4250                    .text_for_range(word_range.start..offset)
 4251                    .collect::<String>(),
 4252            )
 4253        } else {
 4254            None
 4255        }
 4256    }
 4257
 4258    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4259        self.refresh_inlay_hints(
 4260            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4261            cx,
 4262        );
 4263    }
 4264
 4265    pub fn inlay_hints_enabled(&self) -> bool {
 4266        self.inlay_hint_cache.enabled
 4267    }
 4268
 4269    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4270        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4271            return;
 4272        }
 4273
 4274        let reason_description = reason.description();
 4275        let ignore_debounce = matches!(
 4276            reason,
 4277            InlayHintRefreshReason::SettingsChange(_)
 4278                | InlayHintRefreshReason::Toggle(_)
 4279                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4280        );
 4281        let (invalidate_cache, required_languages) = match reason {
 4282            InlayHintRefreshReason::Toggle(enabled) => {
 4283                self.inlay_hint_cache.enabled = enabled;
 4284                if enabled {
 4285                    (InvalidationStrategy::RefreshRequested, None)
 4286                } else {
 4287                    self.inlay_hint_cache.clear();
 4288                    self.splice_inlays(
 4289                        self.visible_inlay_hints(cx)
 4290                            .iter()
 4291                            .map(|inlay| inlay.id)
 4292                            .collect(),
 4293                        Vec::new(),
 4294                        cx,
 4295                    );
 4296                    return;
 4297                }
 4298            }
 4299            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4300                match self.inlay_hint_cache.update_settings(
 4301                    &self.buffer,
 4302                    new_settings,
 4303                    self.visible_inlay_hints(cx),
 4304                    cx,
 4305                ) {
 4306                    ControlFlow::Break(Some(InlaySplice {
 4307                        to_remove,
 4308                        to_insert,
 4309                    })) => {
 4310                        self.splice_inlays(to_remove, to_insert, cx);
 4311                        return;
 4312                    }
 4313                    ControlFlow::Break(None) => return,
 4314                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4315                }
 4316            }
 4317            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4318                if let Some(InlaySplice {
 4319                    to_remove,
 4320                    to_insert,
 4321                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4322                {
 4323                    self.splice_inlays(to_remove, to_insert, cx);
 4324                }
 4325                return;
 4326            }
 4327            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4328            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4329                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4330            }
 4331            InlayHintRefreshReason::RefreshRequested => {
 4332                (InvalidationStrategy::RefreshRequested, None)
 4333            }
 4334        };
 4335
 4336        if let Some(InlaySplice {
 4337            to_remove,
 4338            to_insert,
 4339        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4340            reason_description,
 4341            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4342            invalidate_cache,
 4343            ignore_debounce,
 4344            cx,
 4345        ) {
 4346            self.splice_inlays(to_remove, to_insert, cx);
 4347        }
 4348    }
 4349
 4350    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4351        self.display_map
 4352            .read(cx)
 4353            .current_inlays()
 4354            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4355            .cloned()
 4356            .collect()
 4357    }
 4358
 4359    pub fn excerpts_for_inlay_hints_query(
 4360        &self,
 4361        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4362        cx: &mut ViewContext<Editor>,
 4363    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4364        let Some(project) = self.project.as_ref() else {
 4365            return HashMap::default();
 4366        };
 4367        let project = project.read(cx);
 4368        let multi_buffer = self.buffer().read(cx);
 4369        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4370        let multi_buffer_visible_start = self
 4371            .scroll_manager
 4372            .anchor()
 4373            .anchor
 4374            .to_point(&multi_buffer_snapshot);
 4375        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4376            multi_buffer_visible_start
 4377                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4378            Bias::Left,
 4379        );
 4380        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4381        multi_buffer
 4382            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4383            .into_iter()
 4384            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4385            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4386                let buffer = buffer_handle.read(cx);
 4387                let buffer_file = project::File::from_dyn(buffer.file())?;
 4388                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4389                let worktree_entry = buffer_worktree
 4390                    .read(cx)
 4391                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4392                if worktree_entry.is_ignored {
 4393                    return None;
 4394                }
 4395
 4396                let language = buffer.language()?;
 4397                if let Some(restrict_to_languages) = restrict_to_languages {
 4398                    if !restrict_to_languages.contains(language) {
 4399                        return None;
 4400                    }
 4401                }
 4402                Some((
 4403                    excerpt_id,
 4404                    (
 4405                        buffer_handle,
 4406                        buffer.version().clone(),
 4407                        excerpt_visible_range,
 4408                    ),
 4409                ))
 4410            })
 4411            .collect()
 4412    }
 4413
 4414    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4415        TextLayoutDetails {
 4416            text_system: cx.text_system().clone(),
 4417            editor_style: self.style.clone().unwrap(),
 4418            rem_size: cx.rem_size(),
 4419            scroll_anchor: self.scroll_manager.anchor(),
 4420            visible_rows: self.visible_line_count(),
 4421            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4422        }
 4423    }
 4424
 4425    fn splice_inlays(
 4426        &self,
 4427        to_remove: Vec<InlayId>,
 4428        to_insert: Vec<Inlay>,
 4429        cx: &mut ViewContext<Self>,
 4430    ) {
 4431        self.display_map.update(cx, |display_map, cx| {
 4432            display_map.splice_inlays(to_remove, to_insert, cx);
 4433        });
 4434        cx.notify();
 4435    }
 4436
 4437    fn trigger_on_type_formatting(
 4438        &self,
 4439        input: String,
 4440        cx: &mut ViewContext<Self>,
 4441    ) -> Option<Task<Result<()>>> {
 4442        if input.len() != 1 {
 4443            return None;
 4444        }
 4445
 4446        let project = self.project.as_ref()?;
 4447        let position = self.selections.newest_anchor().head();
 4448        let (buffer, buffer_position) = self
 4449            .buffer
 4450            .read(cx)
 4451            .text_anchor_for_position(position, cx)?;
 4452
 4453        let settings = language_settings::language_settings(
 4454            buffer
 4455                .read(cx)
 4456                .language_at(buffer_position)
 4457                .map(|l| l.name()),
 4458            buffer.read(cx).file(),
 4459            cx,
 4460        );
 4461        if !settings.use_on_type_format {
 4462            return None;
 4463        }
 4464
 4465        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4466        // hence we do LSP request & edit on host side only — add formats to host's history.
 4467        let push_to_lsp_host_history = true;
 4468        // If this is not the host, append its history with new edits.
 4469        let push_to_client_history = project.read(cx).is_via_collab();
 4470
 4471        let on_type_formatting = project.update(cx, |project, cx| {
 4472            project.on_type_format(
 4473                buffer.clone(),
 4474                buffer_position,
 4475                input,
 4476                push_to_lsp_host_history,
 4477                cx,
 4478            )
 4479        });
 4480        Some(cx.spawn(|editor, mut cx| async move {
 4481            if let Some(transaction) = on_type_formatting.await? {
 4482                if push_to_client_history {
 4483                    buffer
 4484                        .update(&mut cx, |buffer, _| {
 4485                            buffer.push_transaction(transaction, Instant::now());
 4486                        })
 4487                        .ok();
 4488                }
 4489                editor.update(&mut cx, |editor, cx| {
 4490                    editor.refresh_document_highlights(cx);
 4491                })?;
 4492            }
 4493            Ok(())
 4494        }))
 4495    }
 4496
 4497    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4498        if self.pending_rename.is_some() {
 4499            return;
 4500        }
 4501
 4502        let Some(provider) = self.completion_provider.as_ref() else {
 4503            return;
 4504        };
 4505
 4506        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4507            return;
 4508        }
 4509
 4510        let position = self.selections.newest_anchor().head();
 4511        let (buffer, buffer_position) =
 4512            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4513                output
 4514            } else {
 4515                return;
 4516            };
 4517
 4518        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4519        let is_followup_invoke = {
 4520            let context_menu_state = self.context_menu.read();
 4521            matches!(
 4522                context_menu_state.deref(),
 4523                Some(ContextMenu::Completions(_))
 4524            )
 4525        };
 4526        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4527            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4528            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4529                CompletionTriggerKind::TRIGGER_CHARACTER
 4530            }
 4531
 4532            _ => CompletionTriggerKind::INVOKED,
 4533        };
 4534        let completion_context = CompletionContext {
 4535            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4536                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4537                    Some(String::from(trigger))
 4538                } else {
 4539                    None
 4540                }
 4541            }),
 4542            trigger_kind,
 4543        };
 4544        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4545        let sort_completions = provider.sort_completions();
 4546
 4547        let id = post_inc(&mut self.next_completion_id);
 4548        let task = cx.spawn(|this, mut cx| {
 4549            async move {
 4550                this.update(&mut cx, |this, _| {
 4551                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4552                })?;
 4553                let completions = completions.await.log_err();
 4554                let menu = if let Some(completions) = completions {
 4555                    let mut menu = CompletionsMenu::new(
 4556                        id,
 4557                        sort_completions,
 4558                        position,
 4559                        buffer.clone(),
 4560                        completions.into(),
 4561                    );
 4562                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4563                        .await;
 4564
 4565                    if menu.matches.is_empty() {
 4566                        None
 4567                    } else {
 4568                        this.update(&mut cx, |editor, cx| {
 4569                            let completions = menu.completions.clone();
 4570                            let matches = menu.matches.clone();
 4571
 4572                            let delay_ms = EditorSettings::get_global(cx)
 4573                                .completion_documentation_secondary_query_debounce;
 4574                            let delay = Duration::from_millis(delay_ms);
 4575                            editor
 4576                                .completion_documentation_pre_resolve_debounce
 4577                                .fire_new(delay, cx, |editor, cx| {
 4578                                    CompletionsMenu::pre_resolve_completion_documentation(
 4579                                        buffer,
 4580                                        completions,
 4581                                        matches,
 4582                                        editor,
 4583                                        cx,
 4584                                    )
 4585                                });
 4586                        })
 4587                        .ok();
 4588                        Some(menu)
 4589                    }
 4590                } else {
 4591                    None
 4592                };
 4593
 4594                this.update(&mut cx, |this, cx| {
 4595                    let mut context_menu = this.context_menu.write();
 4596                    match context_menu.as_ref() {
 4597                        None => {}
 4598
 4599                        Some(ContextMenu::Completions(prev_menu)) => {
 4600                            if prev_menu.id > id {
 4601                                return;
 4602                            }
 4603                        }
 4604
 4605                        _ => return,
 4606                    }
 4607
 4608                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4609                        let menu = menu.unwrap();
 4610                        *context_menu = Some(ContextMenu::Completions(menu));
 4611                        drop(context_menu);
 4612                        this.discard_inline_completion(false, cx);
 4613                        cx.notify();
 4614                    } else if this.completion_tasks.len() <= 1 {
 4615                        // If there are no more completion tasks and the last menu was
 4616                        // empty, we should hide it. If it was already hidden, we should
 4617                        // also show the copilot completion when available.
 4618                        drop(context_menu);
 4619                        if this.hide_context_menu(cx).is_none() {
 4620                            this.update_visible_inline_completion(cx);
 4621                        }
 4622                    }
 4623                })?;
 4624
 4625                Ok::<_, anyhow::Error>(())
 4626            }
 4627            .log_err()
 4628        });
 4629
 4630        self.completion_tasks.push((id, task));
 4631    }
 4632
 4633    pub fn confirm_completion(
 4634        &mut self,
 4635        action: &ConfirmCompletion,
 4636        cx: &mut ViewContext<Self>,
 4637    ) -> Option<Task<Result<()>>> {
 4638        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4639    }
 4640
 4641    pub fn compose_completion(
 4642        &mut self,
 4643        action: &ComposeCompletion,
 4644        cx: &mut ViewContext<Self>,
 4645    ) -> Option<Task<Result<()>>> {
 4646        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4647    }
 4648
 4649    fn do_completion(
 4650        &mut self,
 4651        item_ix: Option<usize>,
 4652        intent: CompletionIntent,
 4653        cx: &mut ViewContext<Editor>,
 4654    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4655        use language::ToOffset as _;
 4656
 4657        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4658            menu
 4659        } else {
 4660            return None;
 4661        };
 4662
 4663        let mat = completions_menu
 4664            .matches
 4665            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4666        let buffer_handle = completions_menu.buffer;
 4667        let completions = completions_menu.completions.read();
 4668        let completion = completions.get(mat.candidate_id)?;
 4669        cx.stop_propagation();
 4670
 4671        let snippet;
 4672        let text;
 4673
 4674        if completion.is_snippet() {
 4675            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4676            text = snippet.as_ref().unwrap().text.clone();
 4677        } else {
 4678            snippet = None;
 4679            text = completion.new_text.clone();
 4680        };
 4681        let selections = self.selections.all::<usize>(cx);
 4682        let buffer = buffer_handle.read(cx);
 4683        let old_range = completion.old_range.to_offset(buffer);
 4684        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4685
 4686        let newest_selection = self.selections.newest_anchor();
 4687        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4688            return None;
 4689        }
 4690
 4691        let lookbehind = newest_selection
 4692            .start
 4693            .text_anchor
 4694            .to_offset(buffer)
 4695            .saturating_sub(old_range.start);
 4696        let lookahead = old_range
 4697            .end
 4698            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4699        let mut common_prefix_len = old_text
 4700            .bytes()
 4701            .zip(text.bytes())
 4702            .take_while(|(a, b)| a == b)
 4703            .count();
 4704
 4705        let snapshot = self.buffer.read(cx).snapshot(cx);
 4706        let mut range_to_replace: Option<Range<isize>> = None;
 4707        let mut ranges = Vec::new();
 4708        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4709        for selection in &selections {
 4710            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4711                let start = selection.start.saturating_sub(lookbehind);
 4712                let end = selection.end + lookahead;
 4713                if selection.id == newest_selection.id {
 4714                    range_to_replace = Some(
 4715                        ((start + common_prefix_len) as isize - selection.start as isize)
 4716                            ..(end as isize - selection.start as isize),
 4717                    );
 4718                }
 4719                ranges.push(start + common_prefix_len..end);
 4720            } else {
 4721                common_prefix_len = 0;
 4722                ranges.clear();
 4723                ranges.extend(selections.iter().map(|s| {
 4724                    if s.id == newest_selection.id {
 4725                        range_to_replace = Some(
 4726                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4727                                - selection.start as isize
 4728                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4729                                    - selection.start as isize,
 4730                        );
 4731                        old_range.clone()
 4732                    } else {
 4733                        s.start..s.end
 4734                    }
 4735                }));
 4736                break;
 4737            }
 4738            if !self.linked_edit_ranges.is_empty() {
 4739                let start_anchor = snapshot.anchor_before(selection.head());
 4740                let end_anchor = snapshot.anchor_after(selection.tail());
 4741                if let Some(ranges) = self
 4742                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4743                {
 4744                    for (buffer, edits) in ranges {
 4745                        linked_edits.entry(buffer.clone()).or_default().extend(
 4746                            edits
 4747                                .into_iter()
 4748                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4749                        );
 4750                    }
 4751                }
 4752            }
 4753        }
 4754        let text = &text[common_prefix_len..];
 4755
 4756        cx.emit(EditorEvent::InputHandled {
 4757            utf16_range_to_replace: range_to_replace,
 4758            text: text.into(),
 4759        });
 4760
 4761        self.transact(cx, |this, cx| {
 4762            if let Some(mut snippet) = snippet {
 4763                snippet.text = text.to_string();
 4764                for tabstop in snippet
 4765                    .tabstops
 4766                    .iter_mut()
 4767                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4768                {
 4769                    tabstop.start -= common_prefix_len as isize;
 4770                    tabstop.end -= common_prefix_len as isize;
 4771                }
 4772
 4773                this.insert_snippet(&ranges, snippet, cx).log_err();
 4774            } else {
 4775                this.buffer.update(cx, |buffer, cx| {
 4776                    buffer.edit(
 4777                        ranges.iter().map(|range| (range.clone(), text)),
 4778                        this.autoindent_mode.clone(),
 4779                        cx,
 4780                    );
 4781                });
 4782            }
 4783            for (buffer, edits) in linked_edits {
 4784                buffer.update(cx, |buffer, cx| {
 4785                    let snapshot = buffer.snapshot();
 4786                    let edits = edits
 4787                        .into_iter()
 4788                        .map(|(range, text)| {
 4789                            use text::ToPoint as TP;
 4790                            let end_point = TP::to_point(&range.end, &snapshot);
 4791                            let start_point = TP::to_point(&range.start, &snapshot);
 4792                            (start_point..end_point, text)
 4793                        })
 4794                        .sorted_by_key(|(range, _)| range.start)
 4795                        .collect::<Vec<_>>();
 4796                    buffer.edit(edits, None, cx);
 4797                })
 4798            }
 4799
 4800            this.refresh_inline_completion(true, false, cx);
 4801        });
 4802
 4803        let show_new_completions_on_confirm = completion
 4804            .confirm
 4805            .as_ref()
 4806            .map_or(false, |confirm| confirm(intent, cx));
 4807        if show_new_completions_on_confirm {
 4808            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4809        }
 4810
 4811        let provider = self.completion_provider.as_ref()?;
 4812        let apply_edits = provider.apply_additional_edits_for_completion(
 4813            buffer_handle,
 4814            completion.clone(),
 4815            true,
 4816            cx,
 4817        );
 4818
 4819        let editor_settings = EditorSettings::get_global(cx);
 4820        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4821            // After the code completion is finished, users often want to know what signatures are needed.
 4822            // so we should automatically call signature_help
 4823            self.show_signature_help(&ShowSignatureHelp, cx);
 4824        }
 4825
 4826        Some(cx.foreground_executor().spawn(async move {
 4827            apply_edits.await?;
 4828            Ok(())
 4829        }))
 4830    }
 4831
 4832    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4833        let mut context_menu = self.context_menu.write();
 4834        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4835            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4836                // Toggle if we're selecting the same one
 4837                *context_menu = None;
 4838                cx.notify();
 4839                return;
 4840            } else {
 4841                // Otherwise, clear it and start a new one
 4842                *context_menu = None;
 4843                cx.notify();
 4844            }
 4845        }
 4846        drop(context_menu);
 4847        let snapshot = self.snapshot(cx);
 4848        let deployed_from_indicator = action.deployed_from_indicator;
 4849        let mut task = self.code_actions_task.take();
 4850        let action = action.clone();
 4851        cx.spawn(|editor, mut cx| async move {
 4852            while let Some(prev_task) = task {
 4853                prev_task.await.log_err();
 4854                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4855            }
 4856
 4857            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4858                if editor.focus_handle.is_focused(cx) {
 4859                    let multibuffer_point = action
 4860                        .deployed_from_indicator
 4861                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4862                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4863                    let (buffer, buffer_row) = snapshot
 4864                        .buffer_snapshot
 4865                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4866                        .and_then(|(buffer_snapshot, range)| {
 4867                            editor
 4868                                .buffer
 4869                                .read(cx)
 4870                                .buffer(buffer_snapshot.remote_id())
 4871                                .map(|buffer| (buffer, range.start.row))
 4872                        })?;
 4873                    let (_, code_actions) = editor
 4874                        .available_code_actions
 4875                        .clone()
 4876                        .and_then(|(location, code_actions)| {
 4877                            let snapshot = location.buffer.read(cx).snapshot();
 4878                            let point_range = location.range.to_point(&snapshot);
 4879                            let point_range = point_range.start.row..=point_range.end.row;
 4880                            if point_range.contains(&buffer_row) {
 4881                                Some((location, code_actions))
 4882                            } else {
 4883                                None
 4884                            }
 4885                        })
 4886                        .unzip();
 4887                    let buffer_id = buffer.read(cx).remote_id();
 4888                    let tasks = editor
 4889                        .tasks
 4890                        .get(&(buffer_id, buffer_row))
 4891                        .map(|t| Arc::new(t.to_owned()));
 4892                    if tasks.is_none() && code_actions.is_none() {
 4893                        return None;
 4894                    }
 4895
 4896                    editor.completion_tasks.clear();
 4897                    editor.discard_inline_completion(false, cx);
 4898                    let task_context =
 4899                        tasks
 4900                            .as_ref()
 4901                            .zip(editor.project.clone())
 4902                            .map(|(tasks, project)| {
 4903                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4904                            });
 4905
 4906                    Some(cx.spawn(|editor, mut cx| async move {
 4907                        let task_context = match task_context {
 4908                            Some(task_context) => task_context.await,
 4909                            None => None,
 4910                        };
 4911                        let resolved_tasks =
 4912                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4913                                Arc::new(ResolvedTasks {
 4914                                    templates: tasks.resolve(&task_context).collect(),
 4915                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4916                                        multibuffer_point.row,
 4917                                        tasks.column,
 4918                                    )),
 4919                                })
 4920                            });
 4921                        let spawn_straight_away = resolved_tasks
 4922                            .as_ref()
 4923                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4924                            && code_actions
 4925                                .as_ref()
 4926                                .map_or(true, |actions| actions.is_empty());
 4927                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4928                            *editor.context_menu.write() =
 4929                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4930                                    buffer,
 4931                                    actions: CodeActionContents {
 4932                                        tasks: resolved_tasks,
 4933                                        actions: code_actions,
 4934                                    },
 4935                                    selected_item: Default::default(),
 4936                                    scroll_handle: UniformListScrollHandle::default(),
 4937                                    deployed_from_indicator,
 4938                                }));
 4939                            if spawn_straight_away {
 4940                                if let Some(task) = editor.confirm_code_action(
 4941                                    &ConfirmCodeAction { item_ix: Some(0) },
 4942                                    cx,
 4943                                ) {
 4944                                    cx.notify();
 4945                                    return task;
 4946                                }
 4947                            }
 4948                            cx.notify();
 4949                            Task::ready(Ok(()))
 4950                        }) {
 4951                            task.await
 4952                        } else {
 4953                            Ok(())
 4954                        }
 4955                    }))
 4956                } else {
 4957                    Some(Task::ready(Ok(())))
 4958                }
 4959            })?;
 4960            if let Some(task) = spawned_test_task {
 4961                task.await?;
 4962            }
 4963
 4964            Ok::<_, anyhow::Error>(())
 4965        })
 4966        .detach_and_log_err(cx);
 4967    }
 4968
 4969    pub fn confirm_code_action(
 4970        &mut self,
 4971        action: &ConfirmCodeAction,
 4972        cx: &mut ViewContext<Self>,
 4973    ) -> Option<Task<Result<()>>> {
 4974        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4975            menu
 4976        } else {
 4977            return None;
 4978        };
 4979        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4980        let action = actions_menu.actions.get(action_ix)?;
 4981        let title = action.label();
 4982        let buffer = actions_menu.buffer;
 4983        let workspace = self.workspace()?;
 4984
 4985        match action {
 4986            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4987                workspace.update(cx, |workspace, cx| {
 4988                    workspace::tasks::schedule_resolved_task(
 4989                        workspace,
 4990                        task_source_kind,
 4991                        resolved_task,
 4992                        false,
 4993                        cx,
 4994                    );
 4995
 4996                    Some(Task::ready(Ok(())))
 4997                })
 4998            }
 4999            CodeActionsItem::CodeAction {
 5000                excerpt_id,
 5001                action,
 5002                provider,
 5003            } => {
 5004                let apply_code_action =
 5005                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 5006                let workspace = workspace.downgrade();
 5007                Some(cx.spawn(|editor, cx| async move {
 5008                    let project_transaction = apply_code_action.await?;
 5009                    Self::open_project_transaction(
 5010                        &editor,
 5011                        workspace,
 5012                        project_transaction,
 5013                        title,
 5014                        cx,
 5015                    )
 5016                    .await
 5017                }))
 5018            }
 5019        }
 5020    }
 5021
 5022    pub async fn open_project_transaction(
 5023        this: &WeakView<Editor>,
 5024        workspace: WeakView<Workspace>,
 5025        transaction: ProjectTransaction,
 5026        title: String,
 5027        mut cx: AsyncWindowContext,
 5028    ) -> Result<()> {
 5029        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5030        cx.update(|cx| {
 5031            entries.sort_unstable_by_key(|(buffer, _)| {
 5032                buffer.read(cx).file().map(|f| f.path().clone())
 5033            });
 5034        })?;
 5035
 5036        // If the project transaction's edits are all contained within this editor, then
 5037        // avoid opening a new editor to display them.
 5038
 5039        if let Some((buffer, transaction)) = entries.first() {
 5040            if entries.len() == 1 {
 5041                let excerpt = this.update(&mut cx, |editor, cx| {
 5042                    editor
 5043                        .buffer()
 5044                        .read(cx)
 5045                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5046                })?;
 5047                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5048                    if excerpted_buffer == *buffer {
 5049                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 5050                            let excerpt_range = excerpt_range.to_offset(buffer);
 5051                            buffer
 5052                                .edited_ranges_for_transaction::<usize>(transaction)
 5053                                .all(|range| {
 5054                                    excerpt_range.start <= range.start
 5055                                        && excerpt_range.end >= range.end
 5056                                })
 5057                        })?;
 5058
 5059                        if all_edits_within_excerpt {
 5060                            return Ok(());
 5061                        }
 5062                    }
 5063                }
 5064            }
 5065        } else {
 5066            return Ok(());
 5067        }
 5068
 5069        let mut ranges_to_highlight = Vec::new();
 5070        let excerpt_buffer = cx.new_model(|cx| {
 5071            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5072            for (buffer_handle, transaction) in &entries {
 5073                let buffer = buffer_handle.read(cx);
 5074                ranges_to_highlight.extend(
 5075                    multibuffer.push_excerpts_with_context_lines(
 5076                        buffer_handle.clone(),
 5077                        buffer
 5078                            .edited_ranges_for_transaction::<usize>(transaction)
 5079                            .collect(),
 5080                        DEFAULT_MULTIBUFFER_CONTEXT,
 5081                        cx,
 5082                    ),
 5083                );
 5084            }
 5085            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5086            multibuffer
 5087        })?;
 5088
 5089        workspace.update(&mut cx, |workspace, cx| {
 5090            let project = workspace.project().clone();
 5091            let editor =
 5092                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5093            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5094            editor.update(cx, |editor, cx| {
 5095                editor.highlight_background::<Self>(
 5096                    &ranges_to_highlight,
 5097                    |theme| theme.editor_highlighted_line_background,
 5098                    cx,
 5099                );
 5100            });
 5101        })?;
 5102
 5103        Ok(())
 5104    }
 5105
 5106    pub fn clear_code_action_providers(&mut self) {
 5107        self.code_action_providers.clear();
 5108        self.available_code_actions.take();
 5109    }
 5110
 5111    pub fn push_code_action_provider(
 5112        &mut self,
 5113        provider: Arc<dyn CodeActionProvider>,
 5114        cx: &mut ViewContext<Self>,
 5115    ) {
 5116        self.code_action_providers.push(provider);
 5117        self.refresh_code_actions(cx);
 5118    }
 5119
 5120    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5121        let buffer = self.buffer.read(cx);
 5122        let newest_selection = self.selections.newest_anchor().clone();
 5123        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5124        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5125        if start_buffer != end_buffer {
 5126            return None;
 5127        }
 5128
 5129        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5130            cx.background_executor()
 5131                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5132                .await;
 5133
 5134            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5135                let providers = this.code_action_providers.clone();
 5136                let tasks = this
 5137                    .code_action_providers
 5138                    .iter()
 5139                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5140                    .collect::<Vec<_>>();
 5141                (providers, tasks)
 5142            })?;
 5143
 5144            let mut actions = Vec::new();
 5145            for (provider, provider_actions) in
 5146                providers.into_iter().zip(future::join_all(tasks).await)
 5147            {
 5148                if let Some(provider_actions) = provider_actions.log_err() {
 5149                    actions.extend(provider_actions.into_iter().map(|action| {
 5150                        AvailableCodeAction {
 5151                            excerpt_id: newest_selection.start.excerpt_id,
 5152                            action,
 5153                            provider: provider.clone(),
 5154                        }
 5155                    }));
 5156                }
 5157            }
 5158
 5159            this.update(&mut cx, |this, cx| {
 5160                this.available_code_actions = if actions.is_empty() {
 5161                    None
 5162                } else {
 5163                    Some((
 5164                        Location {
 5165                            buffer: start_buffer,
 5166                            range: start..end,
 5167                        },
 5168                        actions.into(),
 5169                    ))
 5170                };
 5171                cx.notify();
 5172            })
 5173        }));
 5174        None
 5175    }
 5176
 5177    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5178        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5179            self.show_git_blame_inline = false;
 5180
 5181            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5182                cx.background_executor().timer(delay).await;
 5183
 5184                this.update(&mut cx, |this, cx| {
 5185                    this.show_git_blame_inline = true;
 5186                    cx.notify();
 5187                })
 5188                .log_err();
 5189            }));
 5190        }
 5191    }
 5192
 5193    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5194        if self.pending_rename.is_some() {
 5195            return None;
 5196        }
 5197
 5198        let provider = self.semantics_provider.clone()?;
 5199        let buffer = self.buffer.read(cx);
 5200        let newest_selection = self.selections.newest_anchor().clone();
 5201        let cursor_position = newest_selection.head();
 5202        let (cursor_buffer, cursor_buffer_position) =
 5203            buffer.text_anchor_for_position(cursor_position, cx)?;
 5204        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5205        if cursor_buffer != tail_buffer {
 5206            return None;
 5207        }
 5208
 5209        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5210            cx.background_executor()
 5211                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5212                .await;
 5213
 5214            let highlights = if let Some(highlights) = cx
 5215                .update(|cx| {
 5216                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5217                })
 5218                .ok()
 5219                .flatten()
 5220            {
 5221                highlights.await.log_err()
 5222            } else {
 5223                None
 5224            };
 5225
 5226            if let Some(highlights) = highlights {
 5227                this.update(&mut cx, |this, cx| {
 5228                    if this.pending_rename.is_some() {
 5229                        return;
 5230                    }
 5231
 5232                    let buffer_id = cursor_position.buffer_id;
 5233                    let buffer = this.buffer.read(cx);
 5234                    if !buffer
 5235                        .text_anchor_for_position(cursor_position, cx)
 5236                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5237                    {
 5238                        return;
 5239                    }
 5240
 5241                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5242                    let mut write_ranges = Vec::new();
 5243                    let mut read_ranges = Vec::new();
 5244                    for highlight in highlights {
 5245                        for (excerpt_id, excerpt_range) in
 5246                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5247                        {
 5248                            let start = highlight
 5249                                .range
 5250                                .start
 5251                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5252                            let end = highlight
 5253                                .range
 5254                                .end
 5255                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5256                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5257                                continue;
 5258                            }
 5259
 5260                            let range = Anchor {
 5261                                buffer_id,
 5262                                excerpt_id,
 5263                                text_anchor: start,
 5264                            }..Anchor {
 5265                                buffer_id,
 5266                                excerpt_id,
 5267                                text_anchor: end,
 5268                            };
 5269                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5270                                write_ranges.push(range);
 5271                            } else {
 5272                                read_ranges.push(range);
 5273                            }
 5274                        }
 5275                    }
 5276
 5277                    this.highlight_background::<DocumentHighlightRead>(
 5278                        &read_ranges,
 5279                        |theme| theme.editor_document_highlight_read_background,
 5280                        cx,
 5281                    );
 5282                    this.highlight_background::<DocumentHighlightWrite>(
 5283                        &write_ranges,
 5284                        |theme| theme.editor_document_highlight_write_background,
 5285                        cx,
 5286                    );
 5287                    cx.notify();
 5288                })
 5289                .log_err();
 5290            }
 5291        }));
 5292        None
 5293    }
 5294
 5295    pub fn refresh_inline_completion(
 5296        &mut self,
 5297        debounce: bool,
 5298        user_requested: bool,
 5299        cx: &mut ViewContext<Self>,
 5300    ) -> Option<()> {
 5301        let provider = self.inline_completion_provider()?;
 5302        let cursor = self.selections.newest_anchor().head();
 5303        let (buffer, cursor_buffer_position) =
 5304            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5305
 5306        if !user_requested
 5307            && (!self.enable_inline_completions
 5308                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5309        {
 5310            self.discard_inline_completion(false, cx);
 5311            return None;
 5312        }
 5313
 5314        self.update_visible_inline_completion(cx);
 5315        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5316        Some(())
 5317    }
 5318
 5319    fn cycle_inline_completion(
 5320        &mut self,
 5321        direction: Direction,
 5322        cx: &mut ViewContext<Self>,
 5323    ) -> Option<()> {
 5324        let provider = self.inline_completion_provider()?;
 5325        let cursor = self.selections.newest_anchor().head();
 5326        let (buffer, cursor_buffer_position) =
 5327            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5328        if !self.enable_inline_completions
 5329            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5330        {
 5331            return None;
 5332        }
 5333
 5334        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5335        self.update_visible_inline_completion(cx);
 5336
 5337        Some(())
 5338    }
 5339
 5340    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5341        if !self.has_active_inline_completion(cx) {
 5342            self.refresh_inline_completion(false, true, cx);
 5343            return;
 5344        }
 5345
 5346        self.update_visible_inline_completion(cx);
 5347    }
 5348
 5349    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5350        self.show_cursor_names(cx);
 5351    }
 5352
 5353    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5354        self.show_cursor_names = true;
 5355        cx.notify();
 5356        cx.spawn(|this, mut cx| async move {
 5357            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5358            this.update(&mut cx, |this, cx| {
 5359                this.show_cursor_names = false;
 5360                cx.notify()
 5361            })
 5362            .ok()
 5363        })
 5364        .detach();
 5365    }
 5366
 5367    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5368        if self.has_active_inline_completion(cx) {
 5369            self.cycle_inline_completion(Direction::Next, cx);
 5370        } else {
 5371            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5372            if is_copilot_disabled {
 5373                cx.propagate();
 5374            }
 5375        }
 5376    }
 5377
 5378    pub fn previous_inline_completion(
 5379        &mut self,
 5380        _: &PreviousInlineCompletion,
 5381        cx: &mut ViewContext<Self>,
 5382    ) {
 5383        if self.has_active_inline_completion(cx) {
 5384            self.cycle_inline_completion(Direction::Prev, cx);
 5385        } else {
 5386            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5387            if is_copilot_disabled {
 5388                cx.propagate();
 5389            }
 5390        }
 5391    }
 5392
 5393    pub fn accept_inline_completion(
 5394        &mut self,
 5395        _: &AcceptInlineCompletion,
 5396        cx: &mut ViewContext<Self>,
 5397    ) {
 5398        let Some(completion) = self.take_active_inline_completion(cx) else {
 5399            return;
 5400        };
 5401        if let Some(provider) = self.inline_completion_provider() {
 5402            provider.accept(cx);
 5403        }
 5404
 5405        cx.emit(EditorEvent::InputHandled {
 5406            utf16_range_to_replace: None,
 5407            text: completion.text.to_string().into(),
 5408        });
 5409
 5410        if let Some(range) = completion.delete_range {
 5411            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5412        }
 5413        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5414        self.refresh_inline_completion(true, true, cx);
 5415        cx.notify();
 5416    }
 5417
 5418    pub fn accept_partial_inline_completion(
 5419        &mut self,
 5420        _: &AcceptPartialInlineCompletion,
 5421        cx: &mut ViewContext<Self>,
 5422    ) {
 5423        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5424            if let Some(completion) = self.take_active_inline_completion(cx) {
 5425                let mut partial_completion = completion
 5426                    .text
 5427                    .chars()
 5428                    .by_ref()
 5429                    .take_while(|c| c.is_alphabetic())
 5430                    .collect::<String>();
 5431                if partial_completion.is_empty() {
 5432                    partial_completion = completion
 5433                        .text
 5434                        .chars()
 5435                        .by_ref()
 5436                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5437                        .collect::<String>();
 5438                }
 5439
 5440                cx.emit(EditorEvent::InputHandled {
 5441                    utf16_range_to_replace: None,
 5442                    text: partial_completion.clone().into(),
 5443                });
 5444
 5445                if let Some(range) = completion.delete_range {
 5446                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5447                }
 5448                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5449
 5450                self.refresh_inline_completion(true, true, cx);
 5451                cx.notify();
 5452            }
 5453        }
 5454    }
 5455
 5456    fn discard_inline_completion(
 5457        &mut self,
 5458        should_report_inline_completion_event: bool,
 5459        cx: &mut ViewContext<Self>,
 5460    ) -> bool {
 5461        if let Some(provider) = self.inline_completion_provider() {
 5462            provider.discard(should_report_inline_completion_event, cx);
 5463        }
 5464
 5465        self.take_active_inline_completion(cx).is_some()
 5466    }
 5467
 5468    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5469        if let Some(completion) = self.active_inline_completion.as_ref() {
 5470            let buffer = self.buffer.read(cx).read(cx);
 5471            completion.position.is_valid(&buffer)
 5472        } else {
 5473            false
 5474        }
 5475    }
 5476
 5477    fn take_active_inline_completion(
 5478        &mut self,
 5479        cx: &mut ViewContext<Self>,
 5480    ) -> Option<CompletionState> {
 5481        let completion = self.active_inline_completion.take()?;
 5482        let render_inlay_ids = completion.render_inlay_ids.clone();
 5483        self.display_map.update(cx, |map, cx| {
 5484            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5485        });
 5486        let buffer = self.buffer.read(cx).read(cx);
 5487
 5488        if completion.position.is_valid(&buffer) {
 5489            Some(completion)
 5490        } else {
 5491            None
 5492        }
 5493    }
 5494
 5495    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5496        let selection = self.selections.newest_anchor();
 5497        let cursor = selection.head();
 5498
 5499        let excerpt_id = cursor.excerpt_id;
 5500
 5501        if self.context_menu.read().is_none()
 5502            && self.completion_tasks.is_empty()
 5503            && selection.start == selection.end
 5504        {
 5505            if let Some(provider) = self.inline_completion_provider() {
 5506                if let Some((buffer, cursor_buffer_position)) =
 5507                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5508                {
 5509                    if let Some(proposal) =
 5510                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5511                    {
 5512                        let mut to_remove = Vec::new();
 5513                        if let Some(completion) = self.active_inline_completion.take() {
 5514                            to_remove.extend(completion.render_inlay_ids.iter());
 5515                        }
 5516
 5517                        let to_add = proposal
 5518                            .inlays
 5519                            .iter()
 5520                            .filter_map(|inlay| {
 5521                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5522                                let id = post_inc(&mut self.next_inlay_id);
 5523                                match inlay {
 5524                                    InlayProposal::Hint(position, hint) => {
 5525                                        let position =
 5526                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5527                                        Some(Inlay::hint(id, position, hint))
 5528                                    }
 5529                                    InlayProposal::Suggestion(position, text) => {
 5530                                        let position =
 5531                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5532                                        Some(Inlay::suggestion(id, position, text.clone()))
 5533                                    }
 5534                                }
 5535                            })
 5536                            .collect_vec();
 5537
 5538                        self.active_inline_completion = Some(CompletionState {
 5539                            position: cursor,
 5540                            text: proposal.text,
 5541                            delete_range: proposal.delete_range.and_then(|range| {
 5542                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5543                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5544                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5545                                Some(start?..end?)
 5546                            }),
 5547                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5548                        });
 5549
 5550                        self.display_map
 5551                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5552
 5553                        cx.notify();
 5554                        return;
 5555                    }
 5556                }
 5557            }
 5558        }
 5559
 5560        self.discard_inline_completion(false, cx);
 5561    }
 5562
 5563    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5564        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5565    }
 5566
 5567    fn render_code_actions_indicator(
 5568        &self,
 5569        _style: &EditorStyle,
 5570        row: DisplayRow,
 5571        is_active: bool,
 5572        cx: &mut ViewContext<Self>,
 5573    ) -> Option<IconButton> {
 5574        if self.available_code_actions.is_some() {
 5575            Some(
 5576                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5577                    .shape(ui::IconButtonShape::Square)
 5578                    .icon_size(IconSize::XSmall)
 5579                    .icon_color(Color::Muted)
 5580                    .selected(is_active)
 5581                    .tooltip({
 5582                        let focus_handle = self.focus_handle.clone();
 5583                        move |cx| {
 5584                            Tooltip::for_action_in(
 5585                                "Toggle Code Actions",
 5586                                &ToggleCodeActions {
 5587                                    deployed_from_indicator: None,
 5588                                },
 5589                                &focus_handle,
 5590                                cx,
 5591                            )
 5592                        }
 5593                    })
 5594                    .on_click(cx.listener(move |editor, _e, cx| {
 5595                        editor.focus(cx);
 5596                        editor.toggle_code_actions(
 5597                            &ToggleCodeActions {
 5598                                deployed_from_indicator: Some(row),
 5599                            },
 5600                            cx,
 5601                        );
 5602                    })),
 5603            )
 5604        } else {
 5605            None
 5606        }
 5607    }
 5608
 5609    fn clear_tasks(&mut self) {
 5610        self.tasks.clear()
 5611    }
 5612
 5613    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5614        if self.tasks.insert(key, value).is_some() {
 5615            // This case should hopefully be rare, but just in case...
 5616            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5617        }
 5618    }
 5619
 5620    fn build_tasks_context(
 5621        project: &Model<Project>,
 5622        buffer: &Model<Buffer>,
 5623        buffer_row: u32,
 5624        tasks: &Arc<RunnableTasks>,
 5625        cx: &mut ViewContext<Self>,
 5626    ) -> Task<Option<task::TaskContext>> {
 5627        let position = Point::new(buffer_row, tasks.column);
 5628        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5629        let location = Location {
 5630            buffer: buffer.clone(),
 5631            range: range_start..range_start,
 5632        };
 5633        // Fill in the environmental variables from the tree-sitter captures
 5634        let mut captured_task_variables = TaskVariables::default();
 5635        for (capture_name, value) in tasks.extra_variables.clone() {
 5636            captured_task_variables.insert(
 5637                task::VariableName::Custom(capture_name.into()),
 5638                value.clone(),
 5639            );
 5640        }
 5641        project.update(cx, |project, cx| {
 5642            project.task_store().update(cx, |task_store, cx| {
 5643                task_store.task_context_for_location(captured_task_variables, location, cx)
 5644            })
 5645        })
 5646    }
 5647
 5648    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5649        let Some((workspace, _)) = self.workspace.clone() else {
 5650            return;
 5651        };
 5652        let Some(project) = self.project.clone() else {
 5653            return;
 5654        };
 5655
 5656        // Try to find a closest, enclosing node using tree-sitter that has a
 5657        // task
 5658        let Some((buffer, buffer_row, tasks)) = self
 5659            .find_enclosing_node_task(cx)
 5660            // Or find the task that's closest in row-distance.
 5661            .or_else(|| self.find_closest_task(cx))
 5662        else {
 5663            return;
 5664        };
 5665
 5666        let reveal_strategy = action.reveal;
 5667        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5668        cx.spawn(|_, mut cx| async move {
 5669            let context = task_context.await?;
 5670            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5671
 5672            let resolved = resolved_task.resolved.as_mut()?;
 5673            resolved.reveal = reveal_strategy;
 5674
 5675            workspace
 5676                .update(&mut cx, |workspace, cx| {
 5677                    workspace::tasks::schedule_resolved_task(
 5678                        workspace,
 5679                        task_source_kind,
 5680                        resolved_task,
 5681                        false,
 5682                        cx,
 5683                    );
 5684                })
 5685                .ok()
 5686        })
 5687        .detach();
 5688    }
 5689
 5690    fn find_closest_task(
 5691        &mut self,
 5692        cx: &mut ViewContext<Self>,
 5693    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5694        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5695
 5696        let ((buffer_id, row), tasks) = self
 5697            .tasks
 5698            .iter()
 5699            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5700
 5701        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5702        let tasks = Arc::new(tasks.to_owned());
 5703        Some((buffer, *row, tasks))
 5704    }
 5705
 5706    fn find_enclosing_node_task(
 5707        &mut self,
 5708        cx: &mut ViewContext<Self>,
 5709    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5710        let snapshot = self.buffer.read(cx).snapshot(cx);
 5711        let offset = self.selections.newest::<usize>(cx).head();
 5712        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5713        let buffer_id = excerpt.buffer().remote_id();
 5714
 5715        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5716        let mut cursor = layer.node().walk();
 5717
 5718        while cursor.goto_first_child_for_byte(offset).is_some() {
 5719            if cursor.node().end_byte() == offset {
 5720                cursor.goto_next_sibling();
 5721            }
 5722        }
 5723
 5724        // Ascend to the smallest ancestor that contains the range and has a task.
 5725        loop {
 5726            let node = cursor.node();
 5727            let node_range = node.byte_range();
 5728            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5729
 5730            // Check if this node contains our offset
 5731            if node_range.start <= offset && node_range.end >= offset {
 5732                // If it contains offset, check for task
 5733                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5734                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5735                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5736                }
 5737            }
 5738
 5739            if !cursor.goto_parent() {
 5740                break;
 5741            }
 5742        }
 5743        None
 5744    }
 5745
 5746    fn render_run_indicator(
 5747        &self,
 5748        _style: &EditorStyle,
 5749        is_active: bool,
 5750        row: DisplayRow,
 5751        cx: &mut ViewContext<Self>,
 5752    ) -> IconButton {
 5753        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5754            .shape(ui::IconButtonShape::Square)
 5755            .icon_size(IconSize::XSmall)
 5756            .icon_color(Color::Muted)
 5757            .selected(is_active)
 5758            .on_click(cx.listener(move |editor, _e, cx| {
 5759                editor.focus(cx);
 5760                editor.toggle_code_actions(
 5761                    &ToggleCodeActions {
 5762                        deployed_from_indicator: Some(row),
 5763                    },
 5764                    cx,
 5765                );
 5766            }))
 5767    }
 5768
 5769    pub fn context_menu_visible(&self) -> bool {
 5770        self.context_menu
 5771            .read()
 5772            .as_ref()
 5773            .map_or(false, |menu| menu.visible())
 5774    }
 5775
 5776    fn render_context_menu(
 5777        &self,
 5778        cursor_position: DisplayPoint,
 5779        style: &EditorStyle,
 5780        max_height: Pixels,
 5781        cx: &mut ViewContext<Editor>,
 5782    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5783        self.context_menu.read().as_ref().map(|menu| {
 5784            menu.render(
 5785                cursor_position,
 5786                style,
 5787                max_height,
 5788                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5789                cx,
 5790            )
 5791        })
 5792    }
 5793
 5794    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5795        cx.notify();
 5796        self.completion_tasks.clear();
 5797        let context_menu = self.context_menu.write().take();
 5798        if context_menu.is_some() {
 5799            self.update_visible_inline_completion(cx);
 5800        }
 5801        context_menu
 5802    }
 5803
 5804    fn show_snippet_choices(
 5805        &mut self,
 5806        choices: &Vec<String>,
 5807        selection: Range<Anchor>,
 5808        cx: &mut ViewContext<Self>,
 5809    ) {
 5810        if selection.start.buffer_id.is_none() {
 5811            return;
 5812        }
 5813        let buffer_id = selection.start.buffer_id.unwrap();
 5814        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5815        let id = post_inc(&mut self.next_completion_id);
 5816
 5817        if let Some(buffer) = buffer {
 5818            *self.context_menu.write() = Some(ContextMenu::Completions(
 5819                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
 5820                    .suppress_documentation_resolution(),
 5821            ));
 5822        }
 5823    }
 5824
 5825    pub fn insert_snippet(
 5826        &mut self,
 5827        insertion_ranges: &[Range<usize>],
 5828        snippet: Snippet,
 5829        cx: &mut ViewContext<Self>,
 5830    ) -> Result<()> {
 5831        struct Tabstop<T> {
 5832            is_end_tabstop: bool,
 5833            ranges: Vec<Range<T>>,
 5834            choices: Option<Vec<String>>,
 5835        }
 5836
 5837        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5838            let snippet_text: Arc<str> = snippet.text.clone().into();
 5839            buffer.edit(
 5840                insertion_ranges
 5841                    .iter()
 5842                    .cloned()
 5843                    .map(|range| (range, snippet_text.clone())),
 5844                Some(AutoindentMode::EachLine),
 5845                cx,
 5846            );
 5847
 5848            let snapshot = &*buffer.read(cx);
 5849            let snippet = &snippet;
 5850            snippet
 5851                .tabstops
 5852                .iter()
 5853                .map(|tabstop| {
 5854                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5855                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5856                    });
 5857                    let mut tabstop_ranges = tabstop
 5858                        .ranges
 5859                        .iter()
 5860                        .flat_map(|tabstop_range| {
 5861                            let mut delta = 0_isize;
 5862                            insertion_ranges.iter().map(move |insertion_range| {
 5863                                let insertion_start = insertion_range.start as isize + delta;
 5864                                delta +=
 5865                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5866
 5867                                let start = ((insertion_start + tabstop_range.start) as usize)
 5868                                    .min(snapshot.len());
 5869                                let end = ((insertion_start + tabstop_range.end) as usize)
 5870                                    .min(snapshot.len());
 5871                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5872                            })
 5873                        })
 5874                        .collect::<Vec<_>>();
 5875                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5876
 5877                    Tabstop {
 5878                        is_end_tabstop,
 5879                        ranges: tabstop_ranges,
 5880                        choices: tabstop.choices.clone(),
 5881                    }
 5882                })
 5883                .collect::<Vec<_>>()
 5884        });
 5885        if let Some(tabstop) = tabstops.first() {
 5886            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5887                s.select_ranges(tabstop.ranges.iter().cloned());
 5888            });
 5889
 5890            if let Some(choices) = &tabstop.choices {
 5891                if let Some(selection) = tabstop.ranges.first() {
 5892                    self.show_snippet_choices(choices, selection.clone(), cx)
 5893                }
 5894            }
 5895
 5896            // If we're already at the last tabstop and it's at the end of the snippet,
 5897            // we're done, we don't need to keep the state around.
 5898            if !tabstop.is_end_tabstop {
 5899                let choices = tabstops
 5900                    .iter()
 5901                    .map(|tabstop| tabstop.choices.clone())
 5902                    .collect();
 5903
 5904                let ranges = tabstops
 5905                    .into_iter()
 5906                    .map(|tabstop| tabstop.ranges)
 5907                    .collect::<Vec<_>>();
 5908
 5909                self.snippet_stack.push(SnippetState {
 5910                    active_index: 0,
 5911                    ranges,
 5912                    choices,
 5913                });
 5914            }
 5915
 5916            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5917            if self.autoclose_regions.is_empty() {
 5918                let snapshot = self.buffer.read(cx).snapshot(cx);
 5919                for selection in &mut self.selections.all::<Point>(cx) {
 5920                    let selection_head = selection.head();
 5921                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5922                        continue;
 5923                    };
 5924
 5925                    let mut bracket_pair = None;
 5926                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5927                    let prev_chars = snapshot
 5928                        .reversed_chars_at(selection_head)
 5929                        .collect::<String>();
 5930                    for (pair, enabled) in scope.brackets() {
 5931                        if enabled
 5932                            && pair.close
 5933                            && prev_chars.starts_with(pair.start.as_str())
 5934                            && next_chars.starts_with(pair.end.as_str())
 5935                        {
 5936                            bracket_pair = Some(pair.clone());
 5937                            break;
 5938                        }
 5939                    }
 5940                    if let Some(pair) = bracket_pair {
 5941                        let start = snapshot.anchor_after(selection_head);
 5942                        let end = snapshot.anchor_after(selection_head);
 5943                        self.autoclose_regions.push(AutocloseRegion {
 5944                            selection_id: selection.id,
 5945                            range: start..end,
 5946                            pair,
 5947                        });
 5948                    }
 5949                }
 5950            }
 5951        }
 5952        Ok(())
 5953    }
 5954
 5955    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5956        self.move_to_snippet_tabstop(Bias::Right, cx)
 5957    }
 5958
 5959    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5960        self.move_to_snippet_tabstop(Bias::Left, cx)
 5961    }
 5962
 5963    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5964        if let Some(mut snippet) = self.snippet_stack.pop() {
 5965            match bias {
 5966                Bias::Left => {
 5967                    if snippet.active_index > 0 {
 5968                        snippet.active_index -= 1;
 5969                    } else {
 5970                        self.snippet_stack.push(snippet);
 5971                        return false;
 5972                    }
 5973                }
 5974                Bias::Right => {
 5975                    if snippet.active_index + 1 < snippet.ranges.len() {
 5976                        snippet.active_index += 1;
 5977                    } else {
 5978                        self.snippet_stack.push(snippet);
 5979                        return false;
 5980                    }
 5981                }
 5982            }
 5983            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5984                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5985                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5986                });
 5987
 5988                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5989                    if let Some(selection) = current_ranges.first() {
 5990                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5991                    }
 5992                }
 5993
 5994                // If snippet state is not at the last tabstop, push it back on the stack
 5995                if snippet.active_index + 1 < snippet.ranges.len() {
 5996                    self.snippet_stack.push(snippet);
 5997                }
 5998                return true;
 5999            }
 6000        }
 6001
 6002        false
 6003    }
 6004
 6005    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 6006        self.transact(cx, |this, cx| {
 6007            this.select_all(&SelectAll, cx);
 6008            this.insert("", cx);
 6009        });
 6010    }
 6011
 6012    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 6013        self.transact(cx, |this, cx| {
 6014            this.select_autoclose_pair(cx);
 6015            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6016            if !this.linked_edit_ranges.is_empty() {
 6017                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6018                let snapshot = this.buffer.read(cx).snapshot(cx);
 6019
 6020                for selection in selections.iter() {
 6021                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6022                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6023                    if selection_start.buffer_id != selection_end.buffer_id {
 6024                        continue;
 6025                    }
 6026                    if let Some(ranges) =
 6027                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6028                    {
 6029                        for (buffer, entries) in ranges {
 6030                            linked_ranges.entry(buffer).or_default().extend(entries);
 6031                        }
 6032                    }
 6033                }
 6034            }
 6035
 6036            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6037            if !this.selections.line_mode {
 6038                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6039                for selection in &mut selections {
 6040                    if selection.is_empty() {
 6041                        let old_head = selection.head();
 6042                        let mut new_head =
 6043                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6044                                .to_point(&display_map);
 6045                        if let Some((buffer, line_buffer_range)) = display_map
 6046                            .buffer_snapshot
 6047                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6048                        {
 6049                            let indent_size =
 6050                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6051                            let indent_len = match indent_size.kind {
 6052                                IndentKind::Space => {
 6053                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6054                                }
 6055                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6056                            };
 6057                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6058                                let indent_len = indent_len.get();
 6059                                new_head = cmp::min(
 6060                                    new_head,
 6061                                    MultiBufferPoint::new(
 6062                                        old_head.row,
 6063                                        ((old_head.column - 1) / indent_len) * indent_len,
 6064                                    ),
 6065                                );
 6066                            }
 6067                        }
 6068
 6069                        selection.set_head(new_head, SelectionGoal::None);
 6070                    }
 6071                }
 6072            }
 6073
 6074            this.signature_help_state.set_backspace_pressed(true);
 6075            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6076            this.insert("", cx);
 6077            let empty_str: Arc<str> = Arc::from("");
 6078            for (buffer, edits) in linked_ranges {
 6079                let snapshot = buffer.read(cx).snapshot();
 6080                use text::ToPoint as TP;
 6081
 6082                let edits = edits
 6083                    .into_iter()
 6084                    .map(|range| {
 6085                        let end_point = TP::to_point(&range.end, &snapshot);
 6086                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6087
 6088                        if end_point == start_point {
 6089                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6090                                .saturating_sub(1);
 6091                            start_point = TP::to_point(&offset, &snapshot);
 6092                        };
 6093
 6094                        (start_point..end_point, empty_str.clone())
 6095                    })
 6096                    .sorted_by_key(|(range, _)| range.start)
 6097                    .collect::<Vec<_>>();
 6098                buffer.update(cx, |this, cx| {
 6099                    this.edit(edits, None, cx);
 6100                })
 6101            }
 6102            this.refresh_inline_completion(true, false, cx);
 6103            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6104        });
 6105    }
 6106
 6107    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6108        self.transact(cx, |this, cx| {
 6109            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6110                let line_mode = s.line_mode;
 6111                s.move_with(|map, selection| {
 6112                    if selection.is_empty() && !line_mode {
 6113                        let cursor = movement::right(map, selection.head());
 6114                        selection.end = cursor;
 6115                        selection.reversed = true;
 6116                        selection.goal = SelectionGoal::None;
 6117                    }
 6118                })
 6119            });
 6120            this.insert("", cx);
 6121            this.refresh_inline_completion(true, false, cx);
 6122        });
 6123    }
 6124
 6125    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6126        if self.move_to_prev_snippet_tabstop(cx) {
 6127            return;
 6128        }
 6129
 6130        self.outdent(&Outdent, cx);
 6131    }
 6132
 6133    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6134        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6135            return;
 6136        }
 6137
 6138        let mut selections = self.selections.all_adjusted(cx);
 6139        let buffer = self.buffer.read(cx);
 6140        let snapshot = buffer.snapshot(cx);
 6141        let rows_iter = selections.iter().map(|s| s.head().row);
 6142        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6143
 6144        let mut edits = Vec::new();
 6145        let mut prev_edited_row = 0;
 6146        let mut row_delta = 0;
 6147        for selection in &mut selections {
 6148            if selection.start.row != prev_edited_row {
 6149                row_delta = 0;
 6150            }
 6151            prev_edited_row = selection.end.row;
 6152
 6153            // If the selection is non-empty, then increase the indentation of the selected lines.
 6154            if !selection.is_empty() {
 6155                row_delta =
 6156                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6157                continue;
 6158            }
 6159
 6160            // If the selection is empty and the cursor is in the leading whitespace before the
 6161            // suggested indentation, then auto-indent the line.
 6162            let cursor = selection.head();
 6163            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6164            if let Some(suggested_indent) =
 6165                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6166            {
 6167                if cursor.column < suggested_indent.len
 6168                    && cursor.column <= current_indent.len
 6169                    && current_indent.len <= suggested_indent.len
 6170                {
 6171                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6172                    selection.end = selection.start;
 6173                    if row_delta == 0 {
 6174                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6175                            cursor.row,
 6176                            current_indent,
 6177                            suggested_indent,
 6178                        ));
 6179                        row_delta = suggested_indent.len - current_indent.len;
 6180                    }
 6181                    continue;
 6182                }
 6183            }
 6184
 6185            // Otherwise, insert a hard or soft tab.
 6186            let settings = buffer.settings_at(cursor, cx);
 6187            let tab_size = if settings.hard_tabs {
 6188                IndentSize::tab()
 6189            } else {
 6190                let tab_size = settings.tab_size.get();
 6191                let char_column = snapshot
 6192                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6193                    .flat_map(str::chars)
 6194                    .count()
 6195                    + row_delta as usize;
 6196                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6197                IndentSize::spaces(chars_to_next_tab_stop)
 6198            };
 6199            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6200            selection.end = selection.start;
 6201            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6202            row_delta += tab_size.len;
 6203        }
 6204
 6205        self.transact(cx, |this, cx| {
 6206            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6207            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6208            this.refresh_inline_completion(true, false, cx);
 6209        });
 6210    }
 6211
 6212    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6213        if self.read_only(cx) {
 6214            return;
 6215        }
 6216        let mut selections = self.selections.all::<Point>(cx);
 6217        let mut prev_edited_row = 0;
 6218        let mut row_delta = 0;
 6219        let mut edits = Vec::new();
 6220        let buffer = self.buffer.read(cx);
 6221        let snapshot = buffer.snapshot(cx);
 6222        for selection in &mut selections {
 6223            if selection.start.row != prev_edited_row {
 6224                row_delta = 0;
 6225            }
 6226            prev_edited_row = selection.end.row;
 6227
 6228            row_delta =
 6229                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6230        }
 6231
 6232        self.transact(cx, |this, cx| {
 6233            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6234            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6235        });
 6236    }
 6237
 6238    fn indent_selection(
 6239        buffer: &MultiBuffer,
 6240        snapshot: &MultiBufferSnapshot,
 6241        selection: &mut Selection<Point>,
 6242        edits: &mut Vec<(Range<Point>, String)>,
 6243        delta_for_start_row: u32,
 6244        cx: &AppContext,
 6245    ) -> u32 {
 6246        let settings = buffer.settings_at(selection.start, cx);
 6247        let tab_size = settings.tab_size.get();
 6248        let indent_kind = if settings.hard_tabs {
 6249            IndentKind::Tab
 6250        } else {
 6251            IndentKind::Space
 6252        };
 6253        let mut start_row = selection.start.row;
 6254        let mut end_row = selection.end.row + 1;
 6255
 6256        // If a selection ends at the beginning of a line, don't indent
 6257        // that last line.
 6258        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6259            end_row -= 1;
 6260        }
 6261
 6262        // Avoid re-indenting a row that has already been indented by a
 6263        // previous selection, but still update this selection's column
 6264        // to reflect that indentation.
 6265        if delta_for_start_row > 0 {
 6266            start_row += 1;
 6267            selection.start.column += delta_for_start_row;
 6268            if selection.end.row == selection.start.row {
 6269                selection.end.column += delta_for_start_row;
 6270            }
 6271        }
 6272
 6273        let mut delta_for_end_row = 0;
 6274        let has_multiple_rows = start_row + 1 != end_row;
 6275        for row in start_row..end_row {
 6276            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6277            let indent_delta = match (current_indent.kind, indent_kind) {
 6278                (IndentKind::Space, IndentKind::Space) => {
 6279                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6280                    IndentSize::spaces(columns_to_next_tab_stop)
 6281                }
 6282                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6283                (_, IndentKind::Tab) => IndentSize::tab(),
 6284            };
 6285
 6286            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6287                0
 6288            } else {
 6289                selection.start.column
 6290            };
 6291            let row_start = Point::new(row, start);
 6292            edits.push((
 6293                row_start..row_start,
 6294                indent_delta.chars().collect::<String>(),
 6295            ));
 6296
 6297            // Update this selection's endpoints to reflect the indentation.
 6298            if row == selection.start.row {
 6299                selection.start.column += indent_delta.len;
 6300            }
 6301            if row == selection.end.row {
 6302                selection.end.column += indent_delta.len;
 6303                delta_for_end_row = indent_delta.len;
 6304            }
 6305        }
 6306
 6307        if selection.start.row == selection.end.row {
 6308            delta_for_start_row + delta_for_end_row
 6309        } else {
 6310            delta_for_end_row
 6311        }
 6312    }
 6313
 6314    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6315        if self.read_only(cx) {
 6316            return;
 6317        }
 6318        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6319        let selections = self.selections.all::<Point>(cx);
 6320        let mut deletion_ranges = Vec::new();
 6321        let mut last_outdent = None;
 6322        {
 6323            let buffer = self.buffer.read(cx);
 6324            let snapshot = buffer.snapshot(cx);
 6325            for selection in &selections {
 6326                let settings = buffer.settings_at(selection.start, cx);
 6327                let tab_size = settings.tab_size.get();
 6328                let mut rows = selection.spanned_rows(false, &display_map);
 6329
 6330                // Avoid re-outdenting a row that has already been outdented by a
 6331                // previous selection.
 6332                if let Some(last_row) = last_outdent {
 6333                    if last_row == rows.start {
 6334                        rows.start = rows.start.next_row();
 6335                    }
 6336                }
 6337                let has_multiple_rows = rows.len() > 1;
 6338                for row in rows.iter_rows() {
 6339                    let indent_size = snapshot.indent_size_for_line(row);
 6340                    if indent_size.len > 0 {
 6341                        let deletion_len = match indent_size.kind {
 6342                            IndentKind::Space => {
 6343                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6344                                if columns_to_prev_tab_stop == 0 {
 6345                                    tab_size
 6346                                } else {
 6347                                    columns_to_prev_tab_stop
 6348                                }
 6349                            }
 6350                            IndentKind::Tab => 1,
 6351                        };
 6352                        let start = if has_multiple_rows
 6353                            || deletion_len > selection.start.column
 6354                            || indent_size.len < selection.start.column
 6355                        {
 6356                            0
 6357                        } else {
 6358                            selection.start.column - deletion_len
 6359                        };
 6360                        deletion_ranges.push(
 6361                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6362                        );
 6363                        last_outdent = Some(row);
 6364                    }
 6365                }
 6366            }
 6367        }
 6368
 6369        self.transact(cx, |this, cx| {
 6370            this.buffer.update(cx, |buffer, cx| {
 6371                let empty_str: Arc<str> = Arc::default();
 6372                buffer.edit(
 6373                    deletion_ranges
 6374                        .into_iter()
 6375                        .map(|range| (range, empty_str.clone())),
 6376                    None,
 6377                    cx,
 6378                );
 6379            });
 6380            let selections = this.selections.all::<usize>(cx);
 6381            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6382        });
 6383    }
 6384
 6385    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6386        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6387        let selections = self.selections.all::<Point>(cx);
 6388
 6389        let mut new_cursors = Vec::new();
 6390        let mut edit_ranges = Vec::new();
 6391        let mut selections = selections.iter().peekable();
 6392        while let Some(selection) = selections.next() {
 6393            let mut rows = selection.spanned_rows(false, &display_map);
 6394            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6395
 6396            // Accumulate contiguous regions of rows that we want to delete.
 6397            while let Some(next_selection) = selections.peek() {
 6398                let next_rows = next_selection.spanned_rows(false, &display_map);
 6399                if next_rows.start <= rows.end {
 6400                    rows.end = next_rows.end;
 6401                    selections.next().unwrap();
 6402                } else {
 6403                    break;
 6404                }
 6405            }
 6406
 6407            let buffer = &display_map.buffer_snapshot;
 6408            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6409            let edit_end;
 6410            let cursor_buffer_row;
 6411            if buffer.max_point().row >= rows.end.0 {
 6412                // If there's a line after the range, delete the \n from the end of the row range
 6413                // and position the cursor on the next line.
 6414                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6415                cursor_buffer_row = rows.end;
 6416            } else {
 6417                // If there isn't a line after the range, delete the \n from the line before the
 6418                // start of the row range and position the cursor there.
 6419                edit_start = edit_start.saturating_sub(1);
 6420                edit_end = buffer.len();
 6421                cursor_buffer_row = rows.start.previous_row();
 6422            }
 6423
 6424            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6425            *cursor.column_mut() =
 6426                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6427
 6428            new_cursors.push((
 6429                selection.id,
 6430                buffer.anchor_after(cursor.to_point(&display_map)),
 6431            ));
 6432            edit_ranges.push(edit_start..edit_end);
 6433        }
 6434
 6435        self.transact(cx, |this, cx| {
 6436            let buffer = this.buffer.update(cx, |buffer, cx| {
 6437                let empty_str: Arc<str> = Arc::default();
 6438                buffer.edit(
 6439                    edit_ranges
 6440                        .into_iter()
 6441                        .map(|range| (range, empty_str.clone())),
 6442                    None,
 6443                    cx,
 6444                );
 6445                buffer.snapshot(cx)
 6446            });
 6447            let new_selections = new_cursors
 6448                .into_iter()
 6449                .map(|(id, cursor)| {
 6450                    let cursor = cursor.to_point(&buffer);
 6451                    Selection {
 6452                        id,
 6453                        start: cursor,
 6454                        end: cursor,
 6455                        reversed: false,
 6456                        goal: SelectionGoal::None,
 6457                    }
 6458                })
 6459                .collect();
 6460
 6461            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6462                s.select(new_selections);
 6463            });
 6464        });
 6465    }
 6466
 6467    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6468        if self.read_only(cx) {
 6469            return;
 6470        }
 6471        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6472        for selection in self.selections.all::<Point>(cx) {
 6473            let start = MultiBufferRow(selection.start.row);
 6474            // Treat single line selections as if they include the next line. Otherwise this action
 6475            // would do nothing for single line selections individual cursors.
 6476            let end = if selection.start.row == selection.end.row {
 6477                MultiBufferRow(selection.start.row + 1)
 6478            } else {
 6479                MultiBufferRow(selection.end.row)
 6480            };
 6481
 6482            if let Some(last_row_range) = row_ranges.last_mut() {
 6483                if start <= last_row_range.end {
 6484                    last_row_range.end = end;
 6485                    continue;
 6486                }
 6487            }
 6488            row_ranges.push(start..end);
 6489        }
 6490
 6491        let snapshot = self.buffer.read(cx).snapshot(cx);
 6492        let mut cursor_positions = Vec::new();
 6493        for row_range in &row_ranges {
 6494            let anchor = snapshot.anchor_before(Point::new(
 6495                row_range.end.previous_row().0,
 6496                snapshot.line_len(row_range.end.previous_row()),
 6497            ));
 6498            cursor_positions.push(anchor..anchor);
 6499        }
 6500
 6501        self.transact(cx, |this, cx| {
 6502            for row_range in row_ranges.into_iter().rev() {
 6503                for row in row_range.iter_rows().rev() {
 6504                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6505                    let next_line_row = row.next_row();
 6506                    let indent = snapshot.indent_size_for_line(next_line_row);
 6507                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6508
 6509                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6510                        " "
 6511                    } else {
 6512                        ""
 6513                    };
 6514
 6515                    this.buffer.update(cx, |buffer, cx| {
 6516                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6517                    });
 6518                }
 6519            }
 6520
 6521            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6522                s.select_anchor_ranges(cursor_positions)
 6523            });
 6524        });
 6525    }
 6526
 6527    pub fn sort_lines_case_sensitive(
 6528        &mut self,
 6529        _: &SortLinesCaseSensitive,
 6530        cx: &mut ViewContext<Self>,
 6531    ) {
 6532        self.manipulate_lines(cx, |lines| lines.sort())
 6533    }
 6534
 6535    pub fn sort_lines_case_insensitive(
 6536        &mut self,
 6537        _: &SortLinesCaseInsensitive,
 6538        cx: &mut ViewContext<Self>,
 6539    ) {
 6540        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6541    }
 6542
 6543    pub fn unique_lines_case_insensitive(
 6544        &mut self,
 6545        _: &UniqueLinesCaseInsensitive,
 6546        cx: &mut ViewContext<Self>,
 6547    ) {
 6548        self.manipulate_lines(cx, |lines| {
 6549            let mut seen = HashSet::default();
 6550            lines.retain(|line| seen.insert(line.to_lowercase()));
 6551        })
 6552    }
 6553
 6554    pub fn unique_lines_case_sensitive(
 6555        &mut self,
 6556        _: &UniqueLinesCaseSensitive,
 6557        cx: &mut ViewContext<Self>,
 6558    ) {
 6559        self.manipulate_lines(cx, |lines| {
 6560            let mut seen = HashSet::default();
 6561            lines.retain(|line| seen.insert(*line));
 6562        })
 6563    }
 6564
 6565    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6566        let mut revert_changes = HashMap::default();
 6567        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6568        for hunk in hunks_for_rows(
 6569            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6570            &multi_buffer_snapshot,
 6571        ) {
 6572            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6573        }
 6574        if !revert_changes.is_empty() {
 6575            self.transact(cx, |editor, cx| {
 6576                editor.revert(revert_changes, cx);
 6577            });
 6578        }
 6579    }
 6580
 6581    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6582        let Some(project) = self.project.clone() else {
 6583            return;
 6584        };
 6585        self.reload(project, cx).detach_and_notify_err(cx);
 6586    }
 6587
 6588    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6589        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6590        if !revert_changes.is_empty() {
 6591            self.transact(cx, |editor, cx| {
 6592                editor.revert(revert_changes, cx);
 6593            });
 6594        }
 6595    }
 6596
 6597    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6598        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6599            let project_path = buffer.read(cx).project_path(cx)?;
 6600            let project = self.project.as_ref()?.read(cx);
 6601            let entry = project.entry_for_path(&project_path, cx)?;
 6602            let parent = match &entry.canonical_path {
 6603                Some(canonical_path) => canonical_path.to_path_buf(),
 6604                None => project.absolute_path(&project_path, cx)?,
 6605            }
 6606            .parent()?
 6607            .to_path_buf();
 6608            Some(parent)
 6609        }) {
 6610            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6611        }
 6612    }
 6613
 6614    fn gather_revert_changes(
 6615        &mut self,
 6616        selections: &[Selection<Anchor>],
 6617        cx: &mut ViewContext<'_, Editor>,
 6618    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6619        let mut revert_changes = HashMap::default();
 6620        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6621        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6622            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6623        }
 6624        revert_changes
 6625    }
 6626
 6627    pub fn prepare_revert_change(
 6628        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6629        multi_buffer: &Model<MultiBuffer>,
 6630        hunk: &MultiBufferDiffHunk,
 6631        cx: &AppContext,
 6632    ) -> Option<()> {
 6633        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6634        let buffer = buffer.read(cx);
 6635        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6636        let buffer_snapshot = buffer.snapshot();
 6637        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6638        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6639            probe
 6640                .0
 6641                .start
 6642                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6643                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6644        }) {
 6645            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6646            Some(())
 6647        } else {
 6648            None
 6649        }
 6650    }
 6651
 6652    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6653        self.manipulate_lines(cx, |lines| lines.reverse())
 6654    }
 6655
 6656    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6657        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6658    }
 6659
 6660    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6661    where
 6662        Fn: FnMut(&mut Vec<&str>),
 6663    {
 6664        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6665        let buffer = self.buffer.read(cx).snapshot(cx);
 6666
 6667        let mut edits = Vec::new();
 6668
 6669        let selections = self.selections.all::<Point>(cx);
 6670        let mut selections = selections.iter().peekable();
 6671        let mut contiguous_row_selections = Vec::new();
 6672        let mut new_selections = Vec::new();
 6673        let mut added_lines = 0;
 6674        let mut removed_lines = 0;
 6675
 6676        while let Some(selection) = selections.next() {
 6677            let (start_row, end_row) = consume_contiguous_rows(
 6678                &mut contiguous_row_selections,
 6679                selection,
 6680                &display_map,
 6681                &mut selections,
 6682            );
 6683
 6684            let start_point = Point::new(start_row.0, 0);
 6685            let end_point = Point::new(
 6686                end_row.previous_row().0,
 6687                buffer.line_len(end_row.previous_row()),
 6688            );
 6689            let text = buffer
 6690                .text_for_range(start_point..end_point)
 6691                .collect::<String>();
 6692
 6693            let mut lines = text.split('\n').collect_vec();
 6694
 6695            let lines_before = lines.len();
 6696            callback(&mut lines);
 6697            let lines_after = lines.len();
 6698
 6699            edits.push((start_point..end_point, lines.join("\n")));
 6700
 6701            // Selections must change based on added and removed line count
 6702            let start_row =
 6703                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6704            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6705            new_selections.push(Selection {
 6706                id: selection.id,
 6707                start: start_row,
 6708                end: end_row,
 6709                goal: SelectionGoal::None,
 6710                reversed: selection.reversed,
 6711            });
 6712
 6713            if lines_after > lines_before {
 6714                added_lines += lines_after - lines_before;
 6715            } else if lines_before > lines_after {
 6716                removed_lines += lines_before - lines_after;
 6717            }
 6718        }
 6719
 6720        self.transact(cx, |this, cx| {
 6721            let buffer = this.buffer.update(cx, |buffer, cx| {
 6722                buffer.edit(edits, None, cx);
 6723                buffer.snapshot(cx)
 6724            });
 6725
 6726            // Recalculate offsets on newly edited buffer
 6727            let new_selections = new_selections
 6728                .iter()
 6729                .map(|s| {
 6730                    let start_point = Point::new(s.start.0, 0);
 6731                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6732                    Selection {
 6733                        id: s.id,
 6734                        start: buffer.point_to_offset(start_point),
 6735                        end: buffer.point_to_offset(end_point),
 6736                        goal: s.goal,
 6737                        reversed: s.reversed,
 6738                    }
 6739                })
 6740                .collect();
 6741
 6742            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6743                s.select(new_selections);
 6744            });
 6745
 6746            this.request_autoscroll(Autoscroll::fit(), cx);
 6747        });
 6748    }
 6749
 6750    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6751        self.manipulate_text(cx, |text| text.to_uppercase())
 6752    }
 6753
 6754    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6755        self.manipulate_text(cx, |text| text.to_lowercase())
 6756    }
 6757
 6758    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6759        self.manipulate_text(cx, |text| {
 6760            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6761            // https://github.com/rutrum/convert-case/issues/16
 6762            text.split('\n')
 6763                .map(|line| line.to_case(Case::Title))
 6764                .join("\n")
 6765        })
 6766    }
 6767
 6768    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6769        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6770    }
 6771
 6772    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6773        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6774    }
 6775
 6776    pub fn convert_to_upper_camel_case(
 6777        &mut self,
 6778        _: &ConvertToUpperCamelCase,
 6779        cx: &mut ViewContext<Self>,
 6780    ) {
 6781        self.manipulate_text(cx, |text| {
 6782            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6783            // https://github.com/rutrum/convert-case/issues/16
 6784            text.split('\n')
 6785                .map(|line| line.to_case(Case::UpperCamel))
 6786                .join("\n")
 6787        })
 6788    }
 6789
 6790    pub fn convert_to_lower_camel_case(
 6791        &mut self,
 6792        _: &ConvertToLowerCamelCase,
 6793        cx: &mut ViewContext<Self>,
 6794    ) {
 6795        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6796    }
 6797
 6798    pub fn convert_to_opposite_case(
 6799        &mut self,
 6800        _: &ConvertToOppositeCase,
 6801        cx: &mut ViewContext<Self>,
 6802    ) {
 6803        self.manipulate_text(cx, |text| {
 6804            text.chars()
 6805                .fold(String::with_capacity(text.len()), |mut t, c| {
 6806                    if c.is_uppercase() {
 6807                        t.extend(c.to_lowercase());
 6808                    } else {
 6809                        t.extend(c.to_uppercase());
 6810                    }
 6811                    t
 6812                })
 6813        })
 6814    }
 6815
 6816    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6817    where
 6818        Fn: FnMut(&str) -> String,
 6819    {
 6820        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6821        let buffer = self.buffer.read(cx).snapshot(cx);
 6822
 6823        let mut new_selections = Vec::new();
 6824        let mut edits = Vec::new();
 6825        let mut selection_adjustment = 0i32;
 6826
 6827        for selection in self.selections.all::<usize>(cx) {
 6828            let selection_is_empty = selection.is_empty();
 6829
 6830            let (start, end) = if selection_is_empty {
 6831                let word_range = movement::surrounding_word(
 6832                    &display_map,
 6833                    selection.start.to_display_point(&display_map),
 6834                );
 6835                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6836                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6837                (start, end)
 6838            } else {
 6839                (selection.start, selection.end)
 6840            };
 6841
 6842            let text = buffer.text_for_range(start..end).collect::<String>();
 6843            let old_length = text.len() as i32;
 6844            let text = callback(&text);
 6845
 6846            new_selections.push(Selection {
 6847                start: (start as i32 - selection_adjustment) as usize,
 6848                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6849                goal: SelectionGoal::None,
 6850                ..selection
 6851            });
 6852
 6853            selection_adjustment += old_length - text.len() as i32;
 6854
 6855            edits.push((start..end, text));
 6856        }
 6857
 6858        self.transact(cx, |this, cx| {
 6859            this.buffer.update(cx, |buffer, cx| {
 6860                buffer.edit(edits, None, cx);
 6861            });
 6862
 6863            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6864                s.select(new_selections);
 6865            });
 6866
 6867            this.request_autoscroll(Autoscroll::fit(), cx);
 6868        });
 6869    }
 6870
 6871    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6872        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6873        let buffer = &display_map.buffer_snapshot;
 6874        let selections = self.selections.all::<Point>(cx);
 6875
 6876        let mut edits = Vec::new();
 6877        let mut selections_iter = selections.iter().peekable();
 6878        while let Some(selection) = selections_iter.next() {
 6879            // Avoid duplicating the same lines twice.
 6880            let mut rows = selection.spanned_rows(false, &display_map);
 6881
 6882            while let Some(next_selection) = selections_iter.peek() {
 6883                let next_rows = next_selection.spanned_rows(false, &display_map);
 6884                if next_rows.start < rows.end {
 6885                    rows.end = next_rows.end;
 6886                    selections_iter.next().unwrap();
 6887                } else {
 6888                    break;
 6889                }
 6890            }
 6891
 6892            // Copy the text from the selected row region and splice it either at the start
 6893            // or end of the region.
 6894            let start = Point::new(rows.start.0, 0);
 6895            let end = Point::new(
 6896                rows.end.previous_row().0,
 6897                buffer.line_len(rows.end.previous_row()),
 6898            );
 6899            let text = buffer
 6900                .text_for_range(start..end)
 6901                .chain(Some("\n"))
 6902                .collect::<String>();
 6903            let insert_location = if upwards {
 6904                Point::new(rows.end.0, 0)
 6905            } else {
 6906                start
 6907            };
 6908            edits.push((insert_location..insert_location, text));
 6909        }
 6910
 6911        self.transact(cx, |this, cx| {
 6912            this.buffer.update(cx, |buffer, cx| {
 6913                buffer.edit(edits, None, cx);
 6914            });
 6915
 6916            this.request_autoscroll(Autoscroll::fit(), cx);
 6917        });
 6918    }
 6919
 6920    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6921        self.duplicate_line(true, cx);
 6922    }
 6923
 6924    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6925        self.duplicate_line(false, cx);
 6926    }
 6927
 6928    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6929        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6930        let buffer = self.buffer.read(cx).snapshot(cx);
 6931
 6932        let mut edits = Vec::new();
 6933        let mut unfold_ranges = Vec::new();
 6934        let mut refold_creases = Vec::new();
 6935
 6936        let selections = self.selections.all::<Point>(cx);
 6937        let mut selections = selections.iter().peekable();
 6938        let mut contiguous_row_selections = Vec::new();
 6939        let mut new_selections = Vec::new();
 6940
 6941        while let Some(selection) = selections.next() {
 6942            // Find all the selections that span a contiguous row range
 6943            let (start_row, end_row) = consume_contiguous_rows(
 6944                &mut contiguous_row_selections,
 6945                selection,
 6946                &display_map,
 6947                &mut selections,
 6948            );
 6949
 6950            // Move the text spanned by the row range to be before the line preceding the row range
 6951            if start_row.0 > 0 {
 6952                let range_to_move = Point::new(
 6953                    start_row.previous_row().0,
 6954                    buffer.line_len(start_row.previous_row()),
 6955                )
 6956                    ..Point::new(
 6957                        end_row.previous_row().0,
 6958                        buffer.line_len(end_row.previous_row()),
 6959                    );
 6960                let insertion_point = display_map
 6961                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6962                    .0;
 6963
 6964                // Don't move lines across excerpts
 6965                if buffer
 6966                    .excerpt_boundaries_in_range((
 6967                        Bound::Excluded(insertion_point),
 6968                        Bound::Included(range_to_move.end),
 6969                    ))
 6970                    .next()
 6971                    .is_none()
 6972                {
 6973                    let text = buffer
 6974                        .text_for_range(range_to_move.clone())
 6975                        .flat_map(|s| s.chars())
 6976                        .skip(1)
 6977                        .chain(['\n'])
 6978                        .collect::<String>();
 6979
 6980                    edits.push((
 6981                        buffer.anchor_after(range_to_move.start)
 6982                            ..buffer.anchor_before(range_to_move.end),
 6983                        String::new(),
 6984                    ));
 6985                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6986                    edits.push((insertion_anchor..insertion_anchor, text));
 6987
 6988                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6989
 6990                    // Move selections up
 6991                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6992                        |mut selection| {
 6993                            selection.start.row -= row_delta;
 6994                            selection.end.row -= row_delta;
 6995                            selection
 6996                        },
 6997                    ));
 6998
 6999                    // Move folds up
 7000                    unfold_ranges.push(range_to_move.clone());
 7001                    for fold in display_map.folds_in_range(
 7002                        buffer.anchor_before(range_to_move.start)
 7003                            ..buffer.anchor_after(range_to_move.end),
 7004                    ) {
 7005                        let mut start = fold.range.start.to_point(&buffer);
 7006                        let mut end = fold.range.end.to_point(&buffer);
 7007                        start.row -= row_delta;
 7008                        end.row -= row_delta;
 7009                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7010                    }
 7011                }
 7012            }
 7013
 7014            // If we didn't move line(s), preserve the existing selections
 7015            new_selections.append(&mut contiguous_row_selections);
 7016        }
 7017
 7018        self.transact(cx, |this, cx| {
 7019            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7020            this.buffer.update(cx, |buffer, cx| {
 7021                for (range, text) in edits {
 7022                    buffer.edit([(range, text)], None, cx);
 7023                }
 7024            });
 7025            this.fold_creases(refold_creases, true, cx);
 7026            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7027                s.select(new_selections);
 7028            })
 7029        });
 7030    }
 7031
 7032    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 7033        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7034        let buffer = self.buffer.read(cx).snapshot(cx);
 7035
 7036        let mut edits = Vec::new();
 7037        let mut unfold_ranges = Vec::new();
 7038        let mut refold_creases = Vec::new();
 7039
 7040        let selections = self.selections.all::<Point>(cx);
 7041        let mut selections = selections.iter().peekable();
 7042        let mut contiguous_row_selections = Vec::new();
 7043        let mut new_selections = Vec::new();
 7044
 7045        while let Some(selection) = selections.next() {
 7046            // Find all the selections that span a contiguous row range
 7047            let (start_row, end_row) = consume_contiguous_rows(
 7048                &mut contiguous_row_selections,
 7049                selection,
 7050                &display_map,
 7051                &mut selections,
 7052            );
 7053
 7054            // Move the text spanned by the row range to be after the last line of the row range
 7055            if end_row.0 <= buffer.max_point().row {
 7056                let range_to_move =
 7057                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7058                let insertion_point = display_map
 7059                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7060                    .0;
 7061
 7062                // Don't move lines across excerpt boundaries
 7063                if buffer
 7064                    .excerpt_boundaries_in_range((
 7065                        Bound::Excluded(range_to_move.start),
 7066                        Bound::Included(insertion_point),
 7067                    ))
 7068                    .next()
 7069                    .is_none()
 7070                {
 7071                    let mut text = String::from("\n");
 7072                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7073                    text.pop(); // Drop trailing newline
 7074                    edits.push((
 7075                        buffer.anchor_after(range_to_move.start)
 7076                            ..buffer.anchor_before(range_to_move.end),
 7077                        String::new(),
 7078                    ));
 7079                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7080                    edits.push((insertion_anchor..insertion_anchor, text));
 7081
 7082                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7083
 7084                    // Move selections down
 7085                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7086                        |mut selection| {
 7087                            selection.start.row += row_delta;
 7088                            selection.end.row += row_delta;
 7089                            selection
 7090                        },
 7091                    ));
 7092
 7093                    // Move folds down
 7094                    unfold_ranges.push(range_to_move.clone());
 7095                    for fold in display_map.folds_in_range(
 7096                        buffer.anchor_before(range_to_move.start)
 7097                            ..buffer.anchor_after(range_to_move.end),
 7098                    ) {
 7099                        let mut start = fold.range.start.to_point(&buffer);
 7100                        let mut end = fold.range.end.to_point(&buffer);
 7101                        start.row += row_delta;
 7102                        end.row += row_delta;
 7103                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7104                    }
 7105                }
 7106            }
 7107
 7108            // If we didn't move line(s), preserve the existing selections
 7109            new_selections.append(&mut contiguous_row_selections);
 7110        }
 7111
 7112        self.transact(cx, |this, cx| {
 7113            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7114            this.buffer.update(cx, |buffer, cx| {
 7115                for (range, text) in edits {
 7116                    buffer.edit([(range, text)], None, cx);
 7117                }
 7118            });
 7119            this.fold_creases(refold_creases, true, cx);
 7120            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7121        });
 7122    }
 7123
 7124    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7125        let text_layout_details = &self.text_layout_details(cx);
 7126        self.transact(cx, |this, cx| {
 7127            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7128                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7129                let line_mode = s.line_mode;
 7130                s.move_with(|display_map, selection| {
 7131                    if !selection.is_empty() || line_mode {
 7132                        return;
 7133                    }
 7134
 7135                    let mut head = selection.head();
 7136                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7137                    if head.column() == display_map.line_len(head.row()) {
 7138                        transpose_offset = display_map
 7139                            .buffer_snapshot
 7140                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7141                    }
 7142
 7143                    if transpose_offset == 0 {
 7144                        return;
 7145                    }
 7146
 7147                    *head.column_mut() += 1;
 7148                    head = display_map.clip_point(head, Bias::Right);
 7149                    let goal = SelectionGoal::HorizontalPosition(
 7150                        display_map
 7151                            .x_for_display_point(head, text_layout_details)
 7152                            .into(),
 7153                    );
 7154                    selection.collapse_to(head, goal);
 7155
 7156                    let transpose_start = display_map
 7157                        .buffer_snapshot
 7158                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7159                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7160                        let transpose_end = display_map
 7161                            .buffer_snapshot
 7162                            .clip_offset(transpose_offset + 1, Bias::Right);
 7163                        if let Some(ch) =
 7164                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7165                        {
 7166                            edits.push((transpose_start..transpose_offset, String::new()));
 7167                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7168                        }
 7169                    }
 7170                });
 7171                edits
 7172            });
 7173            this.buffer
 7174                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7175            let selections = this.selections.all::<usize>(cx);
 7176            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7177                s.select(selections);
 7178            });
 7179        });
 7180    }
 7181
 7182    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7183        self.rewrap_impl(IsVimMode::No, cx)
 7184    }
 7185
 7186    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7187        let buffer = self.buffer.read(cx).snapshot(cx);
 7188        let selections = self.selections.all::<Point>(cx);
 7189        let mut selections = selections.iter().peekable();
 7190
 7191        let mut edits = Vec::new();
 7192        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7193
 7194        while let Some(selection) = selections.next() {
 7195            let mut start_row = selection.start.row;
 7196            let mut end_row = selection.end.row;
 7197
 7198            // Skip selections that overlap with a range that has already been rewrapped.
 7199            let selection_range = start_row..end_row;
 7200            if rewrapped_row_ranges
 7201                .iter()
 7202                .any(|range| range.overlaps(&selection_range))
 7203            {
 7204                continue;
 7205            }
 7206
 7207            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7208
 7209            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7210                match language_scope.language_name().0.as_ref() {
 7211                    "Markdown" | "Plain Text" => {
 7212                        should_rewrap = true;
 7213                    }
 7214                    _ => {}
 7215                }
 7216            }
 7217
 7218            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7219
 7220            // Since not all lines in the selection may be at the same indent
 7221            // level, choose the indent size that is the most common between all
 7222            // of the lines.
 7223            //
 7224            // If there is a tie, we use the deepest indent.
 7225            let (indent_size, indent_end) = {
 7226                let mut indent_size_occurrences = HashMap::default();
 7227                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7228
 7229                for row in start_row..=end_row {
 7230                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7231                    rows_by_indent_size.entry(indent).or_default().push(row);
 7232                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7233                }
 7234
 7235                let indent_size = indent_size_occurrences
 7236                    .into_iter()
 7237                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7238                    .map(|(indent, _)| indent)
 7239                    .unwrap_or_default();
 7240                let row = rows_by_indent_size[&indent_size][0];
 7241                let indent_end = Point::new(row, indent_size.len);
 7242
 7243                (indent_size, indent_end)
 7244            };
 7245
 7246            let mut line_prefix = indent_size.chars().collect::<String>();
 7247
 7248            if let Some(comment_prefix) =
 7249                buffer
 7250                    .language_scope_at(selection.head())
 7251                    .and_then(|language| {
 7252                        language
 7253                            .line_comment_prefixes()
 7254                            .iter()
 7255                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7256                            .cloned()
 7257                    })
 7258            {
 7259                line_prefix.push_str(&comment_prefix);
 7260                should_rewrap = true;
 7261            }
 7262
 7263            if !should_rewrap {
 7264                continue;
 7265            }
 7266
 7267            if selection.is_empty() {
 7268                'expand_upwards: while start_row > 0 {
 7269                    let prev_row = start_row - 1;
 7270                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7271                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7272                    {
 7273                        start_row = prev_row;
 7274                    } else {
 7275                        break 'expand_upwards;
 7276                    }
 7277                }
 7278
 7279                'expand_downwards: while end_row < buffer.max_point().row {
 7280                    let next_row = end_row + 1;
 7281                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7282                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7283                    {
 7284                        end_row = next_row;
 7285                    } else {
 7286                        break 'expand_downwards;
 7287                    }
 7288                }
 7289            }
 7290
 7291            let start = Point::new(start_row, 0);
 7292            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7293            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7294            let Some(lines_without_prefixes) = selection_text
 7295                .lines()
 7296                .map(|line| {
 7297                    line.strip_prefix(&line_prefix)
 7298                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7299                        .ok_or_else(|| {
 7300                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7301                        })
 7302                })
 7303                .collect::<Result<Vec<_>, _>>()
 7304                .log_err()
 7305            else {
 7306                continue;
 7307            };
 7308
 7309            let wrap_column = buffer
 7310                .settings_at(Point::new(start_row, 0), cx)
 7311                .preferred_line_length as usize;
 7312            let wrapped_text = wrap_with_prefix(
 7313                line_prefix,
 7314                lines_without_prefixes.join(" "),
 7315                wrap_column,
 7316                tab_size,
 7317            );
 7318
 7319            // TODO: should always use char-based diff while still supporting cursor behavior that
 7320            // matches vim.
 7321            let diff = match is_vim_mode {
 7322                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7323                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7324            };
 7325            let mut offset = start.to_offset(&buffer);
 7326            let mut moved_since_edit = true;
 7327
 7328            for change in diff.iter_all_changes() {
 7329                let value = change.value();
 7330                match change.tag() {
 7331                    ChangeTag::Equal => {
 7332                        offset += value.len();
 7333                        moved_since_edit = true;
 7334                    }
 7335                    ChangeTag::Delete => {
 7336                        let start = buffer.anchor_after(offset);
 7337                        let end = buffer.anchor_before(offset + value.len());
 7338
 7339                        if moved_since_edit {
 7340                            edits.push((start..end, String::new()));
 7341                        } else {
 7342                            edits.last_mut().unwrap().0.end = end;
 7343                        }
 7344
 7345                        offset += value.len();
 7346                        moved_since_edit = false;
 7347                    }
 7348                    ChangeTag::Insert => {
 7349                        if moved_since_edit {
 7350                            let anchor = buffer.anchor_after(offset);
 7351                            edits.push((anchor..anchor, value.to_string()));
 7352                        } else {
 7353                            edits.last_mut().unwrap().1.push_str(value);
 7354                        }
 7355
 7356                        moved_since_edit = false;
 7357                    }
 7358                }
 7359            }
 7360
 7361            rewrapped_row_ranges.push(start_row..=end_row);
 7362        }
 7363
 7364        self.buffer
 7365            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7366    }
 7367
 7368    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7369        let mut text = String::new();
 7370        let buffer = self.buffer.read(cx).snapshot(cx);
 7371        let mut selections = self.selections.all::<Point>(cx);
 7372        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7373        {
 7374            let max_point = buffer.max_point();
 7375            let mut is_first = true;
 7376            for selection in &mut selections {
 7377                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7378                if is_entire_line {
 7379                    selection.start = Point::new(selection.start.row, 0);
 7380                    if !selection.is_empty() && selection.end.column == 0 {
 7381                        selection.end = cmp::min(max_point, selection.end);
 7382                    } else {
 7383                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7384                    }
 7385                    selection.goal = SelectionGoal::None;
 7386                }
 7387                if is_first {
 7388                    is_first = false;
 7389                } else {
 7390                    text += "\n";
 7391                }
 7392                let mut len = 0;
 7393                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7394                    text.push_str(chunk);
 7395                    len += chunk.len();
 7396                }
 7397                clipboard_selections.push(ClipboardSelection {
 7398                    len,
 7399                    is_entire_line,
 7400                    first_line_indent: buffer
 7401                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7402                        .len,
 7403                });
 7404            }
 7405        }
 7406
 7407        self.transact(cx, |this, cx| {
 7408            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7409                s.select(selections);
 7410            });
 7411            this.insert("", cx);
 7412            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7413                text,
 7414                clipboard_selections,
 7415            ));
 7416        });
 7417    }
 7418
 7419    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7420        let selections = self.selections.all::<Point>(cx);
 7421        let buffer = self.buffer.read(cx).read(cx);
 7422        let mut text = String::new();
 7423
 7424        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7425        {
 7426            let max_point = buffer.max_point();
 7427            let mut is_first = true;
 7428            for selection in selections.iter() {
 7429                let mut start = selection.start;
 7430                let mut end = selection.end;
 7431                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7432                if is_entire_line {
 7433                    start = Point::new(start.row, 0);
 7434                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7435                }
 7436                if is_first {
 7437                    is_first = false;
 7438                } else {
 7439                    text += "\n";
 7440                }
 7441                let mut len = 0;
 7442                for chunk in buffer.text_for_range(start..end) {
 7443                    text.push_str(chunk);
 7444                    len += chunk.len();
 7445                }
 7446                clipboard_selections.push(ClipboardSelection {
 7447                    len,
 7448                    is_entire_line,
 7449                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7450                });
 7451            }
 7452        }
 7453
 7454        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7455            text,
 7456            clipboard_selections,
 7457        ));
 7458    }
 7459
 7460    pub fn do_paste(
 7461        &mut self,
 7462        text: &String,
 7463        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7464        handle_entire_lines: bool,
 7465        cx: &mut ViewContext<Self>,
 7466    ) {
 7467        if self.read_only(cx) {
 7468            return;
 7469        }
 7470
 7471        let clipboard_text = Cow::Borrowed(text);
 7472
 7473        self.transact(cx, |this, cx| {
 7474            if let Some(mut clipboard_selections) = clipboard_selections {
 7475                let old_selections = this.selections.all::<usize>(cx);
 7476                let all_selections_were_entire_line =
 7477                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7478                let first_selection_indent_column =
 7479                    clipboard_selections.first().map(|s| s.first_line_indent);
 7480                if clipboard_selections.len() != old_selections.len() {
 7481                    clipboard_selections.drain(..);
 7482                }
 7483                let cursor_offset = this.selections.last::<usize>(cx).head();
 7484                let mut auto_indent_on_paste = true;
 7485
 7486                this.buffer.update(cx, |buffer, cx| {
 7487                    let snapshot = buffer.read(cx);
 7488                    auto_indent_on_paste =
 7489                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7490
 7491                    let mut start_offset = 0;
 7492                    let mut edits = Vec::new();
 7493                    let mut original_indent_columns = Vec::new();
 7494                    for (ix, selection) in old_selections.iter().enumerate() {
 7495                        let to_insert;
 7496                        let entire_line;
 7497                        let original_indent_column;
 7498                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7499                            let end_offset = start_offset + clipboard_selection.len;
 7500                            to_insert = &clipboard_text[start_offset..end_offset];
 7501                            entire_line = clipboard_selection.is_entire_line;
 7502                            start_offset = end_offset + 1;
 7503                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7504                        } else {
 7505                            to_insert = clipboard_text.as_str();
 7506                            entire_line = all_selections_were_entire_line;
 7507                            original_indent_column = first_selection_indent_column
 7508                        }
 7509
 7510                        // If the corresponding selection was empty when this slice of the
 7511                        // clipboard text was written, then the entire line containing the
 7512                        // selection was copied. If this selection is also currently empty,
 7513                        // then paste the line before the current line of the buffer.
 7514                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7515                            let column = selection.start.to_point(&snapshot).column as usize;
 7516                            let line_start = selection.start - column;
 7517                            line_start..line_start
 7518                        } else {
 7519                            selection.range()
 7520                        };
 7521
 7522                        edits.push((range, to_insert));
 7523                        original_indent_columns.extend(original_indent_column);
 7524                    }
 7525                    drop(snapshot);
 7526
 7527                    buffer.edit(
 7528                        edits,
 7529                        if auto_indent_on_paste {
 7530                            Some(AutoindentMode::Block {
 7531                                original_indent_columns,
 7532                            })
 7533                        } else {
 7534                            None
 7535                        },
 7536                        cx,
 7537                    );
 7538                });
 7539
 7540                let selections = this.selections.all::<usize>(cx);
 7541                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7542            } else {
 7543                this.insert(&clipboard_text, cx);
 7544            }
 7545        });
 7546    }
 7547
 7548    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7549        if let Some(item) = cx.read_from_clipboard() {
 7550            let entries = item.entries();
 7551
 7552            match entries.first() {
 7553                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7554                // of all the pasted entries.
 7555                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7556                    .do_paste(
 7557                        clipboard_string.text(),
 7558                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7559                        true,
 7560                        cx,
 7561                    ),
 7562                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7563            }
 7564        }
 7565    }
 7566
 7567    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7568        if self.read_only(cx) {
 7569            return;
 7570        }
 7571
 7572        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7573            if let Some((selections, _)) =
 7574                self.selection_history.transaction(transaction_id).cloned()
 7575            {
 7576                self.change_selections(None, cx, |s| {
 7577                    s.select_anchors(selections.to_vec());
 7578                });
 7579            }
 7580            self.request_autoscroll(Autoscroll::fit(), cx);
 7581            self.unmark_text(cx);
 7582            self.refresh_inline_completion(true, false, cx);
 7583            cx.emit(EditorEvent::Edited { transaction_id });
 7584            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7585        }
 7586    }
 7587
 7588    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7589        if self.read_only(cx) {
 7590            return;
 7591        }
 7592
 7593        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7594            if let Some((_, Some(selections))) =
 7595                self.selection_history.transaction(transaction_id).cloned()
 7596            {
 7597                self.change_selections(None, cx, |s| {
 7598                    s.select_anchors(selections.to_vec());
 7599                });
 7600            }
 7601            self.request_autoscroll(Autoscroll::fit(), cx);
 7602            self.unmark_text(cx);
 7603            self.refresh_inline_completion(true, false, cx);
 7604            cx.emit(EditorEvent::Edited { transaction_id });
 7605        }
 7606    }
 7607
 7608    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7609        self.buffer
 7610            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7611    }
 7612
 7613    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7614        self.buffer
 7615            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7616    }
 7617
 7618    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7619        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7620            let line_mode = s.line_mode;
 7621            s.move_with(|map, selection| {
 7622                let cursor = if selection.is_empty() && !line_mode {
 7623                    movement::left(map, selection.start)
 7624                } else {
 7625                    selection.start
 7626                };
 7627                selection.collapse_to(cursor, SelectionGoal::None);
 7628            });
 7629        })
 7630    }
 7631
 7632    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7633        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7634            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7635        })
 7636    }
 7637
 7638    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7639        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7640            let line_mode = s.line_mode;
 7641            s.move_with(|map, selection| {
 7642                let cursor = if selection.is_empty() && !line_mode {
 7643                    movement::right(map, selection.end)
 7644                } else {
 7645                    selection.end
 7646                };
 7647                selection.collapse_to(cursor, SelectionGoal::None)
 7648            });
 7649        })
 7650    }
 7651
 7652    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7653        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7654            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7655        })
 7656    }
 7657
 7658    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7659        if self.take_rename(true, cx).is_some() {
 7660            return;
 7661        }
 7662
 7663        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7664            cx.propagate();
 7665            return;
 7666        }
 7667
 7668        let text_layout_details = &self.text_layout_details(cx);
 7669        let selection_count = self.selections.count();
 7670        let first_selection = self.selections.first_anchor();
 7671
 7672        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7673            let line_mode = s.line_mode;
 7674            s.move_with(|map, selection| {
 7675                if !selection.is_empty() && !line_mode {
 7676                    selection.goal = SelectionGoal::None;
 7677                }
 7678                let (cursor, goal) = movement::up(
 7679                    map,
 7680                    selection.start,
 7681                    selection.goal,
 7682                    false,
 7683                    text_layout_details,
 7684                );
 7685                selection.collapse_to(cursor, goal);
 7686            });
 7687        });
 7688
 7689        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7690        {
 7691            cx.propagate();
 7692        }
 7693    }
 7694
 7695    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7696        if self.take_rename(true, cx).is_some() {
 7697            return;
 7698        }
 7699
 7700        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7701            cx.propagate();
 7702            return;
 7703        }
 7704
 7705        let text_layout_details = &self.text_layout_details(cx);
 7706
 7707        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7708            let line_mode = s.line_mode;
 7709            s.move_with(|map, selection| {
 7710                if !selection.is_empty() && !line_mode {
 7711                    selection.goal = SelectionGoal::None;
 7712                }
 7713                let (cursor, goal) = movement::up_by_rows(
 7714                    map,
 7715                    selection.start,
 7716                    action.lines,
 7717                    selection.goal,
 7718                    false,
 7719                    text_layout_details,
 7720                );
 7721                selection.collapse_to(cursor, goal);
 7722            });
 7723        })
 7724    }
 7725
 7726    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7727        if self.take_rename(true, cx).is_some() {
 7728            return;
 7729        }
 7730
 7731        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7732            cx.propagate();
 7733            return;
 7734        }
 7735
 7736        let text_layout_details = &self.text_layout_details(cx);
 7737
 7738        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7739            let line_mode = s.line_mode;
 7740            s.move_with(|map, selection| {
 7741                if !selection.is_empty() && !line_mode {
 7742                    selection.goal = SelectionGoal::None;
 7743                }
 7744                let (cursor, goal) = movement::down_by_rows(
 7745                    map,
 7746                    selection.start,
 7747                    action.lines,
 7748                    selection.goal,
 7749                    false,
 7750                    text_layout_details,
 7751                );
 7752                selection.collapse_to(cursor, goal);
 7753            });
 7754        })
 7755    }
 7756
 7757    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7758        let text_layout_details = &self.text_layout_details(cx);
 7759        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7760            s.move_heads_with(|map, head, goal| {
 7761                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7762            })
 7763        })
 7764    }
 7765
 7766    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7767        let text_layout_details = &self.text_layout_details(cx);
 7768        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7769            s.move_heads_with(|map, head, goal| {
 7770                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7771            })
 7772        })
 7773    }
 7774
 7775    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7776        let Some(row_count) = self.visible_row_count() else {
 7777            return;
 7778        };
 7779
 7780        let text_layout_details = &self.text_layout_details(cx);
 7781
 7782        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7783            s.move_heads_with(|map, head, goal| {
 7784                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7785            })
 7786        })
 7787    }
 7788
 7789    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7790        if self.take_rename(true, cx).is_some() {
 7791            return;
 7792        }
 7793
 7794        if self
 7795            .context_menu
 7796            .write()
 7797            .as_mut()
 7798            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7799            .unwrap_or(false)
 7800        {
 7801            return;
 7802        }
 7803
 7804        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7805            cx.propagate();
 7806            return;
 7807        }
 7808
 7809        let Some(row_count) = self.visible_row_count() else {
 7810            return;
 7811        };
 7812
 7813        let autoscroll = if action.center_cursor {
 7814            Autoscroll::center()
 7815        } else {
 7816            Autoscroll::fit()
 7817        };
 7818
 7819        let text_layout_details = &self.text_layout_details(cx);
 7820
 7821        self.change_selections(Some(autoscroll), cx, |s| {
 7822            let line_mode = s.line_mode;
 7823            s.move_with(|map, selection| {
 7824                if !selection.is_empty() && !line_mode {
 7825                    selection.goal = SelectionGoal::None;
 7826                }
 7827                let (cursor, goal) = movement::up_by_rows(
 7828                    map,
 7829                    selection.end,
 7830                    row_count,
 7831                    selection.goal,
 7832                    false,
 7833                    text_layout_details,
 7834                );
 7835                selection.collapse_to(cursor, goal);
 7836            });
 7837        });
 7838    }
 7839
 7840    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7841        let text_layout_details = &self.text_layout_details(cx);
 7842        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7843            s.move_heads_with(|map, head, goal| {
 7844                movement::up(map, head, goal, false, text_layout_details)
 7845            })
 7846        })
 7847    }
 7848
 7849    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7850        self.take_rename(true, cx);
 7851
 7852        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7853            cx.propagate();
 7854            return;
 7855        }
 7856
 7857        let text_layout_details = &self.text_layout_details(cx);
 7858        let selection_count = self.selections.count();
 7859        let first_selection = self.selections.first_anchor();
 7860
 7861        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7862            let line_mode = s.line_mode;
 7863            s.move_with(|map, selection| {
 7864                if !selection.is_empty() && !line_mode {
 7865                    selection.goal = SelectionGoal::None;
 7866                }
 7867                let (cursor, goal) = movement::down(
 7868                    map,
 7869                    selection.end,
 7870                    selection.goal,
 7871                    false,
 7872                    text_layout_details,
 7873                );
 7874                selection.collapse_to(cursor, goal);
 7875            });
 7876        });
 7877
 7878        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7879        {
 7880            cx.propagate();
 7881        }
 7882    }
 7883
 7884    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7885        let Some(row_count) = self.visible_row_count() else {
 7886            return;
 7887        };
 7888
 7889        let text_layout_details = &self.text_layout_details(cx);
 7890
 7891        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7892            s.move_heads_with(|map, head, goal| {
 7893                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7894            })
 7895        })
 7896    }
 7897
 7898    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7899        if self.take_rename(true, cx).is_some() {
 7900            return;
 7901        }
 7902
 7903        if self
 7904            .context_menu
 7905            .write()
 7906            .as_mut()
 7907            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7908            .unwrap_or(false)
 7909        {
 7910            return;
 7911        }
 7912
 7913        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7914            cx.propagate();
 7915            return;
 7916        }
 7917
 7918        let Some(row_count) = self.visible_row_count() else {
 7919            return;
 7920        };
 7921
 7922        let autoscroll = if action.center_cursor {
 7923            Autoscroll::center()
 7924        } else {
 7925            Autoscroll::fit()
 7926        };
 7927
 7928        let text_layout_details = &self.text_layout_details(cx);
 7929        self.change_selections(Some(autoscroll), cx, |s| {
 7930            let line_mode = s.line_mode;
 7931            s.move_with(|map, selection| {
 7932                if !selection.is_empty() && !line_mode {
 7933                    selection.goal = SelectionGoal::None;
 7934                }
 7935                let (cursor, goal) = movement::down_by_rows(
 7936                    map,
 7937                    selection.end,
 7938                    row_count,
 7939                    selection.goal,
 7940                    false,
 7941                    text_layout_details,
 7942                );
 7943                selection.collapse_to(cursor, goal);
 7944            });
 7945        });
 7946    }
 7947
 7948    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7949        let text_layout_details = &self.text_layout_details(cx);
 7950        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7951            s.move_heads_with(|map, head, goal| {
 7952                movement::down(map, head, goal, false, text_layout_details)
 7953            })
 7954        });
 7955    }
 7956
 7957    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7958        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7959            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7960        }
 7961    }
 7962
 7963    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7964        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7965            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7966        }
 7967    }
 7968
 7969    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7970        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7971            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7972        }
 7973    }
 7974
 7975    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7976        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7977            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7978        }
 7979    }
 7980
 7981    pub fn move_to_previous_word_start(
 7982        &mut self,
 7983        _: &MoveToPreviousWordStart,
 7984        cx: &mut ViewContext<Self>,
 7985    ) {
 7986        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7987            s.move_cursors_with(|map, head, _| {
 7988                (
 7989                    movement::previous_word_start(map, head),
 7990                    SelectionGoal::None,
 7991                )
 7992            });
 7993        })
 7994    }
 7995
 7996    pub fn move_to_previous_subword_start(
 7997        &mut self,
 7998        _: &MoveToPreviousSubwordStart,
 7999        cx: &mut ViewContext<Self>,
 8000    ) {
 8001        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8002            s.move_cursors_with(|map, head, _| {
 8003                (
 8004                    movement::previous_subword_start(map, head),
 8005                    SelectionGoal::None,
 8006                )
 8007            });
 8008        })
 8009    }
 8010
 8011    pub fn select_to_previous_word_start(
 8012        &mut self,
 8013        _: &SelectToPreviousWordStart,
 8014        cx: &mut ViewContext<Self>,
 8015    ) {
 8016        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8017            s.move_heads_with(|map, head, _| {
 8018                (
 8019                    movement::previous_word_start(map, head),
 8020                    SelectionGoal::None,
 8021                )
 8022            });
 8023        })
 8024    }
 8025
 8026    pub fn select_to_previous_subword_start(
 8027        &mut self,
 8028        _: &SelectToPreviousSubwordStart,
 8029        cx: &mut ViewContext<Self>,
 8030    ) {
 8031        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8032            s.move_heads_with(|map, head, _| {
 8033                (
 8034                    movement::previous_subword_start(map, head),
 8035                    SelectionGoal::None,
 8036                )
 8037            });
 8038        })
 8039    }
 8040
 8041    pub fn delete_to_previous_word_start(
 8042        &mut self,
 8043        action: &DeleteToPreviousWordStart,
 8044        cx: &mut ViewContext<Self>,
 8045    ) {
 8046        self.transact(cx, |this, cx| {
 8047            this.select_autoclose_pair(cx);
 8048            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8049                let line_mode = s.line_mode;
 8050                s.move_with(|map, selection| {
 8051                    if selection.is_empty() && !line_mode {
 8052                        let cursor = if action.ignore_newlines {
 8053                            movement::previous_word_start(map, selection.head())
 8054                        } else {
 8055                            movement::previous_word_start_or_newline(map, selection.head())
 8056                        };
 8057                        selection.set_head(cursor, SelectionGoal::None);
 8058                    }
 8059                });
 8060            });
 8061            this.insert("", cx);
 8062        });
 8063    }
 8064
 8065    pub fn delete_to_previous_subword_start(
 8066        &mut self,
 8067        _: &DeleteToPreviousSubwordStart,
 8068        cx: &mut ViewContext<Self>,
 8069    ) {
 8070        self.transact(cx, |this, cx| {
 8071            this.select_autoclose_pair(cx);
 8072            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8073                let line_mode = s.line_mode;
 8074                s.move_with(|map, selection| {
 8075                    if selection.is_empty() && !line_mode {
 8076                        let cursor = movement::previous_subword_start(map, selection.head());
 8077                        selection.set_head(cursor, SelectionGoal::None);
 8078                    }
 8079                });
 8080            });
 8081            this.insert("", cx);
 8082        });
 8083    }
 8084
 8085    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8086        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8087            s.move_cursors_with(|map, head, _| {
 8088                (movement::next_word_end(map, head), SelectionGoal::None)
 8089            });
 8090        })
 8091    }
 8092
 8093    pub fn move_to_next_subword_end(
 8094        &mut self,
 8095        _: &MoveToNextSubwordEnd,
 8096        cx: &mut ViewContext<Self>,
 8097    ) {
 8098        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8099            s.move_cursors_with(|map, head, _| {
 8100                (movement::next_subword_end(map, head), SelectionGoal::None)
 8101            });
 8102        })
 8103    }
 8104
 8105    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8106        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8107            s.move_heads_with(|map, head, _| {
 8108                (movement::next_word_end(map, head), SelectionGoal::None)
 8109            });
 8110        })
 8111    }
 8112
 8113    pub fn select_to_next_subword_end(
 8114        &mut self,
 8115        _: &SelectToNextSubwordEnd,
 8116        cx: &mut ViewContext<Self>,
 8117    ) {
 8118        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8119            s.move_heads_with(|map, head, _| {
 8120                (movement::next_subword_end(map, head), SelectionGoal::None)
 8121            });
 8122        })
 8123    }
 8124
 8125    pub fn delete_to_next_word_end(
 8126        &mut self,
 8127        action: &DeleteToNextWordEnd,
 8128        cx: &mut ViewContext<Self>,
 8129    ) {
 8130        self.transact(cx, |this, cx| {
 8131            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8132                let line_mode = s.line_mode;
 8133                s.move_with(|map, selection| {
 8134                    if selection.is_empty() && !line_mode {
 8135                        let cursor = if action.ignore_newlines {
 8136                            movement::next_word_end(map, selection.head())
 8137                        } else {
 8138                            movement::next_word_end_or_newline(map, selection.head())
 8139                        };
 8140                        selection.set_head(cursor, SelectionGoal::None);
 8141                    }
 8142                });
 8143            });
 8144            this.insert("", cx);
 8145        });
 8146    }
 8147
 8148    pub fn delete_to_next_subword_end(
 8149        &mut self,
 8150        _: &DeleteToNextSubwordEnd,
 8151        cx: &mut ViewContext<Self>,
 8152    ) {
 8153        self.transact(cx, |this, cx| {
 8154            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8155                s.move_with(|map, selection| {
 8156                    if selection.is_empty() {
 8157                        let cursor = movement::next_subword_end(map, selection.head());
 8158                        selection.set_head(cursor, SelectionGoal::None);
 8159                    }
 8160                });
 8161            });
 8162            this.insert("", cx);
 8163        });
 8164    }
 8165
 8166    pub fn move_to_beginning_of_line(
 8167        &mut self,
 8168        action: &MoveToBeginningOfLine,
 8169        cx: &mut ViewContext<Self>,
 8170    ) {
 8171        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8172            s.move_cursors_with(|map, head, _| {
 8173                (
 8174                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8175                    SelectionGoal::None,
 8176                )
 8177            });
 8178        })
 8179    }
 8180
 8181    pub fn select_to_beginning_of_line(
 8182        &mut self,
 8183        action: &SelectToBeginningOfLine,
 8184        cx: &mut ViewContext<Self>,
 8185    ) {
 8186        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8187            s.move_heads_with(|map, head, _| {
 8188                (
 8189                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8190                    SelectionGoal::None,
 8191                )
 8192            });
 8193        });
 8194    }
 8195
 8196    pub fn delete_to_beginning_of_line(
 8197        &mut self,
 8198        _: &DeleteToBeginningOfLine,
 8199        cx: &mut ViewContext<Self>,
 8200    ) {
 8201        self.transact(cx, |this, cx| {
 8202            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8203                s.move_with(|_, selection| {
 8204                    selection.reversed = true;
 8205                });
 8206            });
 8207
 8208            this.select_to_beginning_of_line(
 8209                &SelectToBeginningOfLine {
 8210                    stop_at_soft_wraps: false,
 8211                },
 8212                cx,
 8213            );
 8214            this.backspace(&Backspace, cx);
 8215        });
 8216    }
 8217
 8218    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8219        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8220            s.move_cursors_with(|map, head, _| {
 8221                (
 8222                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8223                    SelectionGoal::None,
 8224                )
 8225            });
 8226        })
 8227    }
 8228
 8229    pub fn select_to_end_of_line(
 8230        &mut self,
 8231        action: &SelectToEndOfLine,
 8232        cx: &mut ViewContext<Self>,
 8233    ) {
 8234        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8235            s.move_heads_with(|map, head, _| {
 8236                (
 8237                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8238                    SelectionGoal::None,
 8239                )
 8240            });
 8241        })
 8242    }
 8243
 8244    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8245        self.transact(cx, |this, cx| {
 8246            this.select_to_end_of_line(
 8247                &SelectToEndOfLine {
 8248                    stop_at_soft_wraps: false,
 8249                },
 8250                cx,
 8251            );
 8252            this.delete(&Delete, cx);
 8253        });
 8254    }
 8255
 8256    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8257        self.transact(cx, |this, cx| {
 8258            this.select_to_end_of_line(
 8259                &SelectToEndOfLine {
 8260                    stop_at_soft_wraps: false,
 8261                },
 8262                cx,
 8263            );
 8264            this.cut(&Cut, cx);
 8265        });
 8266    }
 8267
 8268    pub fn move_to_start_of_paragraph(
 8269        &mut self,
 8270        _: &MoveToStartOfParagraph,
 8271        cx: &mut ViewContext<Self>,
 8272    ) {
 8273        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8274            cx.propagate();
 8275            return;
 8276        }
 8277
 8278        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8279            s.move_with(|map, selection| {
 8280                selection.collapse_to(
 8281                    movement::start_of_paragraph(map, selection.head(), 1),
 8282                    SelectionGoal::None,
 8283                )
 8284            });
 8285        })
 8286    }
 8287
 8288    pub fn move_to_end_of_paragraph(
 8289        &mut self,
 8290        _: &MoveToEndOfParagraph,
 8291        cx: &mut ViewContext<Self>,
 8292    ) {
 8293        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8294            cx.propagate();
 8295            return;
 8296        }
 8297
 8298        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8299            s.move_with(|map, selection| {
 8300                selection.collapse_to(
 8301                    movement::end_of_paragraph(map, selection.head(), 1),
 8302                    SelectionGoal::None,
 8303                )
 8304            });
 8305        })
 8306    }
 8307
 8308    pub fn select_to_start_of_paragraph(
 8309        &mut self,
 8310        _: &SelectToStartOfParagraph,
 8311        cx: &mut ViewContext<Self>,
 8312    ) {
 8313        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8314            cx.propagate();
 8315            return;
 8316        }
 8317
 8318        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8319            s.move_heads_with(|map, head, _| {
 8320                (
 8321                    movement::start_of_paragraph(map, head, 1),
 8322                    SelectionGoal::None,
 8323                )
 8324            });
 8325        })
 8326    }
 8327
 8328    pub fn select_to_end_of_paragraph(
 8329        &mut self,
 8330        _: &SelectToEndOfParagraph,
 8331        cx: &mut ViewContext<Self>,
 8332    ) {
 8333        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8334            cx.propagate();
 8335            return;
 8336        }
 8337
 8338        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8339            s.move_heads_with(|map, head, _| {
 8340                (
 8341                    movement::end_of_paragraph(map, head, 1),
 8342                    SelectionGoal::None,
 8343                )
 8344            });
 8345        })
 8346    }
 8347
 8348    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8349        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8350            cx.propagate();
 8351            return;
 8352        }
 8353
 8354        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8355            s.select_ranges(vec![0..0]);
 8356        });
 8357    }
 8358
 8359    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8360        let mut selection = self.selections.last::<Point>(cx);
 8361        selection.set_head(Point::zero(), SelectionGoal::None);
 8362
 8363        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8364            s.select(vec![selection]);
 8365        });
 8366    }
 8367
 8368    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8369        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8370            cx.propagate();
 8371            return;
 8372        }
 8373
 8374        let cursor = self.buffer.read(cx).read(cx).len();
 8375        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8376            s.select_ranges(vec![cursor..cursor])
 8377        });
 8378    }
 8379
 8380    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8381        self.nav_history = nav_history;
 8382    }
 8383
 8384    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8385        self.nav_history.as_ref()
 8386    }
 8387
 8388    fn push_to_nav_history(
 8389        &mut self,
 8390        cursor_anchor: Anchor,
 8391        new_position: Option<Point>,
 8392        cx: &mut ViewContext<Self>,
 8393    ) {
 8394        if let Some(nav_history) = self.nav_history.as_mut() {
 8395            let buffer = self.buffer.read(cx).read(cx);
 8396            let cursor_position = cursor_anchor.to_point(&buffer);
 8397            let scroll_state = self.scroll_manager.anchor();
 8398            let scroll_top_row = scroll_state.top_row(&buffer);
 8399            drop(buffer);
 8400
 8401            if let Some(new_position) = new_position {
 8402                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8403                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8404                    return;
 8405                }
 8406            }
 8407
 8408            nav_history.push(
 8409                Some(NavigationData {
 8410                    cursor_anchor,
 8411                    cursor_position,
 8412                    scroll_anchor: scroll_state,
 8413                    scroll_top_row,
 8414                }),
 8415                cx,
 8416            );
 8417        }
 8418    }
 8419
 8420    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8421        let buffer = self.buffer.read(cx).snapshot(cx);
 8422        let mut selection = self.selections.first::<usize>(cx);
 8423        selection.set_head(buffer.len(), SelectionGoal::None);
 8424        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8425            s.select(vec![selection]);
 8426        });
 8427    }
 8428
 8429    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8430        let end = self.buffer.read(cx).read(cx).len();
 8431        self.change_selections(None, cx, |s| {
 8432            s.select_ranges(vec![0..end]);
 8433        });
 8434    }
 8435
 8436    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8437        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8438        let mut selections = self.selections.all::<Point>(cx);
 8439        let max_point = display_map.buffer_snapshot.max_point();
 8440        for selection in &mut selections {
 8441            let rows = selection.spanned_rows(true, &display_map);
 8442            selection.start = Point::new(rows.start.0, 0);
 8443            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8444            selection.reversed = false;
 8445        }
 8446        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8447            s.select(selections);
 8448        });
 8449    }
 8450
 8451    pub fn split_selection_into_lines(
 8452        &mut self,
 8453        _: &SplitSelectionIntoLines,
 8454        cx: &mut ViewContext<Self>,
 8455    ) {
 8456        let mut to_unfold = Vec::new();
 8457        let mut new_selection_ranges = Vec::new();
 8458        {
 8459            let selections = self.selections.all::<Point>(cx);
 8460            let buffer = self.buffer.read(cx).read(cx);
 8461            for selection in selections {
 8462                for row in selection.start.row..selection.end.row {
 8463                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8464                    new_selection_ranges.push(cursor..cursor);
 8465                }
 8466                new_selection_ranges.push(selection.end..selection.end);
 8467                to_unfold.push(selection.start..selection.end);
 8468            }
 8469        }
 8470        self.unfold_ranges(&to_unfold, true, true, cx);
 8471        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8472            s.select_ranges(new_selection_ranges);
 8473        });
 8474    }
 8475
 8476    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8477        self.add_selection(true, cx);
 8478    }
 8479
 8480    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8481        self.add_selection(false, cx);
 8482    }
 8483
 8484    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8485        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8486        let mut selections = self.selections.all::<Point>(cx);
 8487        let text_layout_details = self.text_layout_details(cx);
 8488        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8489            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8490            let range = oldest_selection.display_range(&display_map).sorted();
 8491
 8492            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8493            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8494            let positions = start_x.min(end_x)..start_x.max(end_x);
 8495
 8496            selections.clear();
 8497            let mut stack = Vec::new();
 8498            for row in range.start.row().0..=range.end.row().0 {
 8499                if let Some(selection) = self.selections.build_columnar_selection(
 8500                    &display_map,
 8501                    DisplayRow(row),
 8502                    &positions,
 8503                    oldest_selection.reversed,
 8504                    &text_layout_details,
 8505                ) {
 8506                    stack.push(selection.id);
 8507                    selections.push(selection);
 8508                }
 8509            }
 8510
 8511            if above {
 8512                stack.reverse();
 8513            }
 8514
 8515            AddSelectionsState { above, stack }
 8516        });
 8517
 8518        let last_added_selection = *state.stack.last().unwrap();
 8519        let mut new_selections = Vec::new();
 8520        if above == state.above {
 8521            let end_row = if above {
 8522                DisplayRow(0)
 8523            } else {
 8524                display_map.max_point().row()
 8525            };
 8526
 8527            'outer: for selection in selections {
 8528                if selection.id == last_added_selection {
 8529                    let range = selection.display_range(&display_map).sorted();
 8530                    debug_assert_eq!(range.start.row(), range.end.row());
 8531                    let mut row = range.start.row();
 8532                    let positions =
 8533                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8534                            px(start)..px(end)
 8535                        } else {
 8536                            let start_x =
 8537                                display_map.x_for_display_point(range.start, &text_layout_details);
 8538                            let end_x =
 8539                                display_map.x_for_display_point(range.end, &text_layout_details);
 8540                            start_x.min(end_x)..start_x.max(end_x)
 8541                        };
 8542
 8543                    while row != end_row {
 8544                        if above {
 8545                            row.0 -= 1;
 8546                        } else {
 8547                            row.0 += 1;
 8548                        }
 8549
 8550                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8551                            &display_map,
 8552                            row,
 8553                            &positions,
 8554                            selection.reversed,
 8555                            &text_layout_details,
 8556                        ) {
 8557                            state.stack.push(new_selection.id);
 8558                            if above {
 8559                                new_selections.push(new_selection);
 8560                                new_selections.push(selection);
 8561                            } else {
 8562                                new_selections.push(selection);
 8563                                new_selections.push(new_selection);
 8564                            }
 8565
 8566                            continue 'outer;
 8567                        }
 8568                    }
 8569                }
 8570
 8571                new_selections.push(selection);
 8572            }
 8573        } else {
 8574            new_selections = selections;
 8575            new_selections.retain(|s| s.id != last_added_selection);
 8576            state.stack.pop();
 8577        }
 8578
 8579        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8580            s.select(new_selections);
 8581        });
 8582        if state.stack.len() > 1 {
 8583            self.add_selections_state = Some(state);
 8584        }
 8585    }
 8586
 8587    pub fn select_next_match_internal(
 8588        &mut self,
 8589        display_map: &DisplaySnapshot,
 8590        replace_newest: bool,
 8591        autoscroll: Option<Autoscroll>,
 8592        cx: &mut ViewContext<Self>,
 8593    ) -> Result<()> {
 8594        fn select_next_match_ranges(
 8595            this: &mut Editor,
 8596            range: Range<usize>,
 8597            replace_newest: bool,
 8598            auto_scroll: Option<Autoscroll>,
 8599            cx: &mut ViewContext<Editor>,
 8600        ) {
 8601            this.unfold_ranges(&[range.clone()], false, true, cx);
 8602            this.change_selections(auto_scroll, cx, |s| {
 8603                if replace_newest {
 8604                    s.delete(s.newest_anchor().id);
 8605                }
 8606                s.insert_range(range.clone());
 8607            });
 8608        }
 8609
 8610        let buffer = &display_map.buffer_snapshot;
 8611        let mut selections = self.selections.all::<usize>(cx);
 8612        if let Some(mut select_next_state) = self.select_next_state.take() {
 8613            let query = &select_next_state.query;
 8614            if !select_next_state.done {
 8615                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8616                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8617                let mut next_selected_range = None;
 8618
 8619                let bytes_after_last_selection =
 8620                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8621                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8622                let query_matches = query
 8623                    .stream_find_iter(bytes_after_last_selection)
 8624                    .map(|result| (last_selection.end, result))
 8625                    .chain(
 8626                        query
 8627                            .stream_find_iter(bytes_before_first_selection)
 8628                            .map(|result| (0, result)),
 8629                    );
 8630
 8631                for (start_offset, query_match) in query_matches {
 8632                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8633                    let offset_range =
 8634                        start_offset + query_match.start()..start_offset + query_match.end();
 8635                    let display_range = offset_range.start.to_display_point(display_map)
 8636                        ..offset_range.end.to_display_point(display_map);
 8637
 8638                    if !select_next_state.wordwise
 8639                        || (!movement::is_inside_word(display_map, display_range.start)
 8640                            && !movement::is_inside_word(display_map, display_range.end))
 8641                    {
 8642                        // TODO: This is n^2, because we might check all the selections
 8643                        if !selections
 8644                            .iter()
 8645                            .any(|selection| selection.range().overlaps(&offset_range))
 8646                        {
 8647                            next_selected_range = Some(offset_range);
 8648                            break;
 8649                        }
 8650                    }
 8651                }
 8652
 8653                if let Some(next_selected_range) = next_selected_range {
 8654                    select_next_match_ranges(
 8655                        self,
 8656                        next_selected_range,
 8657                        replace_newest,
 8658                        autoscroll,
 8659                        cx,
 8660                    );
 8661                } else {
 8662                    select_next_state.done = true;
 8663                }
 8664            }
 8665
 8666            self.select_next_state = Some(select_next_state);
 8667        } else {
 8668            let mut only_carets = true;
 8669            let mut same_text_selected = true;
 8670            let mut selected_text = None;
 8671
 8672            let mut selections_iter = selections.iter().peekable();
 8673            while let Some(selection) = selections_iter.next() {
 8674                if selection.start != selection.end {
 8675                    only_carets = false;
 8676                }
 8677
 8678                if same_text_selected {
 8679                    if selected_text.is_none() {
 8680                        selected_text =
 8681                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8682                    }
 8683
 8684                    if let Some(next_selection) = selections_iter.peek() {
 8685                        if next_selection.range().len() == selection.range().len() {
 8686                            let next_selected_text = buffer
 8687                                .text_for_range(next_selection.range())
 8688                                .collect::<String>();
 8689                            if Some(next_selected_text) != selected_text {
 8690                                same_text_selected = false;
 8691                                selected_text = None;
 8692                            }
 8693                        } else {
 8694                            same_text_selected = false;
 8695                            selected_text = None;
 8696                        }
 8697                    }
 8698                }
 8699            }
 8700
 8701            if only_carets {
 8702                for selection in &mut selections {
 8703                    let word_range = movement::surrounding_word(
 8704                        display_map,
 8705                        selection.start.to_display_point(display_map),
 8706                    );
 8707                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8708                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8709                    selection.goal = SelectionGoal::None;
 8710                    selection.reversed = false;
 8711                    select_next_match_ranges(
 8712                        self,
 8713                        selection.start..selection.end,
 8714                        replace_newest,
 8715                        autoscroll,
 8716                        cx,
 8717                    );
 8718                }
 8719
 8720                if selections.len() == 1 {
 8721                    let selection = selections
 8722                        .last()
 8723                        .expect("ensured that there's only one selection");
 8724                    let query = buffer
 8725                        .text_for_range(selection.start..selection.end)
 8726                        .collect::<String>();
 8727                    let is_empty = query.is_empty();
 8728                    let select_state = SelectNextState {
 8729                        query: AhoCorasick::new(&[query])?,
 8730                        wordwise: true,
 8731                        done: is_empty,
 8732                    };
 8733                    self.select_next_state = Some(select_state);
 8734                } else {
 8735                    self.select_next_state = None;
 8736                }
 8737            } else if let Some(selected_text) = selected_text {
 8738                self.select_next_state = Some(SelectNextState {
 8739                    query: AhoCorasick::new(&[selected_text])?,
 8740                    wordwise: false,
 8741                    done: false,
 8742                });
 8743                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8744            }
 8745        }
 8746        Ok(())
 8747    }
 8748
 8749    pub fn select_all_matches(
 8750        &mut self,
 8751        _action: &SelectAllMatches,
 8752        cx: &mut ViewContext<Self>,
 8753    ) -> Result<()> {
 8754        self.push_to_selection_history();
 8755        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8756
 8757        self.select_next_match_internal(&display_map, false, None, cx)?;
 8758        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8759            return Ok(());
 8760        };
 8761        if select_next_state.done {
 8762            return Ok(());
 8763        }
 8764
 8765        let mut new_selections = self.selections.all::<usize>(cx);
 8766
 8767        let buffer = &display_map.buffer_snapshot;
 8768        let query_matches = select_next_state
 8769            .query
 8770            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8771
 8772        for query_match in query_matches {
 8773            let query_match = query_match.unwrap(); // can only fail due to I/O
 8774            let offset_range = query_match.start()..query_match.end();
 8775            let display_range = offset_range.start.to_display_point(&display_map)
 8776                ..offset_range.end.to_display_point(&display_map);
 8777
 8778            if !select_next_state.wordwise
 8779                || (!movement::is_inside_word(&display_map, display_range.start)
 8780                    && !movement::is_inside_word(&display_map, display_range.end))
 8781            {
 8782                self.selections.change_with(cx, |selections| {
 8783                    new_selections.push(Selection {
 8784                        id: selections.new_selection_id(),
 8785                        start: offset_range.start,
 8786                        end: offset_range.end,
 8787                        reversed: false,
 8788                        goal: SelectionGoal::None,
 8789                    });
 8790                });
 8791            }
 8792        }
 8793
 8794        new_selections.sort_by_key(|selection| selection.start);
 8795        let mut ix = 0;
 8796        while ix + 1 < new_selections.len() {
 8797            let current_selection = &new_selections[ix];
 8798            let next_selection = &new_selections[ix + 1];
 8799            if current_selection.range().overlaps(&next_selection.range()) {
 8800                if current_selection.id < next_selection.id {
 8801                    new_selections.remove(ix + 1);
 8802                } else {
 8803                    new_selections.remove(ix);
 8804                }
 8805            } else {
 8806                ix += 1;
 8807            }
 8808        }
 8809
 8810        select_next_state.done = true;
 8811        self.unfold_ranges(
 8812            &new_selections
 8813                .iter()
 8814                .map(|selection| selection.range())
 8815                .collect::<Vec<_>>(),
 8816            false,
 8817            false,
 8818            cx,
 8819        );
 8820        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8821            selections.select(new_selections)
 8822        });
 8823
 8824        Ok(())
 8825    }
 8826
 8827    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8828        self.push_to_selection_history();
 8829        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8830        self.select_next_match_internal(
 8831            &display_map,
 8832            action.replace_newest,
 8833            Some(Autoscroll::newest()),
 8834            cx,
 8835        )?;
 8836        Ok(())
 8837    }
 8838
 8839    pub fn select_previous(
 8840        &mut self,
 8841        action: &SelectPrevious,
 8842        cx: &mut ViewContext<Self>,
 8843    ) -> Result<()> {
 8844        self.push_to_selection_history();
 8845        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8846        let buffer = &display_map.buffer_snapshot;
 8847        let mut selections = self.selections.all::<usize>(cx);
 8848        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8849            let query = &select_prev_state.query;
 8850            if !select_prev_state.done {
 8851                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8852                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8853                let mut next_selected_range = None;
 8854                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8855                let bytes_before_last_selection =
 8856                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8857                let bytes_after_first_selection =
 8858                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8859                let query_matches = query
 8860                    .stream_find_iter(bytes_before_last_selection)
 8861                    .map(|result| (last_selection.start, result))
 8862                    .chain(
 8863                        query
 8864                            .stream_find_iter(bytes_after_first_selection)
 8865                            .map(|result| (buffer.len(), result)),
 8866                    );
 8867                for (end_offset, query_match) in query_matches {
 8868                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8869                    let offset_range =
 8870                        end_offset - query_match.end()..end_offset - query_match.start();
 8871                    let display_range = offset_range.start.to_display_point(&display_map)
 8872                        ..offset_range.end.to_display_point(&display_map);
 8873
 8874                    if !select_prev_state.wordwise
 8875                        || (!movement::is_inside_word(&display_map, display_range.start)
 8876                            && !movement::is_inside_word(&display_map, display_range.end))
 8877                    {
 8878                        next_selected_range = Some(offset_range);
 8879                        break;
 8880                    }
 8881                }
 8882
 8883                if let Some(next_selected_range) = next_selected_range {
 8884                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8885                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8886                        if action.replace_newest {
 8887                            s.delete(s.newest_anchor().id);
 8888                        }
 8889                        s.insert_range(next_selected_range);
 8890                    });
 8891                } else {
 8892                    select_prev_state.done = true;
 8893                }
 8894            }
 8895
 8896            self.select_prev_state = Some(select_prev_state);
 8897        } else {
 8898            let mut only_carets = true;
 8899            let mut same_text_selected = true;
 8900            let mut selected_text = None;
 8901
 8902            let mut selections_iter = selections.iter().peekable();
 8903            while let Some(selection) = selections_iter.next() {
 8904                if selection.start != selection.end {
 8905                    only_carets = false;
 8906                }
 8907
 8908                if same_text_selected {
 8909                    if selected_text.is_none() {
 8910                        selected_text =
 8911                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8912                    }
 8913
 8914                    if let Some(next_selection) = selections_iter.peek() {
 8915                        if next_selection.range().len() == selection.range().len() {
 8916                            let next_selected_text = buffer
 8917                                .text_for_range(next_selection.range())
 8918                                .collect::<String>();
 8919                            if Some(next_selected_text) != selected_text {
 8920                                same_text_selected = false;
 8921                                selected_text = None;
 8922                            }
 8923                        } else {
 8924                            same_text_selected = false;
 8925                            selected_text = None;
 8926                        }
 8927                    }
 8928                }
 8929            }
 8930
 8931            if only_carets {
 8932                for selection in &mut selections {
 8933                    let word_range = movement::surrounding_word(
 8934                        &display_map,
 8935                        selection.start.to_display_point(&display_map),
 8936                    );
 8937                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8938                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8939                    selection.goal = SelectionGoal::None;
 8940                    selection.reversed = false;
 8941                }
 8942                if selections.len() == 1 {
 8943                    let selection = selections
 8944                        .last()
 8945                        .expect("ensured that there's only one selection");
 8946                    let query = buffer
 8947                        .text_for_range(selection.start..selection.end)
 8948                        .collect::<String>();
 8949                    let is_empty = query.is_empty();
 8950                    let select_state = SelectNextState {
 8951                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8952                        wordwise: true,
 8953                        done: is_empty,
 8954                    };
 8955                    self.select_prev_state = Some(select_state);
 8956                } else {
 8957                    self.select_prev_state = None;
 8958                }
 8959
 8960                self.unfold_ranges(
 8961                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8962                    false,
 8963                    true,
 8964                    cx,
 8965                );
 8966                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8967                    s.select(selections);
 8968                });
 8969            } else if let Some(selected_text) = selected_text {
 8970                self.select_prev_state = Some(SelectNextState {
 8971                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8972                    wordwise: false,
 8973                    done: false,
 8974                });
 8975                self.select_previous(action, cx)?;
 8976            }
 8977        }
 8978        Ok(())
 8979    }
 8980
 8981    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8982        if self.read_only(cx) {
 8983            return;
 8984        }
 8985        let text_layout_details = &self.text_layout_details(cx);
 8986        self.transact(cx, |this, cx| {
 8987            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8988            let mut edits = Vec::new();
 8989            let mut selection_edit_ranges = Vec::new();
 8990            let mut last_toggled_row = None;
 8991            let snapshot = this.buffer.read(cx).read(cx);
 8992            let empty_str: Arc<str> = Arc::default();
 8993            let mut suffixes_inserted = Vec::new();
 8994            let ignore_indent = action.ignore_indent;
 8995
 8996            fn comment_prefix_range(
 8997                snapshot: &MultiBufferSnapshot,
 8998                row: MultiBufferRow,
 8999                comment_prefix: &str,
 9000                comment_prefix_whitespace: &str,
 9001                ignore_indent: bool,
 9002            ) -> Range<Point> {
 9003                let indent_size = if ignore_indent {
 9004                    0
 9005                } else {
 9006                    snapshot.indent_size_for_line(row).len
 9007                };
 9008
 9009                let start = Point::new(row.0, indent_size);
 9010
 9011                let mut line_bytes = snapshot
 9012                    .bytes_in_range(start..snapshot.max_point())
 9013                    .flatten()
 9014                    .copied();
 9015
 9016                // If this line currently begins with the line comment prefix, then record
 9017                // the range containing the prefix.
 9018                if line_bytes
 9019                    .by_ref()
 9020                    .take(comment_prefix.len())
 9021                    .eq(comment_prefix.bytes())
 9022                {
 9023                    // Include any whitespace that matches the comment prefix.
 9024                    let matching_whitespace_len = line_bytes
 9025                        .zip(comment_prefix_whitespace.bytes())
 9026                        .take_while(|(a, b)| a == b)
 9027                        .count() as u32;
 9028                    let end = Point::new(
 9029                        start.row,
 9030                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9031                    );
 9032                    start..end
 9033                } else {
 9034                    start..start
 9035                }
 9036            }
 9037
 9038            fn comment_suffix_range(
 9039                snapshot: &MultiBufferSnapshot,
 9040                row: MultiBufferRow,
 9041                comment_suffix: &str,
 9042                comment_suffix_has_leading_space: bool,
 9043            ) -> Range<Point> {
 9044                let end = Point::new(row.0, snapshot.line_len(row));
 9045                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9046
 9047                let mut line_end_bytes = snapshot
 9048                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9049                    .flatten()
 9050                    .copied();
 9051
 9052                let leading_space_len = if suffix_start_column > 0
 9053                    && line_end_bytes.next() == Some(b' ')
 9054                    && comment_suffix_has_leading_space
 9055                {
 9056                    1
 9057                } else {
 9058                    0
 9059                };
 9060
 9061                // If this line currently begins with the line comment prefix, then record
 9062                // the range containing the prefix.
 9063                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9064                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9065                    start..end
 9066                } else {
 9067                    end..end
 9068                }
 9069            }
 9070
 9071            // TODO: Handle selections that cross excerpts
 9072            for selection in &mut selections {
 9073                let start_column = snapshot
 9074                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9075                    .len;
 9076                let language = if let Some(language) =
 9077                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9078                {
 9079                    language
 9080                } else {
 9081                    continue;
 9082                };
 9083
 9084                selection_edit_ranges.clear();
 9085
 9086                // If multiple selections contain a given row, avoid processing that
 9087                // row more than once.
 9088                let mut start_row = MultiBufferRow(selection.start.row);
 9089                if last_toggled_row == Some(start_row) {
 9090                    start_row = start_row.next_row();
 9091                }
 9092                let end_row =
 9093                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9094                        MultiBufferRow(selection.end.row - 1)
 9095                    } else {
 9096                        MultiBufferRow(selection.end.row)
 9097                    };
 9098                last_toggled_row = Some(end_row);
 9099
 9100                if start_row > end_row {
 9101                    continue;
 9102                }
 9103
 9104                // If the language has line comments, toggle those.
 9105                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9106
 9107                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9108                if ignore_indent {
 9109                    full_comment_prefixes = full_comment_prefixes
 9110                        .into_iter()
 9111                        .map(|s| Arc::from(s.trim_end()))
 9112                        .collect();
 9113                }
 9114
 9115                if !full_comment_prefixes.is_empty() {
 9116                    let first_prefix = full_comment_prefixes
 9117                        .first()
 9118                        .expect("prefixes is non-empty");
 9119                    let prefix_trimmed_lengths = full_comment_prefixes
 9120                        .iter()
 9121                        .map(|p| p.trim_end_matches(' ').len())
 9122                        .collect::<SmallVec<[usize; 4]>>();
 9123
 9124                    let mut all_selection_lines_are_comments = true;
 9125
 9126                    for row in start_row.0..=end_row.0 {
 9127                        let row = MultiBufferRow(row);
 9128                        if start_row < end_row && snapshot.is_line_blank(row) {
 9129                            continue;
 9130                        }
 9131
 9132                        let prefix_range = full_comment_prefixes
 9133                            .iter()
 9134                            .zip(prefix_trimmed_lengths.iter().copied())
 9135                            .map(|(prefix, trimmed_prefix_len)| {
 9136                                comment_prefix_range(
 9137                                    snapshot.deref(),
 9138                                    row,
 9139                                    &prefix[..trimmed_prefix_len],
 9140                                    &prefix[trimmed_prefix_len..],
 9141                                    ignore_indent,
 9142                                )
 9143                            })
 9144                            .max_by_key(|range| range.end.column - range.start.column)
 9145                            .expect("prefixes is non-empty");
 9146
 9147                        if prefix_range.is_empty() {
 9148                            all_selection_lines_are_comments = false;
 9149                        }
 9150
 9151                        selection_edit_ranges.push(prefix_range);
 9152                    }
 9153
 9154                    if all_selection_lines_are_comments {
 9155                        edits.extend(
 9156                            selection_edit_ranges
 9157                                .iter()
 9158                                .cloned()
 9159                                .map(|range| (range, empty_str.clone())),
 9160                        );
 9161                    } else {
 9162                        let min_column = selection_edit_ranges
 9163                            .iter()
 9164                            .map(|range| range.start.column)
 9165                            .min()
 9166                            .unwrap_or(0);
 9167                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9168                            let position = Point::new(range.start.row, min_column);
 9169                            (position..position, first_prefix.clone())
 9170                        }));
 9171                    }
 9172                } else if let Some((full_comment_prefix, comment_suffix)) =
 9173                    language.block_comment_delimiters()
 9174                {
 9175                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9176                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9177                    let prefix_range = comment_prefix_range(
 9178                        snapshot.deref(),
 9179                        start_row,
 9180                        comment_prefix,
 9181                        comment_prefix_whitespace,
 9182                        ignore_indent,
 9183                    );
 9184                    let suffix_range = comment_suffix_range(
 9185                        snapshot.deref(),
 9186                        end_row,
 9187                        comment_suffix.trim_start_matches(' '),
 9188                        comment_suffix.starts_with(' '),
 9189                    );
 9190
 9191                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9192                        edits.push((
 9193                            prefix_range.start..prefix_range.start,
 9194                            full_comment_prefix.clone(),
 9195                        ));
 9196                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9197                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9198                    } else {
 9199                        edits.push((prefix_range, empty_str.clone()));
 9200                        edits.push((suffix_range, empty_str.clone()));
 9201                    }
 9202                } else {
 9203                    continue;
 9204                }
 9205            }
 9206
 9207            drop(snapshot);
 9208            this.buffer.update(cx, |buffer, cx| {
 9209                buffer.edit(edits, None, cx);
 9210            });
 9211
 9212            // Adjust selections so that they end before any comment suffixes that
 9213            // were inserted.
 9214            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9215            let mut selections = this.selections.all::<Point>(cx);
 9216            let snapshot = this.buffer.read(cx).read(cx);
 9217            for selection in &mut selections {
 9218                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9219                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9220                        Ordering::Less => {
 9221                            suffixes_inserted.next();
 9222                            continue;
 9223                        }
 9224                        Ordering::Greater => break,
 9225                        Ordering::Equal => {
 9226                            if selection.end.column == snapshot.line_len(row) {
 9227                                if selection.is_empty() {
 9228                                    selection.start.column -= suffix_len as u32;
 9229                                }
 9230                                selection.end.column -= suffix_len as u32;
 9231                            }
 9232                            break;
 9233                        }
 9234                    }
 9235                }
 9236            }
 9237
 9238            drop(snapshot);
 9239            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9240
 9241            let selections = this.selections.all::<Point>(cx);
 9242            let selections_on_single_row = selections.windows(2).all(|selections| {
 9243                selections[0].start.row == selections[1].start.row
 9244                    && selections[0].end.row == selections[1].end.row
 9245                    && selections[0].start.row == selections[0].end.row
 9246            });
 9247            let selections_selecting = selections
 9248                .iter()
 9249                .any(|selection| selection.start != selection.end);
 9250            let advance_downwards = action.advance_downwards
 9251                && selections_on_single_row
 9252                && !selections_selecting
 9253                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9254
 9255            if advance_downwards {
 9256                let snapshot = this.buffer.read(cx).snapshot(cx);
 9257
 9258                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9259                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9260                        let mut point = display_point.to_point(display_snapshot);
 9261                        point.row += 1;
 9262                        point = snapshot.clip_point(point, Bias::Left);
 9263                        let display_point = point.to_display_point(display_snapshot);
 9264                        let goal = SelectionGoal::HorizontalPosition(
 9265                            display_snapshot
 9266                                .x_for_display_point(display_point, text_layout_details)
 9267                                .into(),
 9268                        );
 9269                        (display_point, goal)
 9270                    })
 9271                });
 9272            }
 9273        });
 9274    }
 9275
 9276    pub fn select_enclosing_symbol(
 9277        &mut self,
 9278        _: &SelectEnclosingSymbol,
 9279        cx: &mut ViewContext<Self>,
 9280    ) {
 9281        let buffer = self.buffer.read(cx).snapshot(cx);
 9282        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9283
 9284        fn update_selection(
 9285            selection: &Selection<usize>,
 9286            buffer_snap: &MultiBufferSnapshot,
 9287        ) -> Option<Selection<usize>> {
 9288            let cursor = selection.head();
 9289            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9290            for symbol in symbols.iter().rev() {
 9291                let start = symbol.range.start.to_offset(buffer_snap);
 9292                let end = symbol.range.end.to_offset(buffer_snap);
 9293                let new_range = start..end;
 9294                if start < selection.start || end > selection.end {
 9295                    return Some(Selection {
 9296                        id: selection.id,
 9297                        start: new_range.start,
 9298                        end: new_range.end,
 9299                        goal: SelectionGoal::None,
 9300                        reversed: selection.reversed,
 9301                    });
 9302                }
 9303            }
 9304            None
 9305        }
 9306
 9307        let mut selected_larger_symbol = false;
 9308        let new_selections = old_selections
 9309            .iter()
 9310            .map(|selection| match update_selection(selection, &buffer) {
 9311                Some(new_selection) => {
 9312                    if new_selection.range() != selection.range() {
 9313                        selected_larger_symbol = true;
 9314                    }
 9315                    new_selection
 9316                }
 9317                None => selection.clone(),
 9318            })
 9319            .collect::<Vec<_>>();
 9320
 9321        if selected_larger_symbol {
 9322            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9323                s.select(new_selections);
 9324            });
 9325        }
 9326    }
 9327
 9328    pub fn select_larger_syntax_node(
 9329        &mut self,
 9330        _: &SelectLargerSyntaxNode,
 9331        cx: &mut ViewContext<Self>,
 9332    ) {
 9333        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9334        let buffer = self.buffer.read(cx).snapshot(cx);
 9335        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9336
 9337        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9338        let mut selected_larger_node = false;
 9339        let new_selections = old_selections
 9340            .iter()
 9341            .map(|selection| {
 9342                let old_range = selection.start..selection.end;
 9343                let mut new_range = old_range.clone();
 9344                while let Some(containing_range) =
 9345                    buffer.range_for_syntax_ancestor(new_range.clone())
 9346                {
 9347                    new_range = containing_range;
 9348                    if !display_map.intersects_fold(new_range.start)
 9349                        && !display_map.intersects_fold(new_range.end)
 9350                    {
 9351                        break;
 9352                    }
 9353                }
 9354
 9355                selected_larger_node |= new_range != old_range;
 9356                Selection {
 9357                    id: selection.id,
 9358                    start: new_range.start,
 9359                    end: new_range.end,
 9360                    goal: SelectionGoal::None,
 9361                    reversed: selection.reversed,
 9362                }
 9363            })
 9364            .collect::<Vec<_>>();
 9365
 9366        if selected_larger_node {
 9367            stack.push(old_selections);
 9368            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9369                s.select(new_selections);
 9370            });
 9371        }
 9372        self.select_larger_syntax_node_stack = stack;
 9373    }
 9374
 9375    pub fn select_smaller_syntax_node(
 9376        &mut self,
 9377        _: &SelectSmallerSyntaxNode,
 9378        cx: &mut ViewContext<Self>,
 9379    ) {
 9380        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9381        if let Some(selections) = stack.pop() {
 9382            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9383                s.select(selections.to_vec());
 9384            });
 9385        }
 9386        self.select_larger_syntax_node_stack = stack;
 9387    }
 9388
 9389    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9390        if !EditorSettings::get_global(cx).gutter.runnables {
 9391            self.clear_tasks();
 9392            return Task::ready(());
 9393        }
 9394        let project = self.project.as_ref().map(Model::downgrade);
 9395        cx.spawn(|this, mut cx| async move {
 9396            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9397            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9398                return;
 9399            };
 9400            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9401                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9402            }) else {
 9403                return;
 9404            };
 9405
 9406            let hide_runnables = project
 9407                .update(&mut cx, |project, cx| {
 9408                    // Do not display any test indicators in non-dev server remote projects.
 9409                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9410                })
 9411                .unwrap_or(true);
 9412            if hide_runnables {
 9413                return;
 9414            }
 9415            let new_rows =
 9416                cx.background_executor()
 9417                    .spawn({
 9418                        let snapshot = display_snapshot.clone();
 9419                        async move {
 9420                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9421                        }
 9422                    })
 9423                    .await;
 9424            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9425
 9426            this.update(&mut cx, |this, _| {
 9427                this.clear_tasks();
 9428                for (key, value) in rows {
 9429                    this.insert_tasks(key, value);
 9430                }
 9431            })
 9432            .ok();
 9433        })
 9434    }
 9435    fn fetch_runnable_ranges(
 9436        snapshot: &DisplaySnapshot,
 9437        range: Range<Anchor>,
 9438    ) -> Vec<language::RunnableRange> {
 9439        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9440    }
 9441
 9442    fn runnable_rows(
 9443        project: Model<Project>,
 9444        snapshot: DisplaySnapshot,
 9445        runnable_ranges: Vec<RunnableRange>,
 9446        mut cx: AsyncWindowContext,
 9447    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9448        runnable_ranges
 9449            .into_iter()
 9450            .filter_map(|mut runnable| {
 9451                let tasks = cx
 9452                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9453                    .ok()?;
 9454                if tasks.is_empty() {
 9455                    return None;
 9456                }
 9457
 9458                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9459
 9460                let row = snapshot
 9461                    .buffer_snapshot
 9462                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9463                    .1
 9464                    .start
 9465                    .row;
 9466
 9467                let context_range =
 9468                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9469                Some((
 9470                    (runnable.buffer_id, row),
 9471                    RunnableTasks {
 9472                        templates: tasks,
 9473                        offset: MultiBufferOffset(runnable.run_range.start),
 9474                        context_range,
 9475                        column: point.column,
 9476                        extra_variables: runnable.extra_captures,
 9477                    },
 9478                ))
 9479            })
 9480            .collect()
 9481    }
 9482
 9483    fn templates_with_tags(
 9484        project: &Model<Project>,
 9485        runnable: &mut Runnable,
 9486        cx: &WindowContext<'_>,
 9487    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9488        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9489            let (worktree_id, file) = project
 9490                .buffer_for_id(runnable.buffer, cx)
 9491                .and_then(|buffer| buffer.read(cx).file())
 9492                .map(|file| (file.worktree_id(cx), file.clone()))
 9493                .unzip();
 9494
 9495            (
 9496                project.task_store().read(cx).task_inventory().cloned(),
 9497                worktree_id,
 9498                file,
 9499            )
 9500        });
 9501
 9502        let tags = mem::take(&mut runnable.tags);
 9503        let mut tags: Vec<_> = tags
 9504            .into_iter()
 9505            .flat_map(|tag| {
 9506                let tag = tag.0.clone();
 9507                inventory
 9508                    .as_ref()
 9509                    .into_iter()
 9510                    .flat_map(|inventory| {
 9511                        inventory.read(cx).list_tasks(
 9512                            file.clone(),
 9513                            Some(runnable.language.clone()),
 9514                            worktree_id,
 9515                            cx,
 9516                        )
 9517                    })
 9518                    .filter(move |(_, template)| {
 9519                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9520                    })
 9521            })
 9522            .sorted_by_key(|(kind, _)| kind.to_owned())
 9523            .collect();
 9524        if let Some((leading_tag_source, _)) = tags.first() {
 9525            // Strongest source wins; if we have worktree tag binding, prefer that to
 9526            // global and language bindings;
 9527            // if we have a global binding, prefer that to language binding.
 9528            let first_mismatch = tags
 9529                .iter()
 9530                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9531            if let Some(index) = first_mismatch {
 9532                tags.truncate(index);
 9533            }
 9534        }
 9535
 9536        tags
 9537    }
 9538
 9539    pub fn move_to_enclosing_bracket(
 9540        &mut self,
 9541        _: &MoveToEnclosingBracket,
 9542        cx: &mut ViewContext<Self>,
 9543    ) {
 9544        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9545            s.move_offsets_with(|snapshot, selection| {
 9546                let Some(enclosing_bracket_ranges) =
 9547                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9548                else {
 9549                    return;
 9550                };
 9551
 9552                let mut best_length = usize::MAX;
 9553                let mut best_inside = false;
 9554                let mut best_in_bracket_range = false;
 9555                let mut best_destination = None;
 9556                for (open, close) in enclosing_bracket_ranges {
 9557                    let close = close.to_inclusive();
 9558                    let length = close.end() - open.start;
 9559                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9560                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9561                        || close.contains(&selection.head());
 9562
 9563                    // If best is next to a bracket and current isn't, skip
 9564                    if !in_bracket_range && best_in_bracket_range {
 9565                        continue;
 9566                    }
 9567
 9568                    // Prefer smaller lengths unless best is inside and current isn't
 9569                    if length > best_length && (best_inside || !inside) {
 9570                        continue;
 9571                    }
 9572
 9573                    best_length = length;
 9574                    best_inside = inside;
 9575                    best_in_bracket_range = in_bracket_range;
 9576                    best_destination = Some(
 9577                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9578                            if inside {
 9579                                open.end
 9580                            } else {
 9581                                open.start
 9582                            }
 9583                        } else if inside {
 9584                            *close.start()
 9585                        } else {
 9586                            *close.end()
 9587                        },
 9588                    );
 9589                }
 9590
 9591                if let Some(destination) = best_destination {
 9592                    selection.collapse_to(destination, SelectionGoal::None);
 9593                }
 9594            })
 9595        });
 9596    }
 9597
 9598    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9599        self.end_selection(cx);
 9600        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9601        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9602            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9603            self.select_next_state = entry.select_next_state;
 9604            self.select_prev_state = entry.select_prev_state;
 9605            self.add_selections_state = entry.add_selections_state;
 9606            self.request_autoscroll(Autoscroll::newest(), cx);
 9607        }
 9608        self.selection_history.mode = SelectionHistoryMode::Normal;
 9609    }
 9610
 9611    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9612        self.end_selection(cx);
 9613        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9614        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9615            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9616            self.select_next_state = entry.select_next_state;
 9617            self.select_prev_state = entry.select_prev_state;
 9618            self.add_selections_state = entry.add_selections_state;
 9619            self.request_autoscroll(Autoscroll::newest(), cx);
 9620        }
 9621        self.selection_history.mode = SelectionHistoryMode::Normal;
 9622    }
 9623
 9624    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9625        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9626    }
 9627
 9628    pub fn expand_excerpts_down(
 9629        &mut self,
 9630        action: &ExpandExcerptsDown,
 9631        cx: &mut ViewContext<Self>,
 9632    ) {
 9633        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9634    }
 9635
 9636    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9637        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9638    }
 9639
 9640    pub fn expand_excerpts_for_direction(
 9641        &mut self,
 9642        lines: u32,
 9643        direction: ExpandExcerptDirection,
 9644        cx: &mut ViewContext<Self>,
 9645    ) {
 9646        let selections = self.selections.disjoint_anchors();
 9647
 9648        let lines = if lines == 0 {
 9649            EditorSettings::get_global(cx).expand_excerpt_lines
 9650        } else {
 9651            lines
 9652        };
 9653
 9654        self.buffer.update(cx, |buffer, cx| {
 9655            buffer.expand_excerpts(
 9656                selections
 9657                    .iter()
 9658                    .map(|selection| selection.head().excerpt_id)
 9659                    .dedup(),
 9660                lines,
 9661                direction,
 9662                cx,
 9663            )
 9664        })
 9665    }
 9666
 9667    pub fn expand_excerpt(
 9668        &mut self,
 9669        excerpt: ExcerptId,
 9670        direction: ExpandExcerptDirection,
 9671        cx: &mut ViewContext<Self>,
 9672    ) {
 9673        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9674        self.buffer.update(cx, |buffer, cx| {
 9675            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9676        })
 9677    }
 9678
 9679    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9680        self.go_to_diagnostic_impl(Direction::Next, cx)
 9681    }
 9682
 9683    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9684        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9685    }
 9686
 9687    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9688        let buffer = self.buffer.read(cx).snapshot(cx);
 9689        let selection = self.selections.newest::<usize>(cx);
 9690
 9691        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9692        if direction == Direction::Next {
 9693            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9694                let (group_id, jump_to) = popover.activation_info();
 9695                if self.activate_diagnostics(group_id, cx) {
 9696                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9697                        let mut new_selection = s.newest_anchor().clone();
 9698                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9699                        s.select_anchors(vec![new_selection.clone()]);
 9700                    });
 9701                }
 9702                return;
 9703            }
 9704        }
 9705
 9706        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9707            active_diagnostics
 9708                .primary_range
 9709                .to_offset(&buffer)
 9710                .to_inclusive()
 9711        });
 9712        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9713            if active_primary_range.contains(&selection.head()) {
 9714                *active_primary_range.start()
 9715            } else {
 9716                selection.head()
 9717            }
 9718        } else {
 9719            selection.head()
 9720        };
 9721        let snapshot = self.snapshot(cx);
 9722        loop {
 9723            let diagnostics = if direction == Direction::Prev {
 9724                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9725            } else {
 9726                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9727            }
 9728            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9729            let group = diagnostics
 9730                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9731                // be sorted in a stable way
 9732                // skip until we are at current active diagnostic, if it exists
 9733                .skip_while(|entry| {
 9734                    (match direction {
 9735                        Direction::Prev => entry.range.start >= search_start,
 9736                        Direction::Next => entry.range.start <= search_start,
 9737                    }) && self
 9738                        .active_diagnostics
 9739                        .as_ref()
 9740                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9741                })
 9742                .find_map(|entry| {
 9743                    if entry.diagnostic.is_primary
 9744                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9745                        && !entry.range.is_empty()
 9746                        // if we match with the active diagnostic, skip it
 9747                        && Some(entry.diagnostic.group_id)
 9748                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9749                    {
 9750                        Some((entry.range, entry.diagnostic.group_id))
 9751                    } else {
 9752                        None
 9753                    }
 9754                });
 9755
 9756            if let Some((primary_range, group_id)) = group {
 9757                if self.activate_diagnostics(group_id, cx) {
 9758                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9759                        s.select(vec![Selection {
 9760                            id: selection.id,
 9761                            start: primary_range.start,
 9762                            end: primary_range.start,
 9763                            reversed: false,
 9764                            goal: SelectionGoal::None,
 9765                        }]);
 9766                    });
 9767                }
 9768                break;
 9769            } else {
 9770                // Cycle around to the start of the buffer, potentially moving back to the start of
 9771                // the currently active diagnostic.
 9772                active_primary_range.take();
 9773                if direction == Direction::Prev {
 9774                    if search_start == buffer.len() {
 9775                        break;
 9776                    } else {
 9777                        search_start = buffer.len();
 9778                    }
 9779                } else if search_start == 0 {
 9780                    break;
 9781                } else {
 9782                    search_start = 0;
 9783                }
 9784            }
 9785        }
 9786    }
 9787
 9788    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9789        let snapshot = self
 9790            .display_map
 9791            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9792        let selection = self.selections.newest::<Point>(cx);
 9793        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9794    }
 9795
 9796    fn go_to_hunk_after_position(
 9797        &mut self,
 9798        snapshot: &DisplaySnapshot,
 9799        position: Point,
 9800        cx: &mut ViewContext<'_, Editor>,
 9801    ) -> Option<MultiBufferDiffHunk> {
 9802        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9803            snapshot,
 9804            position,
 9805            false,
 9806            snapshot
 9807                .buffer_snapshot
 9808                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9809            cx,
 9810        ) {
 9811            return Some(hunk);
 9812        }
 9813
 9814        let wrapped_point = Point::zero();
 9815        self.go_to_next_hunk_in_direction(
 9816            snapshot,
 9817            wrapped_point,
 9818            true,
 9819            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9820                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9821            ),
 9822            cx,
 9823        )
 9824    }
 9825
 9826    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9827        let snapshot = self
 9828            .display_map
 9829            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9830        let selection = self.selections.newest::<Point>(cx);
 9831
 9832        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9833    }
 9834
 9835    fn go_to_hunk_before_position(
 9836        &mut self,
 9837        snapshot: &DisplaySnapshot,
 9838        position: Point,
 9839        cx: &mut ViewContext<'_, Editor>,
 9840    ) -> Option<MultiBufferDiffHunk> {
 9841        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9842            snapshot,
 9843            position,
 9844            false,
 9845            snapshot
 9846                .buffer_snapshot
 9847                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9848            cx,
 9849        ) {
 9850            return Some(hunk);
 9851        }
 9852
 9853        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9854        self.go_to_next_hunk_in_direction(
 9855            snapshot,
 9856            wrapped_point,
 9857            true,
 9858            snapshot
 9859                .buffer_snapshot
 9860                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9861            cx,
 9862        )
 9863    }
 9864
 9865    fn go_to_next_hunk_in_direction(
 9866        &mut self,
 9867        snapshot: &DisplaySnapshot,
 9868        initial_point: Point,
 9869        is_wrapped: bool,
 9870        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9871        cx: &mut ViewContext<Editor>,
 9872    ) -> Option<MultiBufferDiffHunk> {
 9873        let display_point = initial_point.to_display_point(snapshot);
 9874        let mut hunks = hunks
 9875            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9876            .filter(|(display_hunk, _)| {
 9877                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9878            })
 9879            .dedup();
 9880
 9881        if let Some((display_hunk, hunk)) = hunks.next() {
 9882            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9883                let row = display_hunk.start_display_row();
 9884                let point = DisplayPoint::new(row, 0);
 9885                s.select_display_ranges([point..point]);
 9886            });
 9887
 9888            Some(hunk)
 9889        } else {
 9890            None
 9891        }
 9892    }
 9893
 9894    pub fn go_to_definition(
 9895        &mut self,
 9896        _: &GoToDefinition,
 9897        cx: &mut ViewContext<Self>,
 9898    ) -> Task<Result<Navigated>> {
 9899        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9900        cx.spawn(|editor, mut cx| async move {
 9901            if definition.await? == Navigated::Yes {
 9902                return Ok(Navigated::Yes);
 9903            }
 9904            match editor.update(&mut cx, |editor, cx| {
 9905                editor.find_all_references(&FindAllReferences, cx)
 9906            })? {
 9907                Some(references) => references.await,
 9908                None => Ok(Navigated::No),
 9909            }
 9910        })
 9911    }
 9912
 9913    pub fn go_to_declaration(
 9914        &mut self,
 9915        _: &GoToDeclaration,
 9916        cx: &mut ViewContext<Self>,
 9917    ) -> Task<Result<Navigated>> {
 9918        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9919    }
 9920
 9921    pub fn go_to_declaration_split(
 9922        &mut self,
 9923        _: &GoToDeclaration,
 9924        cx: &mut ViewContext<Self>,
 9925    ) -> Task<Result<Navigated>> {
 9926        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9927    }
 9928
 9929    pub fn go_to_implementation(
 9930        &mut self,
 9931        _: &GoToImplementation,
 9932        cx: &mut ViewContext<Self>,
 9933    ) -> Task<Result<Navigated>> {
 9934        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9935    }
 9936
 9937    pub fn go_to_implementation_split(
 9938        &mut self,
 9939        _: &GoToImplementationSplit,
 9940        cx: &mut ViewContext<Self>,
 9941    ) -> Task<Result<Navigated>> {
 9942        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9943    }
 9944
 9945    pub fn go_to_type_definition(
 9946        &mut self,
 9947        _: &GoToTypeDefinition,
 9948        cx: &mut ViewContext<Self>,
 9949    ) -> Task<Result<Navigated>> {
 9950        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9951    }
 9952
 9953    pub fn go_to_definition_split(
 9954        &mut self,
 9955        _: &GoToDefinitionSplit,
 9956        cx: &mut ViewContext<Self>,
 9957    ) -> Task<Result<Navigated>> {
 9958        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9959    }
 9960
 9961    pub fn go_to_type_definition_split(
 9962        &mut self,
 9963        _: &GoToTypeDefinitionSplit,
 9964        cx: &mut ViewContext<Self>,
 9965    ) -> Task<Result<Navigated>> {
 9966        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9967    }
 9968
 9969    fn go_to_definition_of_kind(
 9970        &mut self,
 9971        kind: GotoDefinitionKind,
 9972        split: bool,
 9973        cx: &mut ViewContext<Self>,
 9974    ) -> Task<Result<Navigated>> {
 9975        let Some(provider) = self.semantics_provider.clone() else {
 9976            return Task::ready(Ok(Navigated::No));
 9977        };
 9978        let head = self.selections.newest::<usize>(cx).head();
 9979        let buffer = self.buffer.read(cx);
 9980        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9981            text_anchor
 9982        } else {
 9983            return Task::ready(Ok(Navigated::No));
 9984        };
 9985
 9986        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9987            return Task::ready(Ok(Navigated::No));
 9988        };
 9989
 9990        cx.spawn(|editor, mut cx| async move {
 9991            let definitions = definitions.await?;
 9992            let navigated = editor
 9993                .update(&mut cx, |editor, cx| {
 9994                    editor.navigate_to_hover_links(
 9995                        Some(kind),
 9996                        definitions
 9997                            .into_iter()
 9998                            .filter(|location| {
 9999                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10000                            })
10001                            .map(HoverLink::Text)
10002                            .collect::<Vec<_>>(),
10003                        split,
10004                        cx,
10005                    )
10006                })?
10007                .await?;
10008            anyhow::Ok(navigated)
10009        })
10010    }
10011
10012    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
10013        let position = self.selections.newest_anchor().head();
10014        let Some((buffer, buffer_position)) =
10015            self.buffer.read(cx).text_anchor_for_position(position, cx)
10016        else {
10017            return;
10018        };
10019
10020        cx.spawn(|editor, mut cx| async move {
10021            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10022                editor.update(&mut cx, |_, cx| {
10023                    cx.open_url(&url);
10024                })
10025            } else {
10026                Ok(())
10027            }
10028        })
10029        .detach();
10030    }
10031
10032    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10033        let Some(workspace) = self.workspace() else {
10034            return;
10035        };
10036
10037        let position = self.selections.newest_anchor().head();
10038
10039        let Some((buffer, buffer_position)) =
10040            self.buffer.read(cx).text_anchor_for_position(position, cx)
10041        else {
10042            return;
10043        };
10044
10045        let project = self.project.clone();
10046
10047        cx.spawn(|_, mut cx| async move {
10048            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10049
10050            if let Some((_, path)) = result {
10051                workspace
10052                    .update(&mut cx, |workspace, cx| {
10053                        workspace.open_resolved_path(path, cx)
10054                    })?
10055                    .await?;
10056            }
10057            anyhow::Ok(())
10058        })
10059        .detach();
10060    }
10061
10062    pub(crate) fn navigate_to_hover_links(
10063        &mut self,
10064        kind: Option<GotoDefinitionKind>,
10065        mut definitions: Vec<HoverLink>,
10066        split: bool,
10067        cx: &mut ViewContext<Editor>,
10068    ) -> Task<Result<Navigated>> {
10069        // If there is one definition, just open it directly
10070        if definitions.len() == 1 {
10071            let definition = definitions.pop().unwrap();
10072
10073            enum TargetTaskResult {
10074                Location(Option<Location>),
10075                AlreadyNavigated,
10076            }
10077
10078            let target_task = match definition {
10079                HoverLink::Text(link) => {
10080                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10081                }
10082                HoverLink::InlayHint(lsp_location, server_id) => {
10083                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10084                    cx.background_executor().spawn(async move {
10085                        let location = computation.await?;
10086                        Ok(TargetTaskResult::Location(location))
10087                    })
10088                }
10089                HoverLink::Url(url) => {
10090                    cx.open_url(&url);
10091                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10092                }
10093                HoverLink::File(path) => {
10094                    if let Some(workspace) = self.workspace() {
10095                        cx.spawn(|_, mut cx| async move {
10096                            workspace
10097                                .update(&mut cx, |workspace, cx| {
10098                                    workspace.open_resolved_path(path, cx)
10099                                })?
10100                                .await
10101                                .map(|_| TargetTaskResult::AlreadyNavigated)
10102                        })
10103                    } else {
10104                        Task::ready(Ok(TargetTaskResult::Location(None)))
10105                    }
10106                }
10107            };
10108            cx.spawn(|editor, mut cx| async move {
10109                let target = match target_task.await.context("target resolution task")? {
10110                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10111                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10112                    TargetTaskResult::Location(Some(target)) => target,
10113                };
10114
10115                editor.update(&mut cx, |editor, cx| {
10116                    let Some(workspace) = editor.workspace() else {
10117                        return Navigated::No;
10118                    };
10119                    let pane = workspace.read(cx).active_pane().clone();
10120
10121                    let range = target.range.to_offset(target.buffer.read(cx));
10122                    let range = editor.range_for_match(&range);
10123
10124                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10125                        let buffer = target.buffer.read(cx);
10126                        let range = check_multiline_range(buffer, range);
10127                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10128                            s.select_ranges([range]);
10129                        });
10130                    } else {
10131                        cx.window_context().defer(move |cx| {
10132                            let target_editor: View<Self> =
10133                                workspace.update(cx, |workspace, cx| {
10134                                    let pane = if split {
10135                                        workspace.adjacent_pane(cx)
10136                                    } else {
10137                                        workspace.active_pane().clone()
10138                                    };
10139
10140                                    workspace.open_project_item(
10141                                        pane,
10142                                        target.buffer.clone(),
10143                                        true,
10144                                        true,
10145                                        cx,
10146                                    )
10147                                });
10148                            target_editor.update(cx, |target_editor, cx| {
10149                                // When selecting a definition in a different buffer, disable the nav history
10150                                // to avoid creating a history entry at the previous cursor location.
10151                                pane.update(cx, |pane, _| pane.disable_history());
10152                                let buffer = target.buffer.read(cx);
10153                                let range = check_multiline_range(buffer, range);
10154                                target_editor.change_selections(
10155                                    Some(Autoscroll::focused()),
10156                                    cx,
10157                                    |s| {
10158                                        s.select_ranges([range]);
10159                                    },
10160                                );
10161                                pane.update(cx, |pane, _| pane.enable_history());
10162                            });
10163                        });
10164                    }
10165                    Navigated::Yes
10166                })
10167            })
10168        } else if !definitions.is_empty() {
10169            cx.spawn(|editor, mut cx| async move {
10170                let (title, location_tasks, workspace) = editor
10171                    .update(&mut cx, |editor, cx| {
10172                        let tab_kind = match kind {
10173                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10174                            _ => "Definitions",
10175                        };
10176                        let title = definitions
10177                            .iter()
10178                            .find_map(|definition| match definition {
10179                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10180                                    let buffer = origin.buffer.read(cx);
10181                                    format!(
10182                                        "{} for {}",
10183                                        tab_kind,
10184                                        buffer
10185                                            .text_for_range(origin.range.clone())
10186                                            .collect::<String>()
10187                                    )
10188                                }),
10189                                HoverLink::InlayHint(_, _) => None,
10190                                HoverLink::Url(_) => None,
10191                                HoverLink::File(_) => None,
10192                            })
10193                            .unwrap_or(tab_kind.to_string());
10194                        let location_tasks = definitions
10195                            .into_iter()
10196                            .map(|definition| match definition {
10197                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10198                                HoverLink::InlayHint(lsp_location, server_id) => {
10199                                    editor.compute_target_location(lsp_location, server_id, cx)
10200                                }
10201                                HoverLink::Url(_) => Task::ready(Ok(None)),
10202                                HoverLink::File(_) => Task::ready(Ok(None)),
10203                            })
10204                            .collect::<Vec<_>>();
10205                        (title, location_tasks, editor.workspace().clone())
10206                    })
10207                    .context("location tasks preparation")?;
10208
10209                let locations = future::join_all(location_tasks)
10210                    .await
10211                    .into_iter()
10212                    .filter_map(|location| location.transpose())
10213                    .collect::<Result<_>>()
10214                    .context("location tasks")?;
10215
10216                let Some(workspace) = workspace else {
10217                    return Ok(Navigated::No);
10218                };
10219                let opened = workspace
10220                    .update(&mut cx, |workspace, cx| {
10221                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10222                    })
10223                    .ok();
10224
10225                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10226            })
10227        } else {
10228            Task::ready(Ok(Navigated::No))
10229        }
10230    }
10231
10232    fn compute_target_location(
10233        &self,
10234        lsp_location: lsp::Location,
10235        server_id: LanguageServerId,
10236        cx: &mut ViewContext<Self>,
10237    ) -> Task<anyhow::Result<Option<Location>>> {
10238        let Some(project) = self.project.clone() else {
10239            return Task::Ready(Some(Ok(None)));
10240        };
10241
10242        cx.spawn(move |editor, mut cx| async move {
10243            let location_task = editor.update(&mut cx, |_, cx| {
10244                project.update(cx, |project, cx| {
10245                    let language_server_name = project
10246                        .language_server_statuses(cx)
10247                        .find(|(id, _)| server_id == *id)
10248                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10249                    language_server_name.map(|language_server_name| {
10250                        project.open_local_buffer_via_lsp(
10251                            lsp_location.uri.clone(),
10252                            server_id,
10253                            language_server_name,
10254                            cx,
10255                        )
10256                    })
10257                })
10258            })?;
10259            let location = match location_task {
10260                Some(task) => Some({
10261                    let target_buffer_handle = task.await.context("open local buffer")?;
10262                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10263                        let target_start = target_buffer
10264                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10265                        let target_end = target_buffer
10266                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10267                        target_buffer.anchor_after(target_start)
10268                            ..target_buffer.anchor_before(target_end)
10269                    })?;
10270                    Location {
10271                        buffer: target_buffer_handle,
10272                        range,
10273                    }
10274                }),
10275                None => None,
10276            };
10277            Ok(location)
10278        })
10279    }
10280
10281    pub fn find_all_references(
10282        &mut self,
10283        _: &FindAllReferences,
10284        cx: &mut ViewContext<Self>,
10285    ) -> Option<Task<Result<Navigated>>> {
10286        let selection = self.selections.newest::<usize>(cx);
10287        let multi_buffer = self.buffer.read(cx);
10288        let head = selection.head();
10289
10290        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10291        let head_anchor = multi_buffer_snapshot.anchor_at(
10292            head,
10293            if head < selection.tail() {
10294                Bias::Right
10295            } else {
10296                Bias::Left
10297            },
10298        );
10299
10300        match self
10301            .find_all_references_task_sources
10302            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10303        {
10304            Ok(_) => {
10305                log::info!(
10306                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10307                );
10308                return None;
10309            }
10310            Err(i) => {
10311                self.find_all_references_task_sources.insert(i, head_anchor);
10312            }
10313        }
10314
10315        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10316        let workspace = self.workspace()?;
10317        let project = workspace.read(cx).project().clone();
10318        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10319        Some(cx.spawn(|editor, mut cx| async move {
10320            let _cleanup = defer({
10321                let mut cx = cx.clone();
10322                move || {
10323                    let _ = editor.update(&mut cx, |editor, _| {
10324                        if let Ok(i) =
10325                            editor
10326                                .find_all_references_task_sources
10327                                .binary_search_by(|anchor| {
10328                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10329                                })
10330                        {
10331                            editor.find_all_references_task_sources.remove(i);
10332                        }
10333                    });
10334                }
10335            });
10336
10337            let locations = references.await?;
10338            if locations.is_empty() {
10339                return anyhow::Ok(Navigated::No);
10340            }
10341
10342            workspace.update(&mut cx, |workspace, cx| {
10343                let title = locations
10344                    .first()
10345                    .as_ref()
10346                    .map(|location| {
10347                        let buffer = location.buffer.read(cx);
10348                        format!(
10349                            "References to `{}`",
10350                            buffer
10351                                .text_for_range(location.range.clone())
10352                                .collect::<String>()
10353                        )
10354                    })
10355                    .unwrap();
10356                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10357                Navigated::Yes
10358            })
10359        }))
10360    }
10361
10362    /// Opens a multibuffer with the given project locations in it
10363    pub fn open_locations_in_multibuffer(
10364        workspace: &mut Workspace,
10365        mut locations: Vec<Location>,
10366        title: String,
10367        split: bool,
10368        cx: &mut ViewContext<Workspace>,
10369    ) {
10370        // If there are multiple definitions, open them in a multibuffer
10371        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10372        let mut locations = locations.into_iter().peekable();
10373        let mut ranges_to_highlight = Vec::new();
10374        let capability = workspace.project().read(cx).capability();
10375
10376        let excerpt_buffer = cx.new_model(|cx| {
10377            let mut multibuffer = MultiBuffer::new(capability);
10378            while let Some(location) = locations.next() {
10379                let buffer = location.buffer.read(cx);
10380                let mut ranges_for_buffer = Vec::new();
10381                let range = location.range.to_offset(buffer);
10382                ranges_for_buffer.push(range.clone());
10383
10384                while let Some(next_location) = locations.peek() {
10385                    if next_location.buffer == location.buffer {
10386                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10387                        locations.next();
10388                    } else {
10389                        break;
10390                    }
10391                }
10392
10393                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10394                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10395                    location.buffer.clone(),
10396                    ranges_for_buffer,
10397                    DEFAULT_MULTIBUFFER_CONTEXT,
10398                    cx,
10399                ))
10400            }
10401
10402            multibuffer.with_title(title)
10403        });
10404
10405        let editor = cx.new_view(|cx| {
10406            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10407        });
10408        editor.update(cx, |editor, cx| {
10409            if let Some(first_range) = ranges_to_highlight.first() {
10410                editor.change_selections(None, cx, |selections| {
10411                    selections.clear_disjoint();
10412                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10413                });
10414            }
10415            editor.highlight_background::<Self>(
10416                &ranges_to_highlight,
10417                |theme| theme.editor_highlighted_line_background,
10418                cx,
10419            );
10420        });
10421
10422        let item = Box::new(editor);
10423        let item_id = item.item_id();
10424
10425        if split {
10426            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10427        } else {
10428            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10429                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10430                    pane.close_current_preview_item(cx)
10431                } else {
10432                    None
10433                }
10434            });
10435            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10436        }
10437        workspace.active_pane().update(cx, |pane, cx| {
10438            pane.set_preview_item_id(Some(item_id), cx);
10439        });
10440    }
10441
10442    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10443        use language::ToOffset as _;
10444
10445        let provider = self.semantics_provider.clone()?;
10446        let selection = self.selections.newest_anchor().clone();
10447        let (cursor_buffer, cursor_buffer_position) = self
10448            .buffer
10449            .read(cx)
10450            .text_anchor_for_position(selection.head(), cx)?;
10451        let (tail_buffer, cursor_buffer_position_end) = self
10452            .buffer
10453            .read(cx)
10454            .text_anchor_for_position(selection.tail(), cx)?;
10455        if tail_buffer != cursor_buffer {
10456            return None;
10457        }
10458
10459        let snapshot = cursor_buffer.read(cx).snapshot();
10460        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10461        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10462        let prepare_rename = provider
10463            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10464            .unwrap_or_else(|| Task::ready(Ok(None)));
10465        drop(snapshot);
10466
10467        Some(cx.spawn(|this, mut cx| async move {
10468            let rename_range = if let Some(range) = prepare_rename.await? {
10469                Some(range)
10470            } else {
10471                this.update(&mut cx, |this, cx| {
10472                    let buffer = this.buffer.read(cx).snapshot(cx);
10473                    let mut buffer_highlights = this
10474                        .document_highlights_for_position(selection.head(), &buffer)
10475                        .filter(|highlight| {
10476                            highlight.start.excerpt_id == selection.head().excerpt_id
10477                                && highlight.end.excerpt_id == selection.head().excerpt_id
10478                        });
10479                    buffer_highlights
10480                        .next()
10481                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10482                })?
10483            };
10484            if let Some(rename_range) = rename_range {
10485                this.update(&mut cx, |this, cx| {
10486                    let snapshot = cursor_buffer.read(cx).snapshot();
10487                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10488                    let cursor_offset_in_rename_range =
10489                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10490                    let cursor_offset_in_rename_range_end =
10491                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10492
10493                    this.take_rename(false, cx);
10494                    let buffer = this.buffer.read(cx).read(cx);
10495                    let cursor_offset = selection.head().to_offset(&buffer);
10496                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10497                    let rename_end = rename_start + rename_buffer_range.len();
10498                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10499                    let mut old_highlight_id = None;
10500                    let old_name: Arc<str> = buffer
10501                        .chunks(rename_start..rename_end, true)
10502                        .map(|chunk| {
10503                            if old_highlight_id.is_none() {
10504                                old_highlight_id = chunk.syntax_highlight_id;
10505                            }
10506                            chunk.text
10507                        })
10508                        .collect::<String>()
10509                        .into();
10510
10511                    drop(buffer);
10512
10513                    // Position the selection in the rename editor so that it matches the current selection.
10514                    this.show_local_selections = false;
10515                    let rename_editor = cx.new_view(|cx| {
10516                        let mut editor = Editor::single_line(cx);
10517                        editor.buffer.update(cx, |buffer, cx| {
10518                            buffer.edit([(0..0, old_name.clone())], None, cx)
10519                        });
10520                        let rename_selection_range = match cursor_offset_in_rename_range
10521                            .cmp(&cursor_offset_in_rename_range_end)
10522                        {
10523                            Ordering::Equal => {
10524                                editor.select_all(&SelectAll, cx);
10525                                return editor;
10526                            }
10527                            Ordering::Less => {
10528                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10529                            }
10530                            Ordering::Greater => {
10531                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10532                            }
10533                        };
10534                        if rename_selection_range.end > old_name.len() {
10535                            editor.select_all(&SelectAll, cx);
10536                        } else {
10537                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10538                                s.select_ranges([rename_selection_range]);
10539                            });
10540                        }
10541                        editor
10542                    });
10543                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10544                        if e == &EditorEvent::Focused {
10545                            cx.emit(EditorEvent::FocusedIn)
10546                        }
10547                    })
10548                    .detach();
10549
10550                    let write_highlights =
10551                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10552                    let read_highlights =
10553                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10554                    let ranges = write_highlights
10555                        .iter()
10556                        .flat_map(|(_, ranges)| ranges.iter())
10557                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10558                        .cloned()
10559                        .collect();
10560
10561                    this.highlight_text::<Rename>(
10562                        ranges,
10563                        HighlightStyle {
10564                            fade_out: Some(0.6),
10565                            ..Default::default()
10566                        },
10567                        cx,
10568                    );
10569                    let rename_focus_handle = rename_editor.focus_handle(cx);
10570                    cx.focus(&rename_focus_handle);
10571                    let block_id = this.insert_blocks(
10572                        [BlockProperties {
10573                            style: BlockStyle::Flex,
10574                            placement: BlockPlacement::Below(range.start),
10575                            height: 1,
10576                            render: Arc::new({
10577                                let rename_editor = rename_editor.clone();
10578                                move |cx: &mut BlockContext| {
10579                                    let mut text_style = cx.editor_style.text.clone();
10580                                    if let Some(highlight_style) = old_highlight_id
10581                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10582                                    {
10583                                        text_style = text_style.highlight(highlight_style);
10584                                    }
10585                                    div()
10586                                        .block_mouse_down()
10587                                        .pl(cx.anchor_x)
10588                                        .child(EditorElement::new(
10589                                            &rename_editor,
10590                                            EditorStyle {
10591                                                background: cx.theme().system().transparent,
10592                                                local_player: cx.editor_style.local_player,
10593                                                text: text_style,
10594                                                scrollbar_width: cx.editor_style.scrollbar_width,
10595                                                syntax: cx.editor_style.syntax.clone(),
10596                                                status: cx.editor_style.status.clone(),
10597                                                inlay_hints_style: HighlightStyle {
10598                                                    font_weight: Some(FontWeight::BOLD),
10599                                                    ..make_inlay_hints_style(cx)
10600                                                },
10601                                                suggestions_style: HighlightStyle {
10602                                                    color: Some(cx.theme().status().predictive),
10603                                                    ..HighlightStyle::default()
10604                                                },
10605                                                ..EditorStyle::default()
10606                                            },
10607                                        ))
10608                                        .into_any_element()
10609                                }
10610                            }),
10611                            priority: 0,
10612                        }],
10613                        Some(Autoscroll::fit()),
10614                        cx,
10615                    )[0];
10616                    this.pending_rename = Some(RenameState {
10617                        range,
10618                        old_name,
10619                        editor: rename_editor,
10620                        block_id,
10621                    });
10622                })?;
10623            }
10624
10625            Ok(())
10626        }))
10627    }
10628
10629    pub fn confirm_rename(
10630        &mut self,
10631        _: &ConfirmRename,
10632        cx: &mut ViewContext<Self>,
10633    ) -> Option<Task<Result<()>>> {
10634        let rename = self.take_rename(false, cx)?;
10635        let workspace = self.workspace()?.downgrade();
10636        let (buffer, start) = self
10637            .buffer
10638            .read(cx)
10639            .text_anchor_for_position(rename.range.start, cx)?;
10640        let (end_buffer, _) = self
10641            .buffer
10642            .read(cx)
10643            .text_anchor_for_position(rename.range.end, cx)?;
10644        if buffer != end_buffer {
10645            return None;
10646        }
10647
10648        let old_name = rename.old_name;
10649        let new_name = rename.editor.read(cx).text(cx);
10650
10651        let rename = self.semantics_provider.as_ref()?.perform_rename(
10652            &buffer,
10653            start,
10654            new_name.clone(),
10655            cx,
10656        )?;
10657
10658        Some(cx.spawn(|editor, mut cx| async move {
10659            let project_transaction = rename.await?;
10660            Self::open_project_transaction(
10661                &editor,
10662                workspace,
10663                project_transaction,
10664                format!("Rename: {}{}", old_name, new_name),
10665                cx.clone(),
10666            )
10667            .await?;
10668
10669            editor.update(&mut cx, |editor, cx| {
10670                editor.refresh_document_highlights(cx);
10671            })?;
10672            Ok(())
10673        }))
10674    }
10675
10676    fn take_rename(
10677        &mut self,
10678        moving_cursor: bool,
10679        cx: &mut ViewContext<Self>,
10680    ) -> Option<RenameState> {
10681        let rename = self.pending_rename.take()?;
10682        if rename.editor.focus_handle(cx).is_focused(cx) {
10683            cx.focus(&self.focus_handle);
10684        }
10685
10686        self.remove_blocks(
10687            [rename.block_id].into_iter().collect(),
10688            Some(Autoscroll::fit()),
10689            cx,
10690        );
10691        self.clear_highlights::<Rename>(cx);
10692        self.show_local_selections = true;
10693
10694        if moving_cursor {
10695            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10696                editor.selections.newest::<usize>(cx).head()
10697            });
10698
10699            // Update the selection to match the position of the selection inside
10700            // the rename editor.
10701            let snapshot = self.buffer.read(cx).read(cx);
10702            let rename_range = rename.range.to_offset(&snapshot);
10703            let cursor_in_editor = snapshot
10704                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10705                .min(rename_range.end);
10706            drop(snapshot);
10707
10708            self.change_selections(None, cx, |s| {
10709                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10710            });
10711        } else {
10712            self.refresh_document_highlights(cx);
10713        }
10714
10715        Some(rename)
10716    }
10717
10718    pub fn pending_rename(&self) -> Option<&RenameState> {
10719        self.pending_rename.as_ref()
10720    }
10721
10722    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10723        let project = match &self.project {
10724            Some(project) => project.clone(),
10725            None => return None,
10726        };
10727
10728        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10729    }
10730
10731    fn format_selections(
10732        &mut self,
10733        _: &FormatSelections,
10734        cx: &mut ViewContext<Self>,
10735    ) -> Option<Task<Result<()>>> {
10736        let project = match &self.project {
10737            Some(project) => project.clone(),
10738            None => return None,
10739        };
10740
10741        let selections = self
10742            .selections
10743            .all_adjusted(cx)
10744            .into_iter()
10745            .filter(|s| !s.is_empty())
10746            .collect_vec();
10747
10748        Some(self.perform_format(
10749            project,
10750            FormatTrigger::Manual,
10751            FormatTarget::Ranges(selections),
10752            cx,
10753        ))
10754    }
10755
10756    fn perform_format(
10757        &mut self,
10758        project: Model<Project>,
10759        trigger: FormatTrigger,
10760        target: FormatTarget,
10761        cx: &mut ViewContext<Self>,
10762    ) -> Task<Result<()>> {
10763        let buffer = self.buffer().clone();
10764        let mut buffers = buffer.read(cx).all_buffers();
10765        if trigger == FormatTrigger::Save {
10766            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10767        }
10768
10769        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10770        let format = project.update(cx, |project, cx| {
10771            project.format(buffers, true, trigger, target, cx)
10772        });
10773
10774        cx.spawn(|_, mut cx| async move {
10775            let transaction = futures::select_biased! {
10776                () = timeout => {
10777                    log::warn!("timed out waiting for formatting");
10778                    None
10779                }
10780                transaction = format.log_err().fuse() => transaction,
10781            };
10782
10783            buffer
10784                .update(&mut cx, |buffer, cx| {
10785                    if let Some(transaction) = transaction {
10786                        if !buffer.is_singleton() {
10787                            buffer.push_transaction(&transaction.0, cx);
10788                        }
10789                    }
10790
10791                    cx.notify();
10792                })
10793                .ok();
10794
10795            Ok(())
10796        })
10797    }
10798
10799    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10800        if let Some(project) = self.project.clone() {
10801            self.buffer.update(cx, |multi_buffer, cx| {
10802                project.update(cx, |project, cx| {
10803                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10804                });
10805            })
10806        }
10807    }
10808
10809    fn cancel_language_server_work(
10810        &mut self,
10811        _: &actions::CancelLanguageServerWork,
10812        cx: &mut ViewContext<Self>,
10813    ) {
10814        if let Some(project) = self.project.clone() {
10815            self.buffer.update(cx, |multi_buffer, cx| {
10816                project.update(cx, |project, cx| {
10817                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10818                });
10819            })
10820        }
10821    }
10822
10823    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10824        cx.show_character_palette();
10825    }
10826
10827    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10828        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10829            let buffer = self.buffer.read(cx).snapshot(cx);
10830            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10831            let is_valid = buffer
10832                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10833                .any(|entry| {
10834                    entry.diagnostic.is_primary
10835                        && !entry.range.is_empty()
10836                        && entry.range.start == primary_range_start
10837                        && entry.diagnostic.message == active_diagnostics.primary_message
10838                });
10839
10840            if is_valid != active_diagnostics.is_valid {
10841                active_diagnostics.is_valid = is_valid;
10842                let mut new_styles = HashMap::default();
10843                for (block_id, diagnostic) in &active_diagnostics.blocks {
10844                    new_styles.insert(
10845                        *block_id,
10846                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10847                    );
10848                }
10849                self.display_map.update(cx, |display_map, _cx| {
10850                    display_map.replace_blocks(new_styles)
10851                });
10852            }
10853        }
10854    }
10855
10856    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10857        self.dismiss_diagnostics(cx);
10858        let snapshot = self.snapshot(cx);
10859        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10860            let buffer = self.buffer.read(cx).snapshot(cx);
10861
10862            let mut primary_range = None;
10863            let mut primary_message = None;
10864            let mut group_end = Point::zero();
10865            let diagnostic_group = buffer
10866                .diagnostic_group::<MultiBufferPoint>(group_id)
10867                .filter_map(|entry| {
10868                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10869                        && (entry.range.start.row == entry.range.end.row
10870                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10871                    {
10872                        return None;
10873                    }
10874                    if entry.range.end > group_end {
10875                        group_end = entry.range.end;
10876                    }
10877                    if entry.diagnostic.is_primary {
10878                        primary_range = Some(entry.range.clone());
10879                        primary_message = Some(entry.diagnostic.message.clone());
10880                    }
10881                    Some(entry)
10882                })
10883                .collect::<Vec<_>>();
10884            let primary_range = primary_range?;
10885            let primary_message = primary_message?;
10886            let primary_range =
10887                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10888
10889            let blocks = display_map
10890                .insert_blocks(
10891                    diagnostic_group.iter().map(|entry| {
10892                        let diagnostic = entry.diagnostic.clone();
10893                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10894                        BlockProperties {
10895                            style: BlockStyle::Fixed,
10896                            placement: BlockPlacement::Below(
10897                                buffer.anchor_after(entry.range.start),
10898                            ),
10899                            height: message_height,
10900                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10901                            priority: 0,
10902                        }
10903                    }),
10904                    cx,
10905                )
10906                .into_iter()
10907                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10908                .collect();
10909
10910            Some(ActiveDiagnosticGroup {
10911                primary_range,
10912                primary_message,
10913                group_id,
10914                blocks,
10915                is_valid: true,
10916            })
10917        });
10918        self.active_diagnostics.is_some()
10919    }
10920
10921    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10922        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10923            self.display_map.update(cx, |display_map, cx| {
10924                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10925            });
10926            cx.notify();
10927        }
10928    }
10929
10930    pub fn set_selections_from_remote(
10931        &mut self,
10932        selections: Vec<Selection<Anchor>>,
10933        pending_selection: Option<Selection<Anchor>>,
10934        cx: &mut ViewContext<Self>,
10935    ) {
10936        let old_cursor_position = self.selections.newest_anchor().head();
10937        self.selections.change_with(cx, |s| {
10938            s.select_anchors(selections);
10939            if let Some(pending_selection) = pending_selection {
10940                s.set_pending(pending_selection, SelectMode::Character);
10941            } else {
10942                s.clear_pending();
10943            }
10944        });
10945        self.selections_did_change(false, &old_cursor_position, true, cx);
10946    }
10947
10948    fn push_to_selection_history(&mut self) {
10949        self.selection_history.push(SelectionHistoryEntry {
10950            selections: self.selections.disjoint_anchors(),
10951            select_next_state: self.select_next_state.clone(),
10952            select_prev_state: self.select_prev_state.clone(),
10953            add_selections_state: self.add_selections_state.clone(),
10954        });
10955    }
10956
10957    pub fn transact(
10958        &mut self,
10959        cx: &mut ViewContext<Self>,
10960        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10961    ) -> Option<TransactionId> {
10962        self.start_transaction_at(Instant::now(), cx);
10963        update(self, cx);
10964        self.end_transaction_at(Instant::now(), cx)
10965    }
10966
10967    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10968        self.end_selection(cx);
10969        if let Some(tx_id) = self
10970            .buffer
10971            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10972        {
10973            self.selection_history
10974                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10975            cx.emit(EditorEvent::TransactionBegun {
10976                transaction_id: tx_id,
10977            })
10978        }
10979    }
10980
10981    fn end_transaction_at(
10982        &mut self,
10983        now: Instant,
10984        cx: &mut ViewContext<Self>,
10985    ) -> Option<TransactionId> {
10986        if let Some(transaction_id) = self
10987            .buffer
10988            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10989        {
10990            if let Some((_, end_selections)) =
10991                self.selection_history.transaction_mut(transaction_id)
10992            {
10993                *end_selections = Some(self.selections.disjoint_anchors());
10994            } else {
10995                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10996            }
10997
10998            cx.emit(EditorEvent::Edited { transaction_id });
10999            Some(transaction_id)
11000        } else {
11001            None
11002        }
11003    }
11004
11005    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
11006        let selection = self.selections.newest::<Point>(cx);
11007
11008        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11009        let range = if selection.is_empty() {
11010            let point = selection.head().to_display_point(&display_map);
11011            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11012            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11013                .to_point(&display_map);
11014            start..end
11015        } else {
11016            selection.range()
11017        };
11018        if display_map.folds_in_range(range).next().is_some() {
11019            self.unfold_lines(&Default::default(), cx)
11020        } else {
11021            self.fold(&Default::default(), cx)
11022        }
11023    }
11024
11025    pub fn toggle_fold_recursive(
11026        &mut self,
11027        _: &actions::ToggleFoldRecursive,
11028        cx: &mut ViewContext<Self>,
11029    ) {
11030        let selection = self.selections.newest::<Point>(cx);
11031
11032        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11033        let range = if selection.is_empty() {
11034            let point = selection.head().to_display_point(&display_map);
11035            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11036            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11037                .to_point(&display_map);
11038            start..end
11039        } else {
11040            selection.range()
11041        };
11042        if display_map.folds_in_range(range).next().is_some() {
11043            self.unfold_recursive(&Default::default(), cx)
11044        } else {
11045            self.fold_recursive(&Default::default(), cx)
11046        }
11047    }
11048
11049    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11050        let mut to_fold = Vec::new();
11051        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11052        let selections = self.selections.all_adjusted(cx);
11053
11054        for selection in selections {
11055            let range = selection.range().sorted();
11056            let buffer_start_row = range.start.row;
11057
11058            if range.start.row != range.end.row {
11059                let mut found = false;
11060                let mut row = range.start.row;
11061                while row <= range.end.row {
11062                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11063                        found = true;
11064                        row = crease.range().end.row + 1;
11065                        to_fold.push(crease);
11066                    } else {
11067                        row += 1
11068                    }
11069                }
11070                if found {
11071                    continue;
11072                }
11073            }
11074
11075            for row in (0..=range.start.row).rev() {
11076                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11077                    if crease.range().end.row >= buffer_start_row {
11078                        to_fold.push(crease);
11079                        if row <= range.start.row {
11080                            break;
11081                        }
11082                    }
11083                }
11084            }
11085        }
11086
11087        self.fold_creases(to_fold, true, cx);
11088    }
11089
11090    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11091        let fold_at_level = fold_at.level;
11092        let snapshot = self.buffer.read(cx).snapshot(cx);
11093        let mut to_fold = Vec::new();
11094        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11095
11096        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11097            while start_row < end_row {
11098                match self
11099                    .snapshot(cx)
11100                    .crease_for_buffer_row(MultiBufferRow(start_row))
11101                {
11102                    Some(crease) => {
11103                        let nested_start_row = crease.range().start.row + 1;
11104                        let nested_end_row = crease.range().end.row;
11105
11106                        if current_level < fold_at_level {
11107                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11108                        } else if current_level == fold_at_level {
11109                            to_fold.push(crease);
11110                        }
11111
11112                        start_row = nested_end_row + 1;
11113                    }
11114                    None => start_row += 1,
11115                }
11116            }
11117        }
11118
11119        self.fold_creases(to_fold, true, cx);
11120    }
11121
11122    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11123        let mut fold_ranges = Vec::new();
11124        let snapshot = self.buffer.read(cx).snapshot(cx);
11125
11126        for row in 0..snapshot.max_buffer_row().0 {
11127            if let Some(foldable_range) =
11128                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11129            {
11130                fold_ranges.push(foldable_range);
11131            }
11132        }
11133
11134        self.fold_creases(fold_ranges, true, cx);
11135    }
11136
11137    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11138        let mut to_fold = Vec::new();
11139        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11140        let selections = self.selections.all_adjusted(cx);
11141
11142        for selection in selections {
11143            let range = selection.range().sorted();
11144            let buffer_start_row = range.start.row;
11145
11146            if range.start.row != range.end.row {
11147                let mut found = false;
11148                for row in range.start.row..=range.end.row {
11149                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11150                        found = true;
11151                        to_fold.push(crease);
11152                    }
11153                }
11154                if found {
11155                    continue;
11156                }
11157            }
11158
11159            for row in (0..=range.start.row).rev() {
11160                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11161                    if crease.range().end.row >= buffer_start_row {
11162                        to_fold.push(crease);
11163                    } else {
11164                        break;
11165                    }
11166                }
11167            }
11168        }
11169
11170        self.fold_creases(to_fold, true, cx);
11171    }
11172
11173    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11174        let buffer_row = fold_at.buffer_row;
11175        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11176
11177        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11178            let autoscroll = self
11179                .selections
11180                .all::<Point>(cx)
11181                .iter()
11182                .any(|selection| crease.range().overlaps(&selection.range()));
11183
11184            self.fold_creases(vec![crease], autoscroll, cx);
11185        }
11186    }
11187
11188    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11189        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11190        let buffer = &display_map.buffer_snapshot;
11191        let selections = self.selections.all::<Point>(cx);
11192        let ranges = selections
11193            .iter()
11194            .map(|s| {
11195                let range = s.display_range(&display_map).sorted();
11196                let mut start = range.start.to_point(&display_map);
11197                let mut end = range.end.to_point(&display_map);
11198                start.column = 0;
11199                end.column = buffer.line_len(MultiBufferRow(end.row));
11200                start..end
11201            })
11202            .collect::<Vec<_>>();
11203
11204        self.unfold_ranges(&ranges, true, true, cx);
11205    }
11206
11207    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11208        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11209        let selections = self.selections.all::<Point>(cx);
11210        let ranges = selections
11211            .iter()
11212            .map(|s| {
11213                let mut range = s.display_range(&display_map).sorted();
11214                *range.start.column_mut() = 0;
11215                *range.end.column_mut() = display_map.line_len(range.end.row());
11216                let start = range.start.to_point(&display_map);
11217                let end = range.end.to_point(&display_map);
11218                start..end
11219            })
11220            .collect::<Vec<_>>();
11221
11222        self.unfold_ranges(&ranges, true, true, cx);
11223    }
11224
11225    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11226        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11227
11228        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11229            ..Point::new(
11230                unfold_at.buffer_row.0,
11231                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11232            );
11233
11234        let autoscroll = self
11235            .selections
11236            .all::<Point>(cx)
11237            .iter()
11238            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11239
11240        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11241    }
11242
11243    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11244        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11245        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11246    }
11247
11248    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11249        let selections = self.selections.all::<Point>(cx);
11250        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11251        let line_mode = self.selections.line_mode;
11252        let ranges = selections
11253            .into_iter()
11254            .map(|s| {
11255                if line_mode {
11256                    let start = Point::new(s.start.row, 0);
11257                    let end = Point::new(
11258                        s.end.row,
11259                        display_map
11260                            .buffer_snapshot
11261                            .line_len(MultiBufferRow(s.end.row)),
11262                    );
11263                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11264                } else {
11265                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11266                }
11267            })
11268            .collect::<Vec<_>>();
11269        self.fold_creases(ranges, true, cx);
11270    }
11271
11272    pub fn fold_creases<T: ToOffset + Clone>(
11273        &mut self,
11274        creases: Vec<Crease<T>>,
11275        auto_scroll: bool,
11276        cx: &mut ViewContext<Self>,
11277    ) {
11278        if creases.is_empty() {
11279            return;
11280        }
11281
11282        let mut buffers_affected = HashMap::default();
11283        let multi_buffer = self.buffer().read(cx);
11284        for crease in &creases {
11285            if let Some((_, buffer, _)) =
11286                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11287            {
11288                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11289            };
11290        }
11291
11292        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11293
11294        if auto_scroll {
11295            self.request_autoscroll(Autoscroll::fit(), cx);
11296        }
11297
11298        for buffer in buffers_affected.into_values() {
11299            self.sync_expanded_diff_hunks(buffer, cx);
11300        }
11301
11302        cx.notify();
11303
11304        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11305            // Clear diagnostics block when folding a range that contains it.
11306            let snapshot = self.snapshot(cx);
11307            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11308                drop(snapshot);
11309                self.active_diagnostics = Some(active_diagnostics);
11310                self.dismiss_diagnostics(cx);
11311            } else {
11312                self.active_diagnostics = Some(active_diagnostics);
11313            }
11314        }
11315
11316        self.scrollbar_marker_state.dirty = true;
11317    }
11318
11319    /// Removes any folds whose ranges intersect any of the given ranges.
11320    pub fn unfold_ranges<T: ToOffset + Clone>(
11321        &mut self,
11322        ranges: &[Range<T>],
11323        inclusive: bool,
11324        auto_scroll: bool,
11325        cx: &mut ViewContext<Self>,
11326    ) {
11327        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11328            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11329        });
11330    }
11331
11332    /// Removes any folds with the given ranges.
11333    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11334        &mut self,
11335        ranges: &[Range<T>],
11336        type_id: TypeId,
11337        auto_scroll: bool,
11338        cx: &mut ViewContext<Self>,
11339    ) {
11340        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11341            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11342        });
11343    }
11344
11345    fn remove_folds_with<T: ToOffset + Clone>(
11346        &mut self,
11347        ranges: &[Range<T>],
11348        auto_scroll: bool,
11349        cx: &mut ViewContext<Self>,
11350        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11351    ) {
11352        if ranges.is_empty() {
11353            return;
11354        }
11355
11356        let mut buffers_affected = HashMap::default();
11357        let multi_buffer = self.buffer().read(cx);
11358        for range in ranges {
11359            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11360                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11361            };
11362        }
11363
11364        self.display_map.update(cx, update);
11365
11366        if auto_scroll {
11367            self.request_autoscroll(Autoscroll::fit(), cx);
11368        }
11369
11370        for buffer in buffers_affected.into_values() {
11371            self.sync_expanded_diff_hunks(buffer, cx);
11372        }
11373
11374        cx.notify();
11375        self.scrollbar_marker_state.dirty = true;
11376        self.active_indent_guides_state.dirty = true;
11377    }
11378
11379    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11380        self.display_map.read(cx).fold_placeholder.clone()
11381    }
11382
11383    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11384        if hovered != self.gutter_hovered {
11385            self.gutter_hovered = hovered;
11386            cx.notify();
11387        }
11388    }
11389
11390    pub fn insert_blocks(
11391        &mut self,
11392        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11393        autoscroll: Option<Autoscroll>,
11394        cx: &mut ViewContext<Self>,
11395    ) -> Vec<CustomBlockId> {
11396        let blocks = self
11397            .display_map
11398            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11399        if let Some(autoscroll) = autoscroll {
11400            self.request_autoscroll(autoscroll, cx);
11401        }
11402        cx.notify();
11403        blocks
11404    }
11405
11406    pub fn resize_blocks(
11407        &mut self,
11408        heights: HashMap<CustomBlockId, u32>,
11409        autoscroll: Option<Autoscroll>,
11410        cx: &mut ViewContext<Self>,
11411    ) {
11412        self.display_map
11413            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11414        if let Some(autoscroll) = autoscroll {
11415            self.request_autoscroll(autoscroll, cx);
11416        }
11417        cx.notify();
11418    }
11419
11420    pub fn replace_blocks(
11421        &mut self,
11422        renderers: HashMap<CustomBlockId, RenderBlock>,
11423        autoscroll: Option<Autoscroll>,
11424        cx: &mut ViewContext<Self>,
11425    ) {
11426        self.display_map
11427            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11428        if let Some(autoscroll) = autoscroll {
11429            self.request_autoscroll(autoscroll, cx);
11430        }
11431        cx.notify();
11432    }
11433
11434    pub fn remove_blocks(
11435        &mut self,
11436        block_ids: HashSet<CustomBlockId>,
11437        autoscroll: Option<Autoscroll>,
11438        cx: &mut ViewContext<Self>,
11439    ) {
11440        self.display_map.update(cx, |display_map, cx| {
11441            display_map.remove_blocks(block_ids, cx)
11442        });
11443        if let Some(autoscroll) = autoscroll {
11444            self.request_autoscroll(autoscroll, cx);
11445        }
11446        cx.notify();
11447    }
11448
11449    pub fn row_for_block(
11450        &self,
11451        block_id: CustomBlockId,
11452        cx: &mut ViewContext<Self>,
11453    ) -> Option<DisplayRow> {
11454        self.display_map
11455            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11456    }
11457
11458    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11459        self.focused_block = Some(focused_block);
11460    }
11461
11462    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11463        self.focused_block.take()
11464    }
11465
11466    pub fn insert_creases(
11467        &mut self,
11468        creases: impl IntoIterator<Item = Crease<Anchor>>,
11469        cx: &mut ViewContext<Self>,
11470    ) -> Vec<CreaseId> {
11471        self.display_map
11472            .update(cx, |map, cx| map.insert_creases(creases, cx))
11473    }
11474
11475    pub fn remove_creases(
11476        &mut self,
11477        ids: impl IntoIterator<Item = CreaseId>,
11478        cx: &mut ViewContext<Self>,
11479    ) {
11480        self.display_map
11481            .update(cx, |map, cx| map.remove_creases(ids, cx));
11482    }
11483
11484    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11485        self.display_map
11486            .update(cx, |map, cx| map.snapshot(cx))
11487            .longest_row()
11488    }
11489
11490    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11491        self.display_map
11492            .update(cx, |map, cx| map.snapshot(cx))
11493            .max_point()
11494    }
11495
11496    pub fn text(&self, cx: &AppContext) -> String {
11497        self.buffer.read(cx).read(cx).text()
11498    }
11499
11500    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11501        let text = self.text(cx);
11502        let text = text.trim();
11503
11504        if text.is_empty() {
11505            return None;
11506        }
11507
11508        Some(text.to_string())
11509    }
11510
11511    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11512        self.transact(cx, |this, cx| {
11513            this.buffer
11514                .read(cx)
11515                .as_singleton()
11516                .expect("you can only call set_text on editors for singleton buffers")
11517                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11518        });
11519    }
11520
11521    pub fn display_text(&self, cx: &mut AppContext) -> String {
11522        self.display_map
11523            .update(cx, |map, cx| map.snapshot(cx))
11524            .text()
11525    }
11526
11527    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11528        let mut wrap_guides = smallvec::smallvec![];
11529
11530        if self.show_wrap_guides == Some(false) {
11531            return wrap_guides;
11532        }
11533
11534        let settings = self.buffer.read(cx).settings_at(0, cx);
11535        if settings.show_wrap_guides {
11536            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11537                wrap_guides.push((soft_wrap as usize, true));
11538            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11539                wrap_guides.push((soft_wrap as usize, true));
11540            }
11541            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11542        }
11543
11544        wrap_guides
11545    }
11546
11547    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11548        let settings = self.buffer.read(cx).settings_at(0, cx);
11549        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11550        match mode {
11551            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11552                SoftWrap::None
11553            }
11554            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11555            language_settings::SoftWrap::PreferredLineLength => {
11556                SoftWrap::Column(settings.preferred_line_length)
11557            }
11558            language_settings::SoftWrap::Bounded => {
11559                SoftWrap::Bounded(settings.preferred_line_length)
11560            }
11561        }
11562    }
11563
11564    pub fn set_soft_wrap_mode(
11565        &mut self,
11566        mode: language_settings::SoftWrap,
11567        cx: &mut ViewContext<Self>,
11568    ) {
11569        self.soft_wrap_mode_override = Some(mode);
11570        cx.notify();
11571    }
11572
11573    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11574        self.text_style_refinement = Some(style);
11575    }
11576
11577    /// called by the Element so we know what style we were most recently rendered with.
11578    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11579        let rem_size = cx.rem_size();
11580        self.display_map.update(cx, |map, cx| {
11581            map.set_font(
11582                style.text.font(),
11583                style.text.font_size.to_pixels(rem_size),
11584                cx,
11585            )
11586        });
11587        self.style = Some(style);
11588    }
11589
11590    pub fn style(&self) -> Option<&EditorStyle> {
11591        self.style.as_ref()
11592    }
11593
11594    // Called by the element. This method is not designed to be called outside of the editor
11595    // element's layout code because it does not notify when rewrapping is computed synchronously.
11596    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11597        self.display_map
11598            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11599    }
11600
11601    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11602        if self.soft_wrap_mode_override.is_some() {
11603            self.soft_wrap_mode_override.take();
11604        } else {
11605            let soft_wrap = match self.soft_wrap_mode(cx) {
11606                SoftWrap::GitDiff => return,
11607                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11608                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11609                    language_settings::SoftWrap::None
11610                }
11611            };
11612            self.soft_wrap_mode_override = Some(soft_wrap);
11613        }
11614        cx.notify();
11615    }
11616
11617    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11618        let Some(workspace) = self.workspace() else {
11619            return;
11620        };
11621        let fs = workspace.read(cx).app_state().fs.clone();
11622        let current_show = TabBarSettings::get_global(cx).show;
11623        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11624            setting.show = Some(!current_show);
11625        });
11626    }
11627
11628    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11629        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11630            self.buffer
11631                .read(cx)
11632                .settings_at(0, cx)
11633                .indent_guides
11634                .enabled
11635        });
11636        self.show_indent_guides = Some(!currently_enabled);
11637        cx.notify();
11638    }
11639
11640    fn should_show_indent_guides(&self) -> Option<bool> {
11641        self.show_indent_guides
11642    }
11643
11644    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11645        let mut editor_settings = EditorSettings::get_global(cx).clone();
11646        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11647        EditorSettings::override_global(editor_settings, cx);
11648    }
11649
11650    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11651        self.use_relative_line_numbers
11652            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11653    }
11654
11655    pub fn toggle_relative_line_numbers(
11656        &mut self,
11657        _: &ToggleRelativeLineNumbers,
11658        cx: &mut ViewContext<Self>,
11659    ) {
11660        let is_relative = self.should_use_relative_line_numbers(cx);
11661        self.set_relative_line_number(Some(!is_relative), cx)
11662    }
11663
11664    pub fn set_relative_line_number(
11665        &mut self,
11666        is_relative: Option<bool>,
11667        cx: &mut ViewContext<Self>,
11668    ) {
11669        self.use_relative_line_numbers = is_relative;
11670        cx.notify();
11671    }
11672
11673    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11674        self.show_gutter = show_gutter;
11675        cx.notify();
11676    }
11677
11678    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11679        self.show_line_numbers = Some(show_line_numbers);
11680        cx.notify();
11681    }
11682
11683    pub fn set_show_git_diff_gutter(
11684        &mut self,
11685        show_git_diff_gutter: bool,
11686        cx: &mut ViewContext<Self>,
11687    ) {
11688        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11689        cx.notify();
11690    }
11691
11692    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11693        self.show_code_actions = Some(show_code_actions);
11694        cx.notify();
11695    }
11696
11697    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11698        self.show_runnables = Some(show_runnables);
11699        cx.notify();
11700    }
11701
11702    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11703        if self.display_map.read(cx).masked != masked {
11704            self.display_map.update(cx, |map, _| map.masked = masked);
11705        }
11706        cx.notify()
11707    }
11708
11709    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11710        self.show_wrap_guides = Some(show_wrap_guides);
11711        cx.notify();
11712    }
11713
11714    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11715        self.show_indent_guides = Some(show_indent_guides);
11716        cx.notify();
11717    }
11718
11719    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11720        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11721            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11722                if let Some(dir) = file.abs_path(cx).parent() {
11723                    return Some(dir.to_owned());
11724                }
11725            }
11726
11727            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11728                return Some(project_path.path.to_path_buf());
11729            }
11730        }
11731
11732        None
11733    }
11734
11735    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11736        self.active_excerpt(cx)?
11737            .1
11738            .read(cx)
11739            .file()
11740            .and_then(|f| f.as_local())
11741    }
11742
11743    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11744        if let Some(target) = self.target_file(cx) {
11745            cx.reveal_path(&target.abs_path(cx));
11746        }
11747    }
11748
11749    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11750        if let Some(file) = self.target_file(cx) {
11751            if let Some(path) = file.abs_path(cx).to_str() {
11752                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11753            }
11754        }
11755    }
11756
11757    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11758        if let Some(file) = self.target_file(cx) {
11759            if let Some(path) = file.path().to_str() {
11760                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11761            }
11762        }
11763    }
11764
11765    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11766        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11767
11768        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11769            self.start_git_blame(true, cx);
11770        }
11771
11772        cx.notify();
11773    }
11774
11775    pub fn toggle_git_blame_inline(
11776        &mut self,
11777        _: &ToggleGitBlameInline,
11778        cx: &mut ViewContext<Self>,
11779    ) {
11780        self.toggle_git_blame_inline_internal(true, cx);
11781        cx.notify();
11782    }
11783
11784    pub fn git_blame_inline_enabled(&self) -> bool {
11785        self.git_blame_inline_enabled
11786    }
11787
11788    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11789        self.show_selection_menu = self
11790            .show_selection_menu
11791            .map(|show_selections_menu| !show_selections_menu)
11792            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11793
11794        cx.notify();
11795    }
11796
11797    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11798        self.show_selection_menu
11799            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11800    }
11801
11802    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11803        if let Some(project) = self.project.as_ref() {
11804            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11805                return;
11806            };
11807
11808            if buffer.read(cx).file().is_none() {
11809                return;
11810            }
11811
11812            let focused = self.focus_handle(cx).contains_focused(cx);
11813
11814            let project = project.clone();
11815            let blame =
11816                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11817            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11818            self.blame = Some(blame);
11819        }
11820    }
11821
11822    fn toggle_git_blame_inline_internal(
11823        &mut self,
11824        user_triggered: bool,
11825        cx: &mut ViewContext<Self>,
11826    ) {
11827        if self.git_blame_inline_enabled {
11828            self.git_blame_inline_enabled = false;
11829            self.show_git_blame_inline = false;
11830            self.show_git_blame_inline_delay_task.take();
11831        } else {
11832            self.git_blame_inline_enabled = true;
11833            self.start_git_blame_inline(user_triggered, cx);
11834        }
11835
11836        cx.notify();
11837    }
11838
11839    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11840        self.start_git_blame(user_triggered, cx);
11841
11842        if ProjectSettings::get_global(cx)
11843            .git
11844            .inline_blame_delay()
11845            .is_some()
11846        {
11847            self.start_inline_blame_timer(cx);
11848        } else {
11849            self.show_git_blame_inline = true
11850        }
11851    }
11852
11853    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11854        self.blame.as_ref()
11855    }
11856
11857    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11858        self.show_git_blame_gutter && self.has_blame_entries(cx)
11859    }
11860
11861    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11862        self.show_git_blame_inline
11863            && self.focus_handle.is_focused(cx)
11864            && !self.newest_selection_head_on_empty_line(cx)
11865            && self.has_blame_entries(cx)
11866    }
11867
11868    pub fn render_active_line_trailer(
11869        &mut self,
11870        style: &EditorStyle,
11871        cx: &mut WindowContext,
11872    ) -> Option<AnyElement> {
11873        if !self.newest_selection_head_on_empty_line(cx) || self.has_active_inline_completion(cx) {
11874            return None;
11875        }
11876
11877        let focus_handle = self.focus_handle.clone();
11878        self.active_line_trailer_provider
11879            .as_mut()?
11880            .render_active_line_trailer(style, &focus_handle, cx)
11881    }
11882
11883    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11884        self.blame()
11885            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11886    }
11887
11888    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11889        let cursor_anchor = self.selections.newest_anchor().head();
11890
11891        let snapshot = self.buffer.read(cx).snapshot(cx);
11892        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11893
11894        snapshot.line_len(buffer_row) == 0
11895    }
11896
11897    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11898        let buffer_and_selection = maybe!({
11899            let selection = self.selections.newest::<Point>(cx);
11900            let selection_range = selection.range();
11901
11902            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11903                (buffer, selection_range.start.row..selection_range.end.row)
11904            } else {
11905                let buffer_ranges = self
11906                    .buffer()
11907                    .read(cx)
11908                    .range_to_buffer_ranges(selection_range, cx);
11909
11910                let (buffer, range, _) = if selection.reversed {
11911                    buffer_ranges.first()
11912                } else {
11913                    buffer_ranges.last()
11914                }?;
11915
11916                let snapshot = buffer.read(cx).snapshot();
11917                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11918                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11919                (buffer.clone(), selection)
11920            };
11921
11922            Some((buffer, selection))
11923        });
11924
11925        let Some((buffer, selection)) = buffer_and_selection else {
11926            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11927        };
11928
11929        let Some(project) = self.project.as_ref() else {
11930            return Task::ready(Err(anyhow!("editor does not have project")));
11931        };
11932
11933        project.update(cx, |project, cx| {
11934            project.get_permalink_to_line(&buffer, selection, cx)
11935        })
11936    }
11937
11938    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11939        let permalink_task = self.get_permalink_to_line(cx);
11940        let workspace = self.workspace();
11941
11942        cx.spawn(|_, mut cx| async move {
11943            match permalink_task.await {
11944                Ok(permalink) => {
11945                    cx.update(|cx| {
11946                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11947                    })
11948                    .ok();
11949                }
11950                Err(err) => {
11951                    let message = format!("Failed to copy permalink: {err}");
11952
11953                    Err::<(), anyhow::Error>(err).log_err();
11954
11955                    if let Some(workspace) = workspace {
11956                        workspace
11957                            .update(&mut cx, |workspace, cx| {
11958                                struct CopyPermalinkToLine;
11959
11960                                workspace.show_toast(
11961                                    Toast::new(
11962                                        NotificationId::unique::<CopyPermalinkToLine>(),
11963                                        message,
11964                                    ),
11965                                    cx,
11966                                )
11967                            })
11968                            .ok();
11969                    }
11970                }
11971            }
11972        })
11973        .detach();
11974    }
11975
11976    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11977        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11978        if let Some(file) = self.target_file(cx) {
11979            if let Some(path) = file.path().to_str() {
11980                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11981            }
11982        }
11983    }
11984
11985    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11986        let permalink_task = self.get_permalink_to_line(cx);
11987        let workspace = self.workspace();
11988
11989        cx.spawn(|_, mut cx| async move {
11990            match permalink_task.await {
11991                Ok(permalink) => {
11992                    cx.update(|cx| {
11993                        cx.open_url(permalink.as_ref());
11994                    })
11995                    .ok();
11996                }
11997                Err(err) => {
11998                    let message = format!("Failed to open permalink: {err}");
11999
12000                    Err::<(), anyhow::Error>(err).log_err();
12001
12002                    if let Some(workspace) = workspace {
12003                        workspace
12004                            .update(&mut cx, |workspace, cx| {
12005                                struct OpenPermalinkToLine;
12006
12007                                workspace.show_toast(
12008                                    Toast::new(
12009                                        NotificationId::unique::<OpenPermalinkToLine>(),
12010                                        message,
12011                                    ),
12012                                    cx,
12013                                )
12014                            })
12015                            .ok();
12016                    }
12017                }
12018            }
12019        })
12020        .detach();
12021    }
12022
12023    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12024    /// last highlight added will be used.
12025    ///
12026    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12027    pub fn highlight_rows<T: 'static>(
12028        &mut self,
12029        range: Range<Anchor>,
12030        color: Hsla,
12031        should_autoscroll: bool,
12032        cx: &mut ViewContext<Self>,
12033    ) {
12034        let snapshot = self.buffer().read(cx).snapshot(cx);
12035        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12036        let ix = row_highlights.binary_search_by(|highlight| {
12037            Ordering::Equal
12038                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12039                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12040        });
12041
12042        if let Err(mut ix) = ix {
12043            let index = post_inc(&mut self.highlight_order);
12044
12045            // If this range intersects with the preceding highlight, then merge it with
12046            // the preceding highlight. Otherwise insert a new highlight.
12047            let mut merged = false;
12048            if ix > 0 {
12049                let prev_highlight = &mut row_highlights[ix - 1];
12050                if prev_highlight
12051                    .range
12052                    .end
12053                    .cmp(&range.start, &snapshot)
12054                    .is_ge()
12055                {
12056                    ix -= 1;
12057                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12058                        prev_highlight.range.end = range.end;
12059                    }
12060                    merged = true;
12061                    prev_highlight.index = index;
12062                    prev_highlight.color = color;
12063                    prev_highlight.should_autoscroll = should_autoscroll;
12064                }
12065            }
12066
12067            if !merged {
12068                row_highlights.insert(
12069                    ix,
12070                    RowHighlight {
12071                        range: range.clone(),
12072                        index,
12073                        color,
12074                        should_autoscroll,
12075                    },
12076                );
12077            }
12078
12079            // If any of the following highlights intersect with this one, merge them.
12080            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12081                let highlight = &row_highlights[ix];
12082                if next_highlight
12083                    .range
12084                    .start
12085                    .cmp(&highlight.range.end, &snapshot)
12086                    .is_le()
12087                {
12088                    if next_highlight
12089                        .range
12090                        .end
12091                        .cmp(&highlight.range.end, &snapshot)
12092                        .is_gt()
12093                    {
12094                        row_highlights[ix].range.end = next_highlight.range.end;
12095                    }
12096                    row_highlights.remove(ix + 1);
12097                } else {
12098                    break;
12099                }
12100            }
12101        }
12102    }
12103
12104    /// Remove any highlighted row ranges of the given type that intersect the
12105    /// given ranges.
12106    pub fn remove_highlighted_rows<T: 'static>(
12107        &mut self,
12108        ranges_to_remove: Vec<Range<Anchor>>,
12109        cx: &mut ViewContext<Self>,
12110    ) {
12111        let snapshot = self.buffer().read(cx).snapshot(cx);
12112        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12113        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12114        row_highlights.retain(|highlight| {
12115            while let Some(range_to_remove) = ranges_to_remove.peek() {
12116                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12117                    Ordering::Less | Ordering::Equal => {
12118                        ranges_to_remove.next();
12119                    }
12120                    Ordering::Greater => {
12121                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12122                            Ordering::Less | Ordering::Equal => {
12123                                return false;
12124                            }
12125                            Ordering::Greater => break,
12126                        }
12127                    }
12128                }
12129            }
12130
12131            true
12132        })
12133    }
12134
12135    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12136    pub fn clear_row_highlights<T: 'static>(&mut self) {
12137        self.highlighted_rows.remove(&TypeId::of::<T>());
12138    }
12139
12140    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12141    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12142        self.highlighted_rows
12143            .get(&TypeId::of::<T>())
12144            .map_or(&[] as &[_], |vec| vec.as_slice())
12145            .iter()
12146            .map(|highlight| (highlight.range.clone(), highlight.color))
12147    }
12148
12149    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12150    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12151    /// Allows to ignore certain kinds of highlights.
12152    pub fn highlighted_display_rows(
12153        &mut self,
12154        cx: &mut WindowContext,
12155    ) -> BTreeMap<DisplayRow, Hsla> {
12156        let snapshot = self.snapshot(cx);
12157        let mut used_highlight_orders = HashMap::default();
12158        self.highlighted_rows
12159            .iter()
12160            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12161            .fold(
12162                BTreeMap::<DisplayRow, Hsla>::new(),
12163                |mut unique_rows, highlight| {
12164                    let start = highlight.range.start.to_display_point(&snapshot);
12165                    let end = highlight.range.end.to_display_point(&snapshot);
12166                    let start_row = start.row().0;
12167                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12168                        && end.column() == 0
12169                    {
12170                        end.row().0.saturating_sub(1)
12171                    } else {
12172                        end.row().0
12173                    };
12174                    for row in start_row..=end_row {
12175                        let used_index =
12176                            used_highlight_orders.entry(row).or_insert(highlight.index);
12177                        if highlight.index >= *used_index {
12178                            *used_index = highlight.index;
12179                            unique_rows.insert(DisplayRow(row), highlight.color);
12180                        }
12181                    }
12182                    unique_rows
12183                },
12184            )
12185    }
12186
12187    pub fn highlighted_display_row_for_autoscroll(
12188        &self,
12189        snapshot: &DisplaySnapshot,
12190    ) -> Option<DisplayRow> {
12191        self.highlighted_rows
12192            .values()
12193            .flat_map(|highlighted_rows| highlighted_rows.iter())
12194            .filter_map(|highlight| {
12195                if highlight.should_autoscroll {
12196                    Some(highlight.range.start.to_display_point(snapshot).row())
12197                } else {
12198                    None
12199                }
12200            })
12201            .min()
12202    }
12203
12204    pub fn set_search_within_ranges(
12205        &mut self,
12206        ranges: &[Range<Anchor>],
12207        cx: &mut ViewContext<Self>,
12208    ) {
12209        self.highlight_background::<SearchWithinRange>(
12210            ranges,
12211            |colors| colors.editor_document_highlight_read_background,
12212            cx,
12213        )
12214    }
12215
12216    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12217        self.breadcrumb_header = Some(new_header);
12218    }
12219
12220    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12221        self.clear_background_highlights::<SearchWithinRange>(cx);
12222    }
12223
12224    pub fn highlight_background<T: 'static>(
12225        &mut self,
12226        ranges: &[Range<Anchor>],
12227        color_fetcher: fn(&ThemeColors) -> Hsla,
12228        cx: &mut ViewContext<Self>,
12229    ) {
12230        self.background_highlights
12231            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12232        self.scrollbar_marker_state.dirty = true;
12233        cx.notify();
12234    }
12235
12236    pub fn clear_background_highlights<T: 'static>(
12237        &mut self,
12238        cx: &mut ViewContext<Self>,
12239    ) -> Option<BackgroundHighlight> {
12240        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12241        if !text_highlights.1.is_empty() {
12242            self.scrollbar_marker_state.dirty = true;
12243            cx.notify();
12244        }
12245        Some(text_highlights)
12246    }
12247
12248    pub fn highlight_gutter<T: 'static>(
12249        &mut self,
12250        ranges: &[Range<Anchor>],
12251        color_fetcher: fn(&AppContext) -> Hsla,
12252        cx: &mut ViewContext<Self>,
12253    ) {
12254        self.gutter_highlights
12255            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12256        cx.notify();
12257    }
12258
12259    pub fn clear_gutter_highlights<T: 'static>(
12260        &mut self,
12261        cx: &mut ViewContext<Self>,
12262    ) -> Option<GutterHighlight> {
12263        cx.notify();
12264        self.gutter_highlights.remove(&TypeId::of::<T>())
12265    }
12266
12267    #[cfg(feature = "test-support")]
12268    pub fn all_text_background_highlights(
12269        &mut self,
12270        cx: &mut ViewContext<Self>,
12271    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12272        let snapshot = self.snapshot(cx);
12273        let buffer = &snapshot.buffer_snapshot;
12274        let start = buffer.anchor_before(0);
12275        let end = buffer.anchor_after(buffer.len());
12276        let theme = cx.theme().colors();
12277        self.background_highlights_in_range(start..end, &snapshot, theme)
12278    }
12279
12280    #[cfg(feature = "test-support")]
12281    pub fn search_background_highlights(
12282        &mut self,
12283        cx: &mut ViewContext<Self>,
12284    ) -> Vec<Range<Point>> {
12285        let snapshot = self.buffer().read(cx).snapshot(cx);
12286
12287        let highlights = self
12288            .background_highlights
12289            .get(&TypeId::of::<items::BufferSearchHighlights>());
12290
12291        if let Some((_color, ranges)) = highlights {
12292            ranges
12293                .iter()
12294                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12295                .collect_vec()
12296        } else {
12297            vec![]
12298        }
12299    }
12300
12301    fn document_highlights_for_position<'a>(
12302        &'a self,
12303        position: Anchor,
12304        buffer: &'a MultiBufferSnapshot,
12305    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12306        let read_highlights = self
12307            .background_highlights
12308            .get(&TypeId::of::<DocumentHighlightRead>())
12309            .map(|h| &h.1);
12310        let write_highlights = self
12311            .background_highlights
12312            .get(&TypeId::of::<DocumentHighlightWrite>())
12313            .map(|h| &h.1);
12314        let left_position = position.bias_left(buffer);
12315        let right_position = position.bias_right(buffer);
12316        read_highlights
12317            .into_iter()
12318            .chain(write_highlights)
12319            .flat_map(move |ranges| {
12320                let start_ix = match ranges.binary_search_by(|probe| {
12321                    let cmp = probe.end.cmp(&left_position, buffer);
12322                    if cmp.is_ge() {
12323                        Ordering::Greater
12324                    } else {
12325                        Ordering::Less
12326                    }
12327                }) {
12328                    Ok(i) | Err(i) => i,
12329                };
12330
12331                ranges[start_ix..]
12332                    .iter()
12333                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12334            })
12335    }
12336
12337    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12338        self.background_highlights
12339            .get(&TypeId::of::<T>())
12340            .map_or(false, |(_, highlights)| !highlights.is_empty())
12341    }
12342
12343    pub fn background_highlights_in_range(
12344        &self,
12345        search_range: Range<Anchor>,
12346        display_snapshot: &DisplaySnapshot,
12347        theme: &ThemeColors,
12348    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12349        let mut results = Vec::new();
12350        for (color_fetcher, ranges) in self.background_highlights.values() {
12351            let color = color_fetcher(theme);
12352            let start_ix = match ranges.binary_search_by(|probe| {
12353                let cmp = probe
12354                    .end
12355                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12356                if cmp.is_gt() {
12357                    Ordering::Greater
12358                } else {
12359                    Ordering::Less
12360                }
12361            }) {
12362                Ok(i) | Err(i) => i,
12363            };
12364            for range in &ranges[start_ix..] {
12365                if range
12366                    .start
12367                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12368                    .is_ge()
12369                {
12370                    break;
12371                }
12372
12373                let start = range.start.to_display_point(display_snapshot);
12374                let end = range.end.to_display_point(display_snapshot);
12375                results.push((start..end, color))
12376            }
12377        }
12378        results
12379    }
12380
12381    pub fn background_highlight_row_ranges<T: 'static>(
12382        &self,
12383        search_range: Range<Anchor>,
12384        display_snapshot: &DisplaySnapshot,
12385        count: usize,
12386    ) -> Vec<RangeInclusive<DisplayPoint>> {
12387        let mut results = Vec::new();
12388        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12389            return vec![];
12390        };
12391
12392        let start_ix = match ranges.binary_search_by(|probe| {
12393            let cmp = probe
12394                .end
12395                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12396            if cmp.is_gt() {
12397                Ordering::Greater
12398            } else {
12399                Ordering::Less
12400            }
12401        }) {
12402            Ok(i) | Err(i) => i,
12403        };
12404        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12405            if let (Some(start_display), Some(end_display)) = (start, end) {
12406                results.push(
12407                    start_display.to_display_point(display_snapshot)
12408                        ..=end_display.to_display_point(display_snapshot),
12409                );
12410            }
12411        };
12412        let mut start_row: Option<Point> = None;
12413        let mut end_row: Option<Point> = None;
12414        if ranges.len() > count {
12415            return Vec::new();
12416        }
12417        for range in &ranges[start_ix..] {
12418            if range
12419                .start
12420                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12421                .is_ge()
12422            {
12423                break;
12424            }
12425            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12426            if let Some(current_row) = &end_row {
12427                if end.row == current_row.row {
12428                    continue;
12429                }
12430            }
12431            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12432            if start_row.is_none() {
12433                assert_eq!(end_row, None);
12434                start_row = Some(start);
12435                end_row = Some(end);
12436                continue;
12437            }
12438            if let Some(current_end) = end_row.as_mut() {
12439                if start.row > current_end.row + 1 {
12440                    push_region(start_row, end_row);
12441                    start_row = Some(start);
12442                    end_row = Some(end);
12443                } else {
12444                    // Merge two hunks.
12445                    *current_end = end;
12446                }
12447            } else {
12448                unreachable!();
12449            }
12450        }
12451        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12452        push_region(start_row, end_row);
12453        results
12454    }
12455
12456    pub fn gutter_highlights_in_range(
12457        &self,
12458        search_range: Range<Anchor>,
12459        display_snapshot: &DisplaySnapshot,
12460        cx: &AppContext,
12461    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12462        let mut results = Vec::new();
12463        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12464            let color = color_fetcher(cx);
12465            let start_ix = match ranges.binary_search_by(|probe| {
12466                let cmp = probe
12467                    .end
12468                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12469                if cmp.is_gt() {
12470                    Ordering::Greater
12471                } else {
12472                    Ordering::Less
12473                }
12474            }) {
12475                Ok(i) | Err(i) => i,
12476            };
12477            for range in &ranges[start_ix..] {
12478                if range
12479                    .start
12480                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12481                    .is_ge()
12482                {
12483                    break;
12484                }
12485
12486                let start = range.start.to_display_point(display_snapshot);
12487                let end = range.end.to_display_point(display_snapshot);
12488                results.push((start..end, color))
12489            }
12490        }
12491        results
12492    }
12493
12494    /// Get the text ranges corresponding to the redaction query
12495    pub fn redacted_ranges(
12496        &self,
12497        search_range: Range<Anchor>,
12498        display_snapshot: &DisplaySnapshot,
12499        cx: &WindowContext,
12500    ) -> Vec<Range<DisplayPoint>> {
12501        display_snapshot
12502            .buffer_snapshot
12503            .redacted_ranges(search_range, |file| {
12504                if let Some(file) = file {
12505                    file.is_private()
12506                        && EditorSettings::get(
12507                            Some(SettingsLocation {
12508                                worktree_id: file.worktree_id(cx),
12509                                path: file.path().as_ref(),
12510                            }),
12511                            cx,
12512                        )
12513                        .redact_private_values
12514                } else {
12515                    false
12516                }
12517            })
12518            .map(|range| {
12519                range.start.to_display_point(display_snapshot)
12520                    ..range.end.to_display_point(display_snapshot)
12521            })
12522            .collect()
12523    }
12524
12525    pub fn highlight_text<T: 'static>(
12526        &mut self,
12527        ranges: Vec<Range<Anchor>>,
12528        style: HighlightStyle,
12529        cx: &mut ViewContext<Self>,
12530    ) {
12531        self.display_map.update(cx, |map, _| {
12532            map.highlight_text(TypeId::of::<T>(), ranges, style)
12533        });
12534        cx.notify();
12535    }
12536
12537    pub(crate) fn highlight_inlays<T: 'static>(
12538        &mut self,
12539        highlights: Vec<InlayHighlight>,
12540        style: HighlightStyle,
12541        cx: &mut ViewContext<Self>,
12542    ) {
12543        self.display_map.update(cx, |map, _| {
12544            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12545        });
12546        cx.notify();
12547    }
12548
12549    pub fn text_highlights<'a, T: 'static>(
12550        &'a self,
12551        cx: &'a AppContext,
12552    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12553        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12554    }
12555
12556    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12557        let cleared = self
12558            .display_map
12559            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12560        if cleared {
12561            cx.notify();
12562        }
12563    }
12564
12565    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12566        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12567            && self.focus_handle.is_focused(cx)
12568    }
12569
12570    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12571        self.show_cursor_when_unfocused = is_enabled;
12572        cx.notify();
12573    }
12574
12575    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12576        cx.notify();
12577    }
12578
12579    fn on_buffer_event(
12580        &mut self,
12581        multibuffer: Model<MultiBuffer>,
12582        event: &multi_buffer::Event,
12583        cx: &mut ViewContext<Self>,
12584    ) {
12585        match event {
12586            multi_buffer::Event::Edited {
12587                singleton_buffer_edited,
12588            } => {
12589                self.scrollbar_marker_state.dirty = true;
12590                self.active_indent_guides_state.dirty = true;
12591                self.refresh_active_diagnostics(cx);
12592                self.refresh_code_actions(cx);
12593                if self.has_active_inline_completion(cx) {
12594                    self.update_visible_inline_completion(cx);
12595                }
12596                cx.emit(EditorEvent::BufferEdited);
12597                cx.emit(SearchEvent::MatchesInvalidated);
12598                if *singleton_buffer_edited {
12599                    if let Some(project) = &self.project {
12600                        let project = project.read(cx);
12601                        #[allow(clippy::mutable_key_type)]
12602                        let languages_affected = multibuffer
12603                            .read(cx)
12604                            .all_buffers()
12605                            .into_iter()
12606                            .filter_map(|buffer| {
12607                                let buffer = buffer.read(cx);
12608                                let language = buffer.language()?;
12609                                if project.is_local()
12610                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12611                                {
12612                                    None
12613                                } else {
12614                                    Some(language)
12615                                }
12616                            })
12617                            .cloned()
12618                            .collect::<HashSet<_>>();
12619                        if !languages_affected.is_empty() {
12620                            self.refresh_inlay_hints(
12621                                InlayHintRefreshReason::BufferEdited(languages_affected),
12622                                cx,
12623                            );
12624                        }
12625                    }
12626                }
12627
12628                let Some(project) = &self.project else { return };
12629                let (telemetry, is_via_ssh) = {
12630                    let project = project.read(cx);
12631                    let telemetry = project.client().telemetry().clone();
12632                    let is_via_ssh = project.is_via_ssh();
12633                    (telemetry, is_via_ssh)
12634                };
12635                refresh_linked_ranges(self, cx);
12636                telemetry.log_edit_event("editor", is_via_ssh);
12637            }
12638            multi_buffer::Event::ExcerptsAdded {
12639                buffer,
12640                predecessor,
12641                excerpts,
12642            } => {
12643                self.tasks_update_task = Some(self.refresh_runnables(cx));
12644                cx.emit(EditorEvent::ExcerptsAdded {
12645                    buffer: buffer.clone(),
12646                    predecessor: *predecessor,
12647                    excerpts: excerpts.clone(),
12648                });
12649                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12650            }
12651            multi_buffer::Event::ExcerptsRemoved { ids } => {
12652                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12653                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12654            }
12655            multi_buffer::Event::ExcerptsEdited { ids } => {
12656                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12657            }
12658            multi_buffer::Event::ExcerptsExpanded { ids } => {
12659                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12660            }
12661            multi_buffer::Event::Reparsed(buffer_id) => {
12662                self.tasks_update_task = Some(self.refresh_runnables(cx));
12663
12664                cx.emit(EditorEvent::Reparsed(*buffer_id));
12665            }
12666            multi_buffer::Event::LanguageChanged(buffer_id) => {
12667                linked_editing_ranges::refresh_linked_ranges(self, cx);
12668                cx.emit(EditorEvent::Reparsed(*buffer_id));
12669                cx.notify();
12670            }
12671            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12672            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12673            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12674                cx.emit(EditorEvent::TitleChanged)
12675            }
12676            multi_buffer::Event::DiffBaseChanged => {
12677                self.scrollbar_marker_state.dirty = true;
12678                cx.emit(EditorEvent::DiffBaseChanged);
12679                cx.notify();
12680            }
12681            multi_buffer::Event::DiffUpdated { buffer } => {
12682                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12683                cx.notify();
12684            }
12685            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12686            multi_buffer::Event::DiagnosticsUpdated => {
12687                self.refresh_active_diagnostics(cx);
12688                self.scrollbar_marker_state.dirty = true;
12689                cx.notify();
12690            }
12691            _ => {}
12692        };
12693    }
12694
12695    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12696        cx.notify();
12697    }
12698
12699    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12700        self.tasks_update_task = Some(self.refresh_runnables(cx));
12701        self.refresh_inline_completion(true, false, cx);
12702        self.refresh_inlay_hints(
12703            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12704                self.selections.newest_anchor().head(),
12705                &self.buffer.read(cx).snapshot(cx),
12706                cx,
12707            )),
12708            cx,
12709        );
12710
12711        let old_cursor_shape = self.cursor_shape;
12712
12713        {
12714            let editor_settings = EditorSettings::get_global(cx);
12715            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12716            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12717            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12718        }
12719
12720        if old_cursor_shape != self.cursor_shape {
12721            cx.emit(EditorEvent::CursorShapeChanged);
12722        }
12723
12724        let project_settings = ProjectSettings::get_global(cx);
12725        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12726
12727        if self.mode == EditorMode::Full {
12728            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12729            if self.git_blame_inline_enabled != inline_blame_enabled {
12730                self.toggle_git_blame_inline_internal(false, cx);
12731            }
12732        }
12733
12734        cx.notify();
12735    }
12736
12737    pub fn set_searchable(&mut self, searchable: bool) {
12738        self.searchable = searchable;
12739    }
12740
12741    pub fn searchable(&self) -> bool {
12742        self.searchable
12743    }
12744
12745    fn open_proposed_changes_editor(
12746        &mut self,
12747        _: &OpenProposedChangesEditor,
12748        cx: &mut ViewContext<Self>,
12749    ) {
12750        let Some(workspace) = self.workspace() else {
12751            cx.propagate();
12752            return;
12753        };
12754
12755        let selections = self.selections.all::<usize>(cx);
12756        let buffer = self.buffer.read(cx);
12757        let mut new_selections_by_buffer = HashMap::default();
12758        for selection in selections {
12759            for (buffer, range, _) in
12760                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12761            {
12762                let mut range = range.to_point(buffer.read(cx));
12763                range.start.column = 0;
12764                range.end.column = buffer.read(cx).line_len(range.end.row);
12765                new_selections_by_buffer
12766                    .entry(buffer)
12767                    .or_insert(Vec::new())
12768                    .push(range)
12769            }
12770        }
12771
12772        let proposed_changes_buffers = new_selections_by_buffer
12773            .into_iter()
12774            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12775            .collect::<Vec<_>>();
12776        let proposed_changes_editor = cx.new_view(|cx| {
12777            ProposedChangesEditor::new(
12778                "Proposed changes",
12779                proposed_changes_buffers,
12780                self.project.clone(),
12781                cx,
12782            )
12783        });
12784
12785        cx.window_context().defer(move |cx| {
12786            workspace.update(cx, |workspace, cx| {
12787                workspace.active_pane().update(cx, |pane, cx| {
12788                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12789                });
12790            });
12791        });
12792    }
12793
12794    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12795        self.open_excerpts_common(None, true, cx)
12796    }
12797
12798    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12799        self.open_excerpts_common(None, false, cx)
12800    }
12801
12802    fn open_excerpts_common(
12803        &mut self,
12804        jump_data: Option<JumpData>,
12805        split: bool,
12806        cx: &mut ViewContext<Self>,
12807    ) {
12808        let Some(workspace) = self.workspace() else {
12809            cx.propagate();
12810            return;
12811        };
12812
12813        if self.buffer.read(cx).is_singleton() {
12814            cx.propagate();
12815            return;
12816        }
12817
12818        let mut new_selections_by_buffer = HashMap::default();
12819        match &jump_data {
12820            Some(jump_data) => {
12821                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12822                if let Some(buffer) = multi_buffer_snapshot
12823                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12824                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12825                {
12826                    let buffer_snapshot = buffer.read(cx).snapshot();
12827                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12828                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12829                    } else {
12830                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12831                    };
12832                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12833                    new_selections_by_buffer.insert(
12834                        buffer,
12835                        (
12836                            vec![jump_to_offset..jump_to_offset],
12837                            Some(jump_data.line_offset_from_top),
12838                        ),
12839                    );
12840                }
12841            }
12842            None => {
12843                let selections = self.selections.all::<usize>(cx);
12844                let buffer = self.buffer.read(cx);
12845                for selection in selections {
12846                    for (mut buffer_handle, mut range, _) in
12847                        buffer.range_to_buffer_ranges(selection.range(), cx)
12848                    {
12849                        // When editing branch buffers, jump to the corresponding location
12850                        // in their base buffer.
12851                        let buffer = buffer_handle.read(cx);
12852                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12853                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12854                            buffer_handle = base_buffer;
12855                        }
12856
12857                        if selection.reversed {
12858                            mem::swap(&mut range.start, &mut range.end);
12859                        }
12860                        new_selections_by_buffer
12861                            .entry(buffer_handle)
12862                            .or_insert((Vec::new(), None))
12863                            .0
12864                            .push(range)
12865                    }
12866                }
12867            }
12868        }
12869
12870        if new_selections_by_buffer.is_empty() {
12871            return;
12872        }
12873
12874        // We defer the pane interaction because we ourselves are a workspace item
12875        // and activating a new item causes the pane to call a method on us reentrantly,
12876        // which panics if we're on the stack.
12877        cx.window_context().defer(move |cx| {
12878            workspace.update(cx, |workspace, cx| {
12879                let pane = if split {
12880                    workspace.adjacent_pane(cx)
12881                } else {
12882                    workspace.active_pane().clone()
12883                };
12884
12885                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12886                    let editor =
12887                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12888                    editor.update(cx, |editor, cx| {
12889                        let autoscroll = match scroll_offset {
12890                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12891                            None => Autoscroll::newest(),
12892                        };
12893                        let nav_history = editor.nav_history.take();
12894                        editor.change_selections(Some(autoscroll), cx, |s| {
12895                            s.select_ranges(ranges);
12896                        });
12897                        editor.nav_history = nav_history;
12898                    });
12899                }
12900            })
12901        });
12902    }
12903
12904    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12905        let snapshot = self.buffer.read(cx).read(cx);
12906        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12907        Some(
12908            ranges
12909                .iter()
12910                .map(move |range| {
12911                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12912                })
12913                .collect(),
12914        )
12915    }
12916
12917    fn selection_replacement_ranges(
12918        &self,
12919        range: Range<OffsetUtf16>,
12920        cx: &mut AppContext,
12921    ) -> Vec<Range<OffsetUtf16>> {
12922        let selections = self.selections.all::<OffsetUtf16>(cx);
12923        let newest_selection = selections
12924            .iter()
12925            .max_by_key(|selection| selection.id)
12926            .unwrap();
12927        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12928        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12929        let snapshot = self.buffer.read(cx).read(cx);
12930        selections
12931            .into_iter()
12932            .map(|mut selection| {
12933                selection.start.0 =
12934                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12935                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12936                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12937                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12938            })
12939            .collect()
12940    }
12941
12942    fn report_editor_event(
12943        &self,
12944        operation: &'static str,
12945        file_extension: Option<String>,
12946        cx: &AppContext,
12947    ) {
12948        if cfg!(any(test, feature = "test-support")) {
12949            return;
12950        }
12951
12952        let Some(project) = &self.project else { return };
12953
12954        // If None, we are in a file without an extension
12955        let file = self
12956            .buffer
12957            .read(cx)
12958            .as_singleton()
12959            .and_then(|b| b.read(cx).file());
12960        let file_extension = file_extension.or(file
12961            .as_ref()
12962            .and_then(|file| Path::new(file.file_name(cx)).extension())
12963            .and_then(|e| e.to_str())
12964            .map(|a| a.to_string()));
12965
12966        let vim_mode = cx
12967            .global::<SettingsStore>()
12968            .raw_user_settings()
12969            .get("vim_mode")
12970            == Some(&serde_json::Value::Bool(true));
12971
12972        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12973            == language::language_settings::InlineCompletionProvider::Copilot;
12974        let copilot_enabled_for_language = self
12975            .buffer
12976            .read(cx)
12977            .settings_at(0, cx)
12978            .show_inline_completions;
12979
12980        let project = project.read(cx);
12981        let telemetry = project.client().telemetry().clone();
12982        telemetry.report_editor_event(
12983            file_extension,
12984            vim_mode,
12985            operation,
12986            copilot_enabled,
12987            copilot_enabled_for_language,
12988            project.is_via_ssh(),
12989        )
12990    }
12991
12992    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12993    /// with each line being an array of {text, highlight} objects.
12994    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12995        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12996            return;
12997        };
12998
12999        #[derive(Serialize)]
13000        struct Chunk<'a> {
13001            text: String,
13002            highlight: Option<&'a str>,
13003        }
13004
13005        let snapshot = buffer.read(cx).snapshot();
13006        let range = self
13007            .selected_text_range(false, cx)
13008            .and_then(|selection| {
13009                if selection.range.is_empty() {
13010                    None
13011                } else {
13012                    Some(selection.range)
13013                }
13014            })
13015            .unwrap_or_else(|| 0..snapshot.len());
13016
13017        let chunks = snapshot.chunks(range, true);
13018        let mut lines = Vec::new();
13019        let mut line: VecDeque<Chunk> = VecDeque::new();
13020
13021        let Some(style) = self.style.as_ref() else {
13022            return;
13023        };
13024
13025        for chunk in chunks {
13026            let highlight = chunk
13027                .syntax_highlight_id
13028                .and_then(|id| id.name(&style.syntax));
13029            let mut chunk_lines = chunk.text.split('\n').peekable();
13030            while let Some(text) = chunk_lines.next() {
13031                let mut merged_with_last_token = false;
13032                if let Some(last_token) = line.back_mut() {
13033                    if last_token.highlight == highlight {
13034                        last_token.text.push_str(text);
13035                        merged_with_last_token = true;
13036                    }
13037                }
13038
13039                if !merged_with_last_token {
13040                    line.push_back(Chunk {
13041                        text: text.into(),
13042                        highlight,
13043                    });
13044                }
13045
13046                if chunk_lines.peek().is_some() {
13047                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13048                        line.pop_front();
13049                    }
13050                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13051                        line.pop_back();
13052                    }
13053
13054                    lines.push(mem::take(&mut line));
13055                }
13056            }
13057        }
13058
13059        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13060            return;
13061        };
13062        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13063    }
13064
13065    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13066        &self.inlay_hint_cache
13067    }
13068
13069    pub fn replay_insert_event(
13070        &mut self,
13071        text: &str,
13072        relative_utf16_range: Option<Range<isize>>,
13073        cx: &mut ViewContext<Self>,
13074    ) {
13075        if !self.input_enabled {
13076            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13077            return;
13078        }
13079        if let Some(relative_utf16_range) = relative_utf16_range {
13080            let selections = self.selections.all::<OffsetUtf16>(cx);
13081            self.change_selections(None, cx, |s| {
13082                let new_ranges = selections.into_iter().map(|range| {
13083                    let start = OffsetUtf16(
13084                        range
13085                            .head()
13086                            .0
13087                            .saturating_add_signed(relative_utf16_range.start),
13088                    );
13089                    let end = OffsetUtf16(
13090                        range
13091                            .head()
13092                            .0
13093                            .saturating_add_signed(relative_utf16_range.end),
13094                    );
13095                    start..end
13096                });
13097                s.select_ranges(new_ranges);
13098            });
13099        }
13100
13101        self.handle_input(text, cx);
13102    }
13103
13104    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13105        let Some(provider) = self.semantics_provider.as_ref() else {
13106            return false;
13107        };
13108
13109        let mut supports = false;
13110        self.buffer().read(cx).for_each_buffer(|buffer| {
13111            supports |= provider.supports_inlay_hints(buffer, cx);
13112        });
13113        supports
13114    }
13115
13116    pub fn focus(&self, cx: &mut WindowContext) {
13117        cx.focus(&self.focus_handle)
13118    }
13119
13120    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13121        self.focus_handle.is_focused(cx)
13122    }
13123
13124    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13125        cx.emit(EditorEvent::Focused);
13126
13127        if let Some(descendant) = self
13128            .last_focused_descendant
13129            .take()
13130            .and_then(|descendant| descendant.upgrade())
13131        {
13132            cx.focus(&descendant);
13133        } else {
13134            if let Some(blame) = self.blame.as_ref() {
13135                blame.update(cx, GitBlame::focus)
13136            }
13137
13138            self.blink_manager.update(cx, BlinkManager::enable);
13139            self.show_cursor_names(cx);
13140            self.buffer.update(cx, |buffer, cx| {
13141                buffer.finalize_last_transaction(cx);
13142                if self.leader_peer_id.is_none() {
13143                    buffer.set_active_selections(
13144                        &self.selections.disjoint_anchors(),
13145                        self.selections.line_mode,
13146                        self.cursor_shape,
13147                        cx,
13148                    );
13149                }
13150            });
13151        }
13152    }
13153
13154    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13155        cx.emit(EditorEvent::FocusedIn)
13156    }
13157
13158    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13159        if event.blurred != self.focus_handle {
13160            self.last_focused_descendant = Some(event.blurred);
13161        }
13162    }
13163
13164    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13165        self.blink_manager.update(cx, BlinkManager::disable);
13166        self.buffer
13167            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13168
13169        if let Some(blame) = self.blame.as_ref() {
13170            blame.update(cx, GitBlame::blur)
13171        }
13172        if !self.hover_state.focused(cx) {
13173            hide_hover(self, cx);
13174        }
13175
13176        self.hide_context_menu(cx);
13177        cx.emit(EditorEvent::Blurred);
13178        cx.notify();
13179    }
13180
13181    pub fn register_action<A: Action>(
13182        &mut self,
13183        listener: impl Fn(&A, &mut WindowContext) + 'static,
13184    ) -> Subscription {
13185        let id = self.next_editor_action_id.post_inc();
13186        let listener = Arc::new(listener);
13187        self.editor_actions.borrow_mut().insert(
13188            id,
13189            Box::new(move |cx| {
13190                let cx = cx.window_context();
13191                let listener = listener.clone();
13192                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13193                    let action = action.downcast_ref().unwrap();
13194                    if phase == DispatchPhase::Bubble {
13195                        listener(action, cx)
13196                    }
13197                })
13198            }),
13199        );
13200
13201        let editor_actions = self.editor_actions.clone();
13202        Subscription::new(move || {
13203            editor_actions.borrow_mut().remove(&id);
13204        })
13205    }
13206
13207    pub fn file_header_size(&self) -> u32 {
13208        FILE_HEADER_HEIGHT
13209    }
13210
13211    pub fn revert(
13212        &mut self,
13213        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13214        cx: &mut ViewContext<Self>,
13215    ) {
13216        self.buffer().update(cx, |multi_buffer, cx| {
13217            for (buffer_id, changes) in revert_changes {
13218                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13219                    buffer.update(cx, |buffer, cx| {
13220                        buffer.edit(
13221                            changes.into_iter().map(|(range, text)| {
13222                                (range, text.to_string().map(Arc::<str>::from))
13223                            }),
13224                            None,
13225                            cx,
13226                        );
13227                    });
13228                }
13229            }
13230        });
13231        self.change_selections(None, cx, |selections| selections.refresh());
13232    }
13233
13234    pub fn to_pixel_point(
13235        &mut self,
13236        source: multi_buffer::Anchor,
13237        editor_snapshot: &EditorSnapshot,
13238        cx: &mut ViewContext<Self>,
13239    ) -> Option<gpui::Point<Pixels>> {
13240        let source_point = source.to_display_point(editor_snapshot);
13241        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13242    }
13243
13244    pub fn display_to_pixel_point(
13245        &mut self,
13246        source: DisplayPoint,
13247        editor_snapshot: &EditorSnapshot,
13248        cx: &mut ViewContext<Self>,
13249    ) -> Option<gpui::Point<Pixels>> {
13250        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13251        let text_layout_details = self.text_layout_details(cx);
13252        let scroll_top = text_layout_details
13253            .scroll_anchor
13254            .scroll_position(editor_snapshot)
13255            .y;
13256
13257        if source.row().as_f32() < scroll_top.floor() {
13258            return None;
13259        }
13260        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13261        let source_y = line_height * (source.row().as_f32() - scroll_top);
13262        Some(gpui::Point::new(source_x, source_y))
13263    }
13264
13265    pub fn has_active_completions_menu(&self) -> bool {
13266        self.context_menu.read().as_ref().map_or(false, |menu| {
13267            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13268        })
13269    }
13270
13271    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13272        self.addons
13273            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13274    }
13275
13276    pub fn unregister_addon<T: Addon>(&mut self) {
13277        self.addons.remove(&std::any::TypeId::of::<T>());
13278    }
13279
13280    pub fn addon<T: Addon>(&self) -> Option<&T> {
13281        let type_id = std::any::TypeId::of::<T>();
13282        self.addons
13283            .get(&type_id)
13284            .and_then(|item| item.to_any().downcast_ref::<T>())
13285    }
13286}
13287
13288fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13289    let tab_size = tab_size.get() as usize;
13290    let mut width = offset;
13291
13292    for ch in text.chars() {
13293        width += if ch == '\t' {
13294            tab_size - (width % tab_size)
13295        } else {
13296            1
13297        };
13298    }
13299
13300    width - offset
13301}
13302
13303#[cfg(test)]
13304mod tests {
13305    use super::*;
13306
13307    #[test]
13308    fn test_string_size_with_expanded_tabs() {
13309        let nz = |val| NonZeroU32::new(val).unwrap();
13310        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13311        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13312        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13313        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13314        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13315        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13316        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13317        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13318    }
13319}
13320
13321/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13322struct WordBreakingTokenizer<'a> {
13323    input: &'a str,
13324}
13325
13326impl<'a> WordBreakingTokenizer<'a> {
13327    fn new(input: &'a str) -> Self {
13328        Self { input }
13329    }
13330}
13331
13332fn is_char_ideographic(ch: char) -> bool {
13333    use unicode_script::Script::*;
13334    use unicode_script::UnicodeScript;
13335    matches!(ch.script(), Han | Tangut | Yi)
13336}
13337
13338fn is_grapheme_ideographic(text: &str) -> bool {
13339    text.chars().any(is_char_ideographic)
13340}
13341
13342fn is_grapheme_whitespace(text: &str) -> bool {
13343    text.chars().any(|x| x.is_whitespace())
13344}
13345
13346fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13347    text.chars().next().map_or(false, |ch| {
13348        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13349    })
13350}
13351
13352#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13353struct WordBreakToken<'a> {
13354    token: &'a str,
13355    grapheme_len: usize,
13356    is_whitespace: bool,
13357}
13358
13359impl<'a> Iterator for WordBreakingTokenizer<'a> {
13360    /// Yields a span, the count of graphemes in the token, and whether it was
13361    /// whitespace. Note that it also breaks at word boundaries.
13362    type Item = WordBreakToken<'a>;
13363
13364    fn next(&mut self) -> Option<Self::Item> {
13365        use unicode_segmentation::UnicodeSegmentation;
13366        if self.input.is_empty() {
13367            return None;
13368        }
13369
13370        let mut iter = self.input.graphemes(true).peekable();
13371        let mut offset = 0;
13372        let mut graphemes = 0;
13373        if let Some(first_grapheme) = iter.next() {
13374            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13375            offset += first_grapheme.len();
13376            graphemes += 1;
13377            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13378                if let Some(grapheme) = iter.peek().copied() {
13379                    if should_stay_with_preceding_ideograph(grapheme) {
13380                        offset += grapheme.len();
13381                        graphemes += 1;
13382                    }
13383                }
13384            } else {
13385                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13386                let mut next_word_bound = words.peek().copied();
13387                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13388                    next_word_bound = words.next();
13389                }
13390                while let Some(grapheme) = iter.peek().copied() {
13391                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13392                        break;
13393                    };
13394                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13395                        break;
13396                    };
13397                    offset += grapheme.len();
13398                    graphemes += 1;
13399                    iter.next();
13400                }
13401            }
13402            let token = &self.input[..offset];
13403            self.input = &self.input[offset..];
13404            if is_whitespace {
13405                Some(WordBreakToken {
13406                    token: " ",
13407                    grapheme_len: 1,
13408                    is_whitespace: true,
13409                })
13410            } else {
13411                Some(WordBreakToken {
13412                    token,
13413                    grapheme_len: graphemes,
13414                    is_whitespace: false,
13415                })
13416            }
13417        } else {
13418            None
13419        }
13420    }
13421}
13422
13423#[test]
13424fn test_word_breaking_tokenizer() {
13425    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13426        ("", &[]),
13427        ("  ", &[(" ", 1, true)]),
13428        ("Ʒ", &[("Ʒ", 1, false)]),
13429        ("Ǽ", &[("Ǽ", 1, false)]),
13430        ("", &[("", 1, false)]),
13431        ("⋑⋑", &[("⋑⋑", 2, false)]),
13432        (
13433            "原理,进而",
13434            &[
13435                ("", 1, false),
13436                ("理,", 2, false),
13437                ("", 1, false),
13438                ("", 1, false),
13439            ],
13440        ),
13441        (
13442            "hello world",
13443            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13444        ),
13445        (
13446            "hello, world",
13447            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13448        ),
13449        (
13450            "  hello world",
13451            &[
13452                (" ", 1, true),
13453                ("hello", 5, false),
13454                (" ", 1, true),
13455                ("world", 5, false),
13456            ],
13457        ),
13458        (
13459            "这是什么 \n 钢笔",
13460            &[
13461                ("", 1, false),
13462                ("", 1, false),
13463                ("", 1, false),
13464                ("", 1, false),
13465                (" ", 1, true),
13466                ("", 1, false),
13467                ("", 1, false),
13468            ],
13469        ),
13470        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13471    ];
13472
13473    for (input, result) in tests {
13474        assert_eq!(
13475            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13476            result
13477                .iter()
13478                .copied()
13479                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13480                    token,
13481                    grapheme_len,
13482                    is_whitespace,
13483                })
13484                .collect::<Vec<_>>()
13485        );
13486    }
13487}
13488
13489fn wrap_with_prefix(
13490    line_prefix: String,
13491    unwrapped_text: String,
13492    wrap_column: usize,
13493    tab_size: NonZeroU32,
13494) -> String {
13495    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13496    let mut wrapped_text = String::new();
13497    let mut current_line = line_prefix.clone();
13498
13499    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13500    let mut current_line_len = line_prefix_len;
13501    for WordBreakToken {
13502        token,
13503        grapheme_len,
13504        is_whitespace,
13505    } in tokenizer
13506    {
13507        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13508            wrapped_text.push_str(current_line.trim_end());
13509            wrapped_text.push('\n');
13510            current_line.truncate(line_prefix.len());
13511            current_line_len = line_prefix_len;
13512            if !is_whitespace {
13513                current_line.push_str(token);
13514                current_line_len += grapheme_len;
13515            }
13516        } else if !is_whitespace {
13517            current_line.push_str(token);
13518            current_line_len += grapheme_len;
13519        } else if current_line_len != line_prefix_len {
13520            current_line.push(' ');
13521            current_line_len += 1;
13522        }
13523    }
13524
13525    if !current_line.is_empty() {
13526        wrapped_text.push_str(&current_line);
13527    }
13528    wrapped_text
13529}
13530
13531#[test]
13532fn test_wrap_with_prefix() {
13533    assert_eq!(
13534        wrap_with_prefix(
13535            "# ".to_string(),
13536            "abcdefg".to_string(),
13537            4,
13538            NonZeroU32::new(4).unwrap()
13539        ),
13540        "# abcdefg"
13541    );
13542    assert_eq!(
13543        wrap_with_prefix(
13544            "".to_string(),
13545            "\thello world".to_string(),
13546            8,
13547            NonZeroU32::new(4).unwrap()
13548        ),
13549        "hello\nworld"
13550    );
13551    assert_eq!(
13552        wrap_with_prefix(
13553            "// ".to_string(),
13554            "xx \nyy zz aa bb cc".to_string(),
13555            12,
13556            NonZeroU32::new(4).unwrap()
13557        ),
13558        "// xx yy zz\n// aa bb cc"
13559    );
13560    assert_eq!(
13561        wrap_with_prefix(
13562            String::new(),
13563            "这是什么 \n 钢笔".to_string(),
13564            3,
13565            NonZeroU32::new(4).unwrap()
13566        ),
13567        "这是什\n么 钢\n"
13568    );
13569}
13570
13571fn hunks_for_selections(
13572    multi_buffer_snapshot: &MultiBufferSnapshot,
13573    selections: &[Selection<Anchor>],
13574) -> Vec<MultiBufferDiffHunk> {
13575    let buffer_rows_for_selections = selections.iter().map(|selection| {
13576        let head = selection.head();
13577        let tail = selection.tail();
13578        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13579        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13580        if start > end {
13581            end..start
13582        } else {
13583            start..end
13584        }
13585    });
13586
13587    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13588}
13589
13590pub fn hunks_for_rows(
13591    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13592    multi_buffer_snapshot: &MultiBufferSnapshot,
13593) -> Vec<MultiBufferDiffHunk> {
13594    let mut hunks = Vec::new();
13595    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13596        HashMap::default();
13597    for selected_multi_buffer_rows in rows {
13598        let query_rows =
13599            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13600        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13601            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13602            // when the caret is just above or just below the deleted hunk.
13603            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13604            let related_to_selection = if allow_adjacent {
13605                hunk.row_range.overlaps(&query_rows)
13606                    || hunk.row_range.start == query_rows.end
13607                    || hunk.row_range.end == query_rows.start
13608            } else {
13609                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13610                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13611                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13612                    || selected_multi_buffer_rows.end == hunk.row_range.start
13613            };
13614            if related_to_selection {
13615                if !processed_buffer_rows
13616                    .entry(hunk.buffer_id)
13617                    .or_default()
13618                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13619                {
13620                    continue;
13621                }
13622                hunks.push(hunk);
13623            }
13624        }
13625    }
13626
13627    hunks
13628}
13629
13630pub trait CollaborationHub {
13631    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13632    fn user_participant_indices<'a>(
13633        &self,
13634        cx: &'a AppContext,
13635    ) -> &'a HashMap<u64, ParticipantIndex>;
13636    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13637}
13638
13639impl CollaborationHub for Model<Project> {
13640    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13641        self.read(cx).collaborators()
13642    }
13643
13644    fn user_participant_indices<'a>(
13645        &self,
13646        cx: &'a AppContext,
13647    ) -> &'a HashMap<u64, ParticipantIndex> {
13648        self.read(cx).user_store().read(cx).participant_indices()
13649    }
13650
13651    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13652        let this = self.read(cx);
13653        let user_ids = this.collaborators().values().map(|c| c.user_id);
13654        this.user_store().read_with(cx, |user_store, cx| {
13655            user_store.participant_names(user_ids, cx)
13656        })
13657    }
13658}
13659
13660pub trait SemanticsProvider {
13661    fn hover(
13662        &self,
13663        buffer: &Model<Buffer>,
13664        position: text::Anchor,
13665        cx: &mut AppContext,
13666    ) -> Option<Task<Vec<project::Hover>>>;
13667
13668    fn inlay_hints(
13669        &self,
13670        buffer_handle: Model<Buffer>,
13671        range: Range<text::Anchor>,
13672        cx: &mut AppContext,
13673    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13674
13675    fn resolve_inlay_hint(
13676        &self,
13677        hint: InlayHint,
13678        buffer_handle: Model<Buffer>,
13679        server_id: LanguageServerId,
13680        cx: &mut AppContext,
13681    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13682
13683    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13684
13685    fn document_highlights(
13686        &self,
13687        buffer: &Model<Buffer>,
13688        position: text::Anchor,
13689        cx: &mut AppContext,
13690    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13691
13692    fn definitions(
13693        &self,
13694        buffer: &Model<Buffer>,
13695        position: text::Anchor,
13696        kind: GotoDefinitionKind,
13697        cx: &mut AppContext,
13698    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13699
13700    fn range_for_rename(
13701        &self,
13702        buffer: &Model<Buffer>,
13703        position: text::Anchor,
13704        cx: &mut AppContext,
13705    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13706
13707    fn perform_rename(
13708        &self,
13709        buffer: &Model<Buffer>,
13710        position: text::Anchor,
13711        new_name: String,
13712        cx: &mut AppContext,
13713    ) -> Option<Task<Result<ProjectTransaction>>>;
13714}
13715
13716pub trait CompletionProvider {
13717    fn completions(
13718        &self,
13719        buffer: &Model<Buffer>,
13720        buffer_position: text::Anchor,
13721        trigger: CompletionContext,
13722        cx: &mut ViewContext<Editor>,
13723    ) -> Task<Result<Vec<Completion>>>;
13724
13725    fn resolve_completions(
13726        &self,
13727        buffer: Model<Buffer>,
13728        completion_indices: Vec<usize>,
13729        completions: Arc<RwLock<Box<[Completion]>>>,
13730        cx: &mut ViewContext<Editor>,
13731    ) -> Task<Result<bool>>;
13732
13733    fn apply_additional_edits_for_completion(
13734        &self,
13735        buffer: Model<Buffer>,
13736        completion: Completion,
13737        push_to_history: bool,
13738        cx: &mut ViewContext<Editor>,
13739    ) -> Task<Result<Option<language::Transaction>>>;
13740
13741    fn is_completion_trigger(
13742        &self,
13743        buffer: &Model<Buffer>,
13744        position: language::Anchor,
13745        text: &str,
13746        trigger_in_words: bool,
13747        cx: &mut ViewContext<Editor>,
13748    ) -> bool;
13749
13750    fn sort_completions(&self) -> bool {
13751        true
13752    }
13753}
13754
13755pub trait CodeActionProvider {
13756    fn code_actions(
13757        &self,
13758        buffer: &Model<Buffer>,
13759        range: Range<text::Anchor>,
13760        cx: &mut WindowContext,
13761    ) -> Task<Result<Vec<CodeAction>>>;
13762
13763    fn apply_code_action(
13764        &self,
13765        buffer_handle: Model<Buffer>,
13766        action: CodeAction,
13767        excerpt_id: ExcerptId,
13768        push_to_history: bool,
13769        cx: &mut WindowContext,
13770    ) -> Task<Result<ProjectTransaction>>;
13771}
13772
13773impl CodeActionProvider for Model<Project> {
13774    fn code_actions(
13775        &self,
13776        buffer: &Model<Buffer>,
13777        range: Range<text::Anchor>,
13778        cx: &mut WindowContext,
13779    ) -> Task<Result<Vec<CodeAction>>> {
13780        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13781    }
13782
13783    fn apply_code_action(
13784        &self,
13785        buffer_handle: Model<Buffer>,
13786        action: CodeAction,
13787        _excerpt_id: ExcerptId,
13788        push_to_history: bool,
13789        cx: &mut WindowContext,
13790    ) -> Task<Result<ProjectTransaction>> {
13791        self.update(cx, |project, cx| {
13792            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13793        })
13794    }
13795}
13796
13797fn snippet_completions(
13798    project: &Project,
13799    buffer: &Model<Buffer>,
13800    buffer_position: text::Anchor,
13801    cx: &mut AppContext,
13802) -> Vec<Completion> {
13803    let language = buffer.read(cx).language_at(buffer_position);
13804    let language_name = language.as_ref().map(|language| language.lsp_id());
13805    let snippet_store = project.snippets().read(cx);
13806    let snippets = snippet_store.snippets_for(language_name, cx);
13807
13808    if snippets.is_empty() {
13809        return vec![];
13810    }
13811    let snapshot = buffer.read(cx).text_snapshot();
13812    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13813
13814    let scope = language.map(|language| language.default_scope());
13815    let classifier = CharClassifier::new(scope).for_completion(true);
13816    let mut last_word = chars
13817        .take_while(|c| classifier.is_word(*c))
13818        .collect::<String>();
13819    last_word = last_word.chars().rev().collect();
13820    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13821    let to_lsp = |point: &text::Anchor| {
13822        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13823        point_to_lsp(end)
13824    };
13825    let lsp_end = to_lsp(&buffer_position);
13826    snippets
13827        .into_iter()
13828        .filter_map(|snippet| {
13829            let matching_prefix = snippet
13830                .prefix
13831                .iter()
13832                .find(|prefix| prefix.starts_with(&last_word))?;
13833            let start = as_offset - last_word.len();
13834            let start = snapshot.anchor_before(start);
13835            let range = start..buffer_position;
13836            let lsp_start = to_lsp(&start);
13837            let lsp_range = lsp::Range {
13838                start: lsp_start,
13839                end: lsp_end,
13840            };
13841            Some(Completion {
13842                old_range: range,
13843                new_text: snippet.body.clone(),
13844                label: CodeLabel {
13845                    text: matching_prefix.clone(),
13846                    runs: vec![],
13847                    filter_range: 0..matching_prefix.len(),
13848                },
13849                server_id: LanguageServerId(usize::MAX),
13850                documentation: snippet.description.clone().map(Documentation::SingleLine),
13851                lsp_completion: lsp::CompletionItem {
13852                    label: snippet.prefix.first().unwrap().clone(),
13853                    kind: Some(CompletionItemKind::SNIPPET),
13854                    label_details: snippet.description.as_ref().map(|description| {
13855                        lsp::CompletionItemLabelDetails {
13856                            detail: Some(description.clone()),
13857                            description: None,
13858                        }
13859                    }),
13860                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13861                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13862                        lsp::InsertReplaceEdit {
13863                            new_text: snippet.body.clone(),
13864                            insert: lsp_range,
13865                            replace: lsp_range,
13866                        },
13867                    )),
13868                    filter_text: Some(snippet.body.clone()),
13869                    sort_text: Some(char::MAX.to_string()),
13870                    ..Default::default()
13871                },
13872                confirm: None,
13873            })
13874        })
13875        .collect()
13876}
13877
13878impl CompletionProvider for Model<Project> {
13879    fn completions(
13880        &self,
13881        buffer: &Model<Buffer>,
13882        buffer_position: text::Anchor,
13883        options: CompletionContext,
13884        cx: &mut ViewContext<Editor>,
13885    ) -> Task<Result<Vec<Completion>>> {
13886        self.update(cx, |project, cx| {
13887            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13888            let project_completions = project.completions(buffer, buffer_position, options, cx);
13889            cx.background_executor().spawn(async move {
13890                let mut completions = project_completions.await?;
13891                //let snippets = snippets.into_iter().;
13892                completions.extend(snippets);
13893                Ok(completions)
13894            })
13895        })
13896    }
13897
13898    fn resolve_completions(
13899        &self,
13900        buffer: Model<Buffer>,
13901        completion_indices: Vec<usize>,
13902        completions: Arc<RwLock<Box<[Completion]>>>,
13903        cx: &mut ViewContext<Editor>,
13904    ) -> Task<Result<bool>> {
13905        self.update(cx, |project, cx| {
13906            project.resolve_completions(buffer, completion_indices, completions, cx)
13907        })
13908    }
13909
13910    fn apply_additional_edits_for_completion(
13911        &self,
13912        buffer: Model<Buffer>,
13913        completion: Completion,
13914        push_to_history: bool,
13915        cx: &mut ViewContext<Editor>,
13916    ) -> Task<Result<Option<language::Transaction>>> {
13917        self.update(cx, |project, cx| {
13918            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13919        })
13920    }
13921
13922    fn is_completion_trigger(
13923        &self,
13924        buffer: &Model<Buffer>,
13925        position: language::Anchor,
13926        text: &str,
13927        trigger_in_words: bool,
13928        cx: &mut ViewContext<Editor>,
13929    ) -> bool {
13930        if !EditorSettings::get_global(cx).show_completions_on_input {
13931            return false;
13932        }
13933
13934        let mut chars = text.chars();
13935        let char = if let Some(char) = chars.next() {
13936            char
13937        } else {
13938            return false;
13939        };
13940        if chars.next().is_some() {
13941            return false;
13942        }
13943
13944        let buffer = buffer.read(cx);
13945        let classifier = buffer
13946            .snapshot()
13947            .char_classifier_at(position)
13948            .for_completion(true);
13949        if trigger_in_words && classifier.is_word(char) {
13950            return true;
13951        }
13952
13953        buffer.completion_triggers().contains(text)
13954    }
13955}
13956
13957impl SemanticsProvider for Model<Project> {
13958    fn hover(
13959        &self,
13960        buffer: &Model<Buffer>,
13961        position: text::Anchor,
13962        cx: &mut AppContext,
13963    ) -> Option<Task<Vec<project::Hover>>> {
13964        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13965    }
13966
13967    fn document_highlights(
13968        &self,
13969        buffer: &Model<Buffer>,
13970        position: text::Anchor,
13971        cx: &mut AppContext,
13972    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13973        Some(self.update(cx, |project, cx| {
13974            project.document_highlights(buffer, position, cx)
13975        }))
13976    }
13977
13978    fn definitions(
13979        &self,
13980        buffer: &Model<Buffer>,
13981        position: text::Anchor,
13982        kind: GotoDefinitionKind,
13983        cx: &mut AppContext,
13984    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13985        Some(self.update(cx, |project, cx| match kind {
13986            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13987            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13988            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13989            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13990        }))
13991    }
13992
13993    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13994        // TODO: make this work for remote projects
13995        self.read(cx)
13996            .language_servers_for_buffer(buffer.read(cx), cx)
13997            .any(
13998                |(_, server)| match server.capabilities().inlay_hint_provider {
13999                    Some(lsp::OneOf::Left(enabled)) => enabled,
14000                    Some(lsp::OneOf::Right(_)) => true,
14001                    None => false,
14002                },
14003            )
14004    }
14005
14006    fn inlay_hints(
14007        &self,
14008        buffer_handle: Model<Buffer>,
14009        range: Range<text::Anchor>,
14010        cx: &mut AppContext,
14011    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14012        Some(self.update(cx, |project, cx| {
14013            project.inlay_hints(buffer_handle, range, cx)
14014        }))
14015    }
14016
14017    fn resolve_inlay_hint(
14018        &self,
14019        hint: InlayHint,
14020        buffer_handle: Model<Buffer>,
14021        server_id: LanguageServerId,
14022        cx: &mut AppContext,
14023    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14024        Some(self.update(cx, |project, cx| {
14025            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14026        }))
14027    }
14028
14029    fn range_for_rename(
14030        &self,
14031        buffer: &Model<Buffer>,
14032        position: text::Anchor,
14033        cx: &mut AppContext,
14034    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14035        Some(self.update(cx, |project, cx| {
14036            project.prepare_rename(buffer.clone(), position, cx)
14037        }))
14038    }
14039
14040    fn perform_rename(
14041        &self,
14042        buffer: &Model<Buffer>,
14043        position: text::Anchor,
14044        new_name: String,
14045        cx: &mut AppContext,
14046    ) -> Option<Task<Result<ProjectTransaction>>> {
14047        Some(self.update(cx, |project, cx| {
14048            project.perform_rename(buffer.clone(), position, new_name, cx)
14049        }))
14050    }
14051}
14052
14053fn inlay_hint_settings(
14054    location: Anchor,
14055    snapshot: &MultiBufferSnapshot,
14056    cx: &mut ViewContext<'_, Editor>,
14057) -> InlayHintSettings {
14058    let file = snapshot.file_at(location);
14059    let language = snapshot.language_at(location).map(|l| l.name());
14060    language_settings(language, file, cx).inlay_hints
14061}
14062
14063fn consume_contiguous_rows(
14064    contiguous_row_selections: &mut Vec<Selection<Point>>,
14065    selection: &Selection<Point>,
14066    display_map: &DisplaySnapshot,
14067    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14068) -> (MultiBufferRow, MultiBufferRow) {
14069    contiguous_row_selections.push(selection.clone());
14070    let start_row = MultiBufferRow(selection.start.row);
14071    let mut end_row = ending_row(selection, display_map);
14072
14073    while let Some(next_selection) = selections.peek() {
14074        if next_selection.start.row <= end_row.0 {
14075            end_row = ending_row(next_selection, display_map);
14076            contiguous_row_selections.push(selections.next().unwrap().clone());
14077        } else {
14078            break;
14079        }
14080    }
14081    (start_row, end_row)
14082}
14083
14084fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14085    if next_selection.end.column > 0 || next_selection.is_empty() {
14086        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14087    } else {
14088        MultiBufferRow(next_selection.end.row)
14089    }
14090}
14091
14092impl EditorSnapshot {
14093    pub fn remote_selections_in_range<'a>(
14094        &'a self,
14095        range: &'a Range<Anchor>,
14096        collaboration_hub: &dyn CollaborationHub,
14097        cx: &'a AppContext,
14098    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14099        let participant_names = collaboration_hub.user_names(cx);
14100        let participant_indices = collaboration_hub.user_participant_indices(cx);
14101        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14102        let collaborators_by_replica_id = collaborators_by_peer_id
14103            .iter()
14104            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14105            .collect::<HashMap<_, _>>();
14106        self.buffer_snapshot
14107            .selections_in_range(range, false)
14108            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14109                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14110                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14111                let user_name = participant_names.get(&collaborator.user_id).cloned();
14112                Some(RemoteSelection {
14113                    replica_id,
14114                    selection,
14115                    cursor_shape,
14116                    line_mode,
14117                    participant_index,
14118                    peer_id: collaborator.peer_id,
14119                    user_name,
14120                })
14121            })
14122    }
14123
14124    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14125        self.display_snapshot.buffer_snapshot.language_at(position)
14126    }
14127
14128    pub fn is_focused(&self) -> bool {
14129        self.is_focused
14130    }
14131
14132    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14133        self.placeholder_text.as_ref()
14134    }
14135
14136    pub fn scroll_position(&self) -> gpui::Point<f32> {
14137        self.scroll_anchor.scroll_position(&self.display_snapshot)
14138    }
14139
14140    fn gutter_dimensions(
14141        &self,
14142        font_id: FontId,
14143        font_size: Pixels,
14144        em_width: Pixels,
14145        em_advance: Pixels,
14146        max_line_number_width: Pixels,
14147        cx: &AppContext,
14148    ) -> GutterDimensions {
14149        if !self.show_gutter {
14150            return GutterDimensions::default();
14151        }
14152        let descent = cx.text_system().descent(font_id, font_size);
14153
14154        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14155            matches!(
14156                ProjectSettings::get_global(cx).git.git_gutter,
14157                Some(GitGutterSetting::TrackedFiles)
14158            )
14159        });
14160        let gutter_settings = EditorSettings::get_global(cx).gutter;
14161        let show_line_numbers = self
14162            .show_line_numbers
14163            .unwrap_or(gutter_settings.line_numbers);
14164        let line_gutter_width = if show_line_numbers {
14165            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14166            let min_width_for_number_on_gutter = em_advance * 4.0;
14167            max_line_number_width.max(min_width_for_number_on_gutter)
14168        } else {
14169            0.0.into()
14170        };
14171
14172        let show_code_actions = self
14173            .show_code_actions
14174            .unwrap_or(gutter_settings.code_actions);
14175
14176        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14177
14178        let git_blame_entries_width =
14179            self.git_blame_gutter_max_author_length
14180                .map(|max_author_length| {
14181                    // Length of the author name, but also space for the commit hash,
14182                    // the spacing and the timestamp.
14183                    let max_char_count = max_author_length
14184                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14185                        + 7 // length of commit sha
14186                        + 14 // length of max relative timestamp ("60 minutes ago")
14187                        + 4; // gaps and margins
14188
14189                    em_advance * max_char_count
14190                });
14191
14192        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14193        left_padding += if show_code_actions || show_runnables {
14194            em_width * 3.0
14195        } else if show_git_gutter && show_line_numbers {
14196            em_width * 2.0
14197        } else if show_git_gutter || show_line_numbers {
14198            em_width
14199        } else {
14200            px(0.)
14201        };
14202
14203        let right_padding = if gutter_settings.folds && show_line_numbers {
14204            em_width * 4.0
14205        } else if gutter_settings.folds {
14206            em_width * 3.0
14207        } else if show_line_numbers {
14208            em_width
14209        } else {
14210            px(0.)
14211        };
14212
14213        GutterDimensions {
14214            left_padding,
14215            right_padding,
14216            width: line_gutter_width + left_padding + right_padding,
14217            margin: -descent,
14218            git_blame_entries_width,
14219        }
14220    }
14221
14222    pub fn render_crease_toggle(
14223        &self,
14224        buffer_row: MultiBufferRow,
14225        row_contains_cursor: bool,
14226        editor: View<Editor>,
14227        cx: &mut WindowContext,
14228    ) -> Option<AnyElement> {
14229        let folded = self.is_line_folded(buffer_row);
14230        let mut is_foldable = false;
14231
14232        if let Some(crease) = self
14233            .crease_snapshot
14234            .query_row(buffer_row, &self.buffer_snapshot)
14235        {
14236            is_foldable = true;
14237            match crease {
14238                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14239                    if let Some(render_toggle) = render_toggle {
14240                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14241                            if folded {
14242                                editor.update(cx, |editor, cx| {
14243                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14244                                });
14245                            } else {
14246                                editor.update(cx, |editor, cx| {
14247                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14248                                });
14249                            }
14250                        });
14251                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14252                    }
14253                }
14254            }
14255        }
14256
14257        is_foldable |= self.starts_indent(buffer_row);
14258
14259        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14260            Some(
14261                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14262                    .selected(folded)
14263                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14264                        if folded {
14265                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14266                        } else {
14267                            this.fold_at(&FoldAt { buffer_row }, cx);
14268                        }
14269                    }))
14270                    .into_any_element(),
14271            )
14272        } else {
14273            None
14274        }
14275    }
14276
14277    pub fn render_crease_trailer(
14278        &self,
14279        buffer_row: MultiBufferRow,
14280        cx: &mut WindowContext,
14281    ) -> Option<AnyElement> {
14282        let folded = self.is_line_folded(buffer_row);
14283        if let Crease::Inline { render_trailer, .. } = self
14284            .crease_snapshot
14285            .query_row(buffer_row, &self.buffer_snapshot)?
14286        {
14287            let render_trailer = render_trailer.as_ref()?;
14288            Some(render_trailer(buffer_row, folded, cx))
14289        } else {
14290            None
14291        }
14292    }
14293}
14294
14295impl Deref for EditorSnapshot {
14296    type Target = DisplaySnapshot;
14297
14298    fn deref(&self) -> &Self::Target {
14299        &self.display_snapshot
14300    }
14301}
14302
14303#[derive(Clone, Debug, PartialEq, Eq)]
14304pub enum EditorEvent {
14305    InputIgnored {
14306        text: Arc<str>,
14307    },
14308    InputHandled {
14309        utf16_range_to_replace: Option<Range<isize>>,
14310        text: Arc<str>,
14311    },
14312    ExcerptsAdded {
14313        buffer: Model<Buffer>,
14314        predecessor: ExcerptId,
14315        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14316    },
14317    ExcerptsRemoved {
14318        ids: Vec<ExcerptId>,
14319    },
14320    ExcerptsEdited {
14321        ids: Vec<ExcerptId>,
14322    },
14323    ExcerptsExpanded {
14324        ids: Vec<ExcerptId>,
14325    },
14326    BufferEdited,
14327    Edited {
14328        transaction_id: clock::Lamport,
14329    },
14330    Reparsed(BufferId),
14331    Focused,
14332    FocusedIn,
14333    Blurred,
14334    DirtyChanged,
14335    Saved,
14336    TitleChanged,
14337    DiffBaseChanged,
14338    SelectionsChanged {
14339        local: bool,
14340    },
14341    ScrollPositionChanged {
14342        local: bool,
14343        autoscroll: bool,
14344    },
14345    Closed,
14346    TransactionUndone {
14347        transaction_id: clock::Lamport,
14348    },
14349    TransactionBegun {
14350        transaction_id: clock::Lamport,
14351    },
14352    Reloaded,
14353    CursorShapeChanged,
14354}
14355
14356impl EventEmitter<EditorEvent> for Editor {}
14357
14358impl FocusableView for Editor {
14359    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14360        self.focus_handle.clone()
14361    }
14362}
14363
14364impl Render for Editor {
14365    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14366        let settings = ThemeSettings::get_global(cx);
14367
14368        let mut text_style = match self.mode {
14369            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14370                color: cx.theme().colors().editor_foreground,
14371                font_family: settings.ui_font.family.clone(),
14372                font_features: settings.ui_font.features.clone(),
14373                font_fallbacks: settings.ui_font.fallbacks.clone(),
14374                font_size: rems(0.875).into(),
14375                font_weight: settings.ui_font.weight,
14376                line_height: relative(settings.buffer_line_height.value()),
14377                ..Default::default()
14378            },
14379            EditorMode::Full => TextStyle {
14380                color: cx.theme().colors().editor_foreground,
14381                font_family: settings.buffer_font.family.clone(),
14382                font_features: settings.buffer_font.features.clone(),
14383                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14384                font_size: settings.buffer_font_size(cx).into(),
14385                font_weight: settings.buffer_font.weight,
14386                line_height: relative(settings.buffer_line_height.value()),
14387                ..Default::default()
14388            },
14389        };
14390        if let Some(text_style_refinement) = &self.text_style_refinement {
14391            text_style.refine(text_style_refinement)
14392        }
14393
14394        let background = match self.mode {
14395            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14396            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14397            EditorMode::Full => cx.theme().colors().editor_background,
14398        };
14399
14400        EditorElement::new(
14401            cx.view(),
14402            EditorStyle {
14403                background,
14404                local_player: cx.theme().players().local(),
14405                text: text_style,
14406                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14407                syntax: cx.theme().syntax().clone(),
14408                status: cx.theme().status().clone(),
14409                inlay_hints_style: make_inlay_hints_style(cx),
14410                suggestions_style: HighlightStyle {
14411                    color: Some(cx.theme().status().predictive),
14412                    ..HighlightStyle::default()
14413                },
14414                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14415            },
14416        )
14417    }
14418}
14419
14420impl ViewInputHandler for Editor {
14421    fn text_for_range(
14422        &mut self,
14423        range_utf16: Range<usize>,
14424        cx: &mut ViewContext<Self>,
14425    ) -> Option<String> {
14426        Some(
14427            self.buffer
14428                .read(cx)
14429                .read(cx)
14430                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14431                .collect(),
14432        )
14433    }
14434
14435    fn selected_text_range(
14436        &mut self,
14437        ignore_disabled_input: bool,
14438        cx: &mut ViewContext<Self>,
14439    ) -> Option<UTF16Selection> {
14440        // Prevent the IME menu from appearing when holding down an alphabetic key
14441        // while input is disabled.
14442        if !ignore_disabled_input && !self.input_enabled {
14443            return None;
14444        }
14445
14446        let selection = self.selections.newest::<OffsetUtf16>(cx);
14447        let range = selection.range();
14448
14449        Some(UTF16Selection {
14450            range: range.start.0..range.end.0,
14451            reversed: selection.reversed,
14452        })
14453    }
14454
14455    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14456        let snapshot = self.buffer.read(cx).read(cx);
14457        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14458        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14459    }
14460
14461    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14462        self.clear_highlights::<InputComposition>(cx);
14463        self.ime_transaction.take();
14464    }
14465
14466    fn replace_text_in_range(
14467        &mut self,
14468        range_utf16: Option<Range<usize>>,
14469        text: &str,
14470        cx: &mut ViewContext<Self>,
14471    ) {
14472        if !self.input_enabled {
14473            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14474            return;
14475        }
14476
14477        self.transact(cx, |this, cx| {
14478            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14479                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14480                Some(this.selection_replacement_ranges(range_utf16, cx))
14481            } else {
14482                this.marked_text_ranges(cx)
14483            };
14484
14485            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14486                let newest_selection_id = this.selections.newest_anchor().id;
14487                this.selections
14488                    .all::<OffsetUtf16>(cx)
14489                    .iter()
14490                    .zip(ranges_to_replace.iter())
14491                    .find_map(|(selection, range)| {
14492                        if selection.id == newest_selection_id {
14493                            Some(
14494                                (range.start.0 as isize - selection.head().0 as isize)
14495                                    ..(range.end.0 as isize - selection.head().0 as isize),
14496                            )
14497                        } else {
14498                            None
14499                        }
14500                    })
14501            });
14502
14503            cx.emit(EditorEvent::InputHandled {
14504                utf16_range_to_replace: range_to_replace,
14505                text: text.into(),
14506            });
14507
14508            if let Some(new_selected_ranges) = new_selected_ranges {
14509                this.change_selections(None, cx, |selections| {
14510                    selections.select_ranges(new_selected_ranges)
14511                });
14512                this.backspace(&Default::default(), cx);
14513            }
14514
14515            this.handle_input(text, cx);
14516        });
14517
14518        if let Some(transaction) = self.ime_transaction {
14519            self.buffer.update(cx, |buffer, cx| {
14520                buffer.group_until_transaction(transaction, cx);
14521            });
14522        }
14523
14524        self.unmark_text(cx);
14525    }
14526
14527    fn replace_and_mark_text_in_range(
14528        &mut self,
14529        range_utf16: Option<Range<usize>>,
14530        text: &str,
14531        new_selected_range_utf16: Option<Range<usize>>,
14532        cx: &mut ViewContext<Self>,
14533    ) {
14534        if !self.input_enabled {
14535            return;
14536        }
14537
14538        let transaction = self.transact(cx, |this, cx| {
14539            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14540                let snapshot = this.buffer.read(cx).read(cx);
14541                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14542                    for marked_range in &mut marked_ranges {
14543                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14544                        marked_range.start.0 += relative_range_utf16.start;
14545                        marked_range.start =
14546                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14547                        marked_range.end =
14548                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14549                    }
14550                }
14551                Some(marked_ranges)
14552            } else if let Some(range_utf16) = range_utf16 {
14553                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14554                Some(this.selection_replacement_ranges(range_utf16, cx))
14555            } else {
14556                None
14557            };
14558
14559            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14560                let newest_selection_id = this.selections.newest_anchor().id;
14561                this.selections
14562                    .all::<OffsetUtf16>(cx)
14563                    .iter()
14564                    .zip(ranges_to_replace.iter())
14565                    .find_map(|(selection, range)| {
14566                        if selection.id == newest_selection_id {
14567                            Some(
14568                                (range.start.0 as isize - selection.head().0 as isize)
14569                                    ..(range.end.0 as isize - selection.head().0 as isize),
14570                            )
14571                        } else {
14572                            None
14573                        }
14574                    })
14575            });
14576
14577            cx.emit(EditorEvent::InputHandled {
14578                utf16_range_to_replace: range_to_replace,
14579                text: text.into(),
14580            });
14581
14582            if let Some(ranges) = ranges_to_replace {
14583                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14584            }
14585
14586            let marked_ranges = {
14587                let snapshot = this.buffer.read(cx).read(cx);
14588                this.selections
14589                    .disjoint_anchors()
14590                    .iter()
14591                    .map(|selection| {
14592                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14593                    })
14594                    .collect::<Vec<_>>()
14595            };
14596
14597            if text.is_empty() {
14598                this.unmark_text(cx);
14599            } else {
14600                this.highlight_text::<InputComposition>(
14601                    marked_ranges.clone(),
14602                    HighlightStyle {
14603                        underline: Some(UnderlineStyle {
14604                            thickness: px(1.),
14605                            color: None,
14606                            wavy: false,
14607                        }),
14608                        ..Default::default()
14609                    },
14610                    cx,
14611                );
14612            }
14613
14614            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14615            let use_autoclose = this.use_autoclose;
14616            let use_auto_surround = this.use_auto_surround;
14617            this.set_use_autoclose(false);
14618            this.set_use_auto_surround(false);
14619            this.handle_input(text, cx);
14620            this.set_use_autoclose(use_autoclose);
14621            this.set_use_auto_surround(use_auto_surround);
14622
14623            if let Some(new_selected_range) = new_selected_range_utf16 {
14624                let snapshot = this.buffer.read(cx).read(cx);
14625                let new_selected_ranges = marked_ranges
14626                    .into_iter()
14627                    .map(|marked_range| {
14628                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14629                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14630                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14631                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14632                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14633                    })
14634                    .collect::<Vec<_>>();
14635
14636                drop(snapshot);
14637                this.change_selections(None, cx, |selections| {
14638                    selections.select_ranges(new_selected_ranges)
14639                });
14640            }
14641        });
14642
14643        self.ime_transaction = self.ime_transaction.or(transaction);
14644        if let Some(transaction) = self.ime_transaction {
14645            self.buffer.update(cx, |buffer, cx| {
14646                buffer.group_until_transaction(transaction, cx);
14647            });
14648        }
14649
14650        if self.text_highlights::<InputComposition>(cx).is_none() {
14651            self.ime_transaction.take();
14652        }
14653    }
14654
14655    fn bounds_for_range(
14656        &mut self,
14657        range_utf16: Range<usize>,
14658        element_bounds: gpui::Bounds<Pixels>,
14659        cx: &mut ViewContext<Self>,
14660    ) -> Option<gpui::Bounds<Pixels>> {
14661        let text_layout_details = self.text_layout_details(cx);
14662        let style = &text_layout_details.editor_style;
14663        let font_id = cx.text_system().resolve_font(&style.text.font());
14664        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14665        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14666
14667        let em_width = cx
14668            .text_system()
14669            .typographic_bounds(font_id, font_size, 'm')
14670            .unwrap()
14671            .size
14672            .width;
14673
14674        let snapshot = self.snapshot(cx);
14675        let scroll_position = snapshot.scroll_position();
14676        let scroll_left = scroll_position.x * em_width;
14677
14678        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14679        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14680            + self.gutter_dimensions.width;
14681        let y = line_height * (start.row().as_f32() - scroll_position.y);
14682
14683        Some(Bounds {
14684            origin: element_bounds.origin + point(x, y),
14685            size: size(em_width, line_height),
14686        })
14687    }
14688}
14689
14690trait SelectionExt {
14691    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14692    fn spanned_rows(
14693        &self,
14694        include_end_if_at_line_start: bool,
14695        map: &DisplaySnapshot,
14696    ) -> Range<MultiBufferRow>;
14697}
14698
14699impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14700    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14701        let start = self
14702            .start
14703            .to_point(&map.buffer_snapshot)
14704            .to_display_point(map);
14705        let end = self
14706            .end
14707            .to_point(&map.buffer_snapshot)
14708            .to_display_point(map);
14709        if self.reversed {
14710            end..start
14711        } else {
14712            start..end
14713        }
14714    }
14715
14716    fn spanned_rows(
14717        &self,
14718        include_end_if_at_line_start: bool,
14719        map: &DisplaySnapshot,
14720    ) -> Range<MultiBufferRow> {
14721        let start = self.start.to_point(&map.buffer_snapshot);
14722        let mut end = self.end.to_point(&map.buffer_snapshot);
14723        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14724            end.row -= 1;
14725        }
14726
14727        let buffer_start = map.prev_line_boundary(start).0;
14728        let buffer_end = map.next_line_boundary(end).0;
14729        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14730    }
14731}
14732
14733impl<T: InvalidationRegion> InvalidationStack<T> {
14734    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14735    where
14736        S: Clone + ToOffset,
14737    {
14738        while let Some(region) = self.last() {
14739            let all_selections_inside_invalidation_ranges =
14740                if selections.len() == region.ranges().len() {
14741                    selections
14742                        .iter()
14743                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14744                        .all(|(selection, invalidation_range)| {
14745                            let head = selection.head().to_offset(buffer);
14746                            invalidation_range.start <= head && invalidation_range.end >= head
14747                        })
14748                } else {
14749                    false
14750                };
14751
14752            if all_selections_inside_invalidation_ranges {
14753                break;
14754            } else {
14755                self.pop();
14756            }
14757        }
14758    }
14759}
14760
14761impl<T> Default for InvalidationStack<T> {
14762    fn default() -> Self {
14763        Self(Default::default())
14764    }
14765}
14766
14767impl<T> Deref for InvalidationStack<T> {
14768    type Target = Vec<T>;
14769
14770    fn deref(&self) -> &Self::Target {
14771        &self.0
14772    }
14773}
14774
14775impl<T> DerefMut for InvalidationStack<T> {
14776    fn deref_mut(&mut self) -> &mut Self::Target {
14777        &mut self.0
14778    }
14779}
14780
14781impl InvalidationRegion for SnippetState {
14782    fn ranges(&self) -> &[Range<Anchor>] {
14783        &self.ranges[self.active_index]
14784    }
14785}
14786
14787pub fn diagnostic_block_renderer(
14788    diagnostic: Diagnostic,
14789    max_message_rows: Option<u8>,
14790    allow_closing: bool,
14791    _is_valid: bool,
14792) -> RenderBlock {
14793    let (text_without_backticks, code_ranges) =
14794        highlight_diagnostic_message(&diagnostic, max_message_rows);
14795
14796    Arc::new(move |cx: &mut BlockContext| {
14797        let group_id: SharedString = cx.block_id.to_string().into();
14798
14799        let mut text_style = cx.text_style().clone();
14800        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14801        let theme_settings = ThemeSettings::get_global(cx);
14802        text_style.font_family = theme_settings.buffer_font.family.clone();
14803        text_style.font_style = theme_settings.buffer_font.style;
14804        text_style.font_features = theme_settings.buffer_font.features.clone();
14805        text_style.font_weight = theme_settings.buffer_font.weight;
14806
14807        let multi_line_diagnostic = diagnostic.message.contains('\n');
14808
14809        let buttons = |diagnostic: &Diagnostic| {
14810            if multi_line_diagnostic {
14811                v_flex()
14812            } else {
14813                h_flex()
14814            }
14815            .when(allow_closing, |div| {
14816                div.children(diagnostic.is_primary.then(|| {
14817                    IconButton::new("close-block", IconName::XCircle)
14818                        .icon_color(Color::Muted)
14819                        .size(ButtonSize::Compact)
14820                        .style(ButtonStyle::Transparent)
14821                        .visible_on_hover(group_id.clone())
14822                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14823                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14824                }))
14825            })
14826            .child(
14827                IconButton::new("copy-block", IconName::Copy)
14828                    .icon_color(Color::Muted)
14829                    .size(ButtonSize::Compact)
14830                    .style(ButtonStyle::Transparent)
14831                    .visible_on_hover(group_id.clone())
14832                    .on_click({
14833                        let message = diagnostic.message.clone();
14834                        move |_click, cx| {
14835                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14836                        }
14837                    })
14838                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14839            )
14840        };
14841
14842        let icon_size = buttons(&diagnostic)
14843            .into_any_element()
14844            .layout_as_root(AvailableSpace::min_size(), cx);
14845
14846        h_flex()
14847            .id(cx.block_id)
14848            .group(group_id.clone())
14849            .relative()
14850            .size_full()
14851            .block_mouse_down()
14852            .pl(cx.gutter_dimensions.width)
14853            .w(cx.max_width - cx.gutter_dimensions.full_width())
14854            .child(
14855                div()
14856                    .flex()
14857                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14858                    .flex_shrink(),
14859            )
14860            .child(buttons(&diagnostic))
14861            .child(div().flex().flex_shrink_0().child(
14862                StyledText::new(text_without_backticks.clone()).with_highlights(
14863                    &text_style,
14864                    code_ranges.iter().map(|range| {
14865                        (
14866                            range.clone(),
14867                            HighlightStyle {
14868                                font_weight: Some(FontWeight::BOLD),
14869                                ..Default::default()
14870                            },
14871                        )
14872                    }),
14873                ),
14874            ))
14875            .into_any_element()
14876    })
14877}
14878
14879pub fn highlight_diagnostic_message(
14880    diagnostic: &Diagnostic,
14881    mut max_message_rows: Option<u8>,
14882) -> (SharedString, Vec<Range<usize>>) {
14883    let mut text_without_backticks = String::new();
14884    let mut code_ranges = Vec::new();
14885
14886    if let Some(source) = &diagnostic.source {
14887        text_without_backticks.push_str(source);
14888        code_ranges.push(0..source.len());
14889        text_without_backticks.push_str(": ");
14890    }
14891
14892    let mut prev_offset = 0;
14893    let mut in_code_block = false;
14894    let has_row_limit = max_message_rows.is_some();
14895    let mut newline_indices = diagnostic
14896        .message
14897        .match_indices('\n')
14898        .filter(|_| has_row_limit)
14899        .map(|(ix, _)| ix)
14900        .fuse()
14901        .peekable();
14902
14903    for (quote_ix, _) in diagnostic
14904        .message
14905        .match_indices('`')
14906        .chain([(diagnostic.message.len(), "")])
14907    {
14908        let mut first_newline_ix = None;
14909        let mut last_newline_ix = None;
14910        while let Some(newline_ix) = newline_indices.peek() {
14911            if *newline_ix < quote_ix {
14912                if first_newline_ix.is_none() {
14913                    first_newline_ix = Some(*newline_ix);
14914                }
14915                last_newline_ix = Some(*newline_ix);
14916
14917                if let Some(rows_left) = &mut max_message_rows {
14918                    if *rows_left == 0 {
14919                        break;
14920                    } else {
14921                        *rows_left -= 1;
14922                    }
14923                }
14924                let _ = newline_indices.next();
14925            } else {
14926                break;
14927            }
14928        }
14929        let prev_len = text_without_backticks.len();
14930        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14931        text_without_backticks.push_str(new_text);
14932        if in_code_block {
14933            code_ranges.push(prev_len..text_without_backticks.len());
14934        }
14935        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14936        in_code_block = !in_code_block;
14937        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14938            text_without_backticks.push_str("...");
14939            break;
14940        }
14941    }
14942
14943    (text_without_backticks.into(), code_ranges)
14944}
14945
14946fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14947    match severity {
14948        DiagnosticSeverity::ERROR => colors.error,
14949        DiagnosticSeverity::WARNING => colors.warning,
14950        DiagnosticSeverity::INFORMATION => colors.info,
14951        DiagnosticSeverity::HINT => colors.info,
14952        _ => colors.ignored,
14953    }
14954}
14955
14956pub fn styled_runs_for_code_label<'a>(
14957    label: &'a CodeLabel,
14958    syntax_theme: &'a theme::SyntaxTheme,
14959) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14960    let fade_out = HighlightStyle {
14961        fade_out: Some(0.35),
14962        ..Default::default()
14963    };
14964
14965    let mut prev_end = label.filter_range.end;
14966    label
14967        .runs
14968        .iter()
14969        .enumerate()
14970        .flat_map(move |(ix, (range, highlight_id))| {
14971            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14972                style
14973            } else {
14974                return Default::default();
14975            };
14976            let mut muted_style = style;
14977            muted_style.highlight(fade_out);
14978
14979            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14980            if range.start >= label.filter_range.end {
14981                if range.start > prev_end {
14982                    runs.push((prev_end..range.start, fade_out));
14983                }
14984                runs.push((range.clone(), muted_style));
14985            } else if range.end <= label.filter_range.end {
14986                runs.push((range.clone(), style));
14987            } else {
14988                runs.push((range.start..label.filter_range.end, style));
14989                runs.push((label.filter_range.end..range.end, muted_style));
14990            }
14991            prev_end = cmp::max(prev_end, range.end);
14992
14993            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14994                runs.push((prev_end..label.text.len(), fade_out));
14995            }
14996
14997            runs
14998        })
14999}
15000
15001pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15002    let mut prev_index = 0;
15003    let mut prev_codepoint: Option<char> = None;
15004    text.char_indices()
15005        .chain([(text.len(), '\0')])
15006        .filter_map(move |(index, codepoint)| {
15007            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15008            let is_boundary = index == text.len()
15009                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15010                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15011            if is_boundary {
15012                let chunk = &text[prev_index..index];
15013                prev_index = index;
15014                Some(chunk)
15015            } else {
15016                None
15017            }
15018        })
15019}
15020
15021pub trait RangeToAnchorExt: Sized {
15022    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15023
15024    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15025        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15026        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15027    }
15028}
15029
15030impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15031    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15032        let start_offset = self.start.to_offset(snapshot);
15033        let end_offset = self.end.to_offset(snapshot);
15034        if start_offset == end_offset {
15035            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15036        } else {
15037            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15038        }
15039    }
15040}
15041
15042pub trait RowExt {
15043    fn as_f32(&self) -> f32;
15044
15045    fn next_row(&self) -> Self;
15046
15047    fn previous_row(&self) -> Self;
15048
15049    fn minus(&self, other: Self) -> u32;
15050}
15051
15052impl RowExt for DisplayRow {
15053    fn as_f32(&self) -> f32 {
15054        self.0 as f32
15055    }
15056
15057    fn next_row(&self) -> Self {
15058        Self(self.0 + 1)
15059    }
15060
15061    fn previous_row(&self) -> Self {
15062        Self(self.0.saturating_sub(1))
15063    }
15064
15065    fn minus(&self, other: Self) -> u32 {
15066        self.0 - other.0
15067    }
15068}
15069
15070impl RowExt for MultiBufferRow {
15071    fn as_f32(&self) -> f32 {
15072        self.0 as f32
15073    }
15074
15075    fn next_row(&self) -> Self {
15076        Self(self.0 + 1)
15077    }
15078
15079    fn previous_row(&self) -> Self {
15080        Self(self.0.saturating_sub(1))
15081    }
15082
15083    fn minus(&self, other: Self) -> u32 {
15084        self.0 - other.0
15085    }
15086}
15087
15088trait RowRangeExt {
15089    type Row;
15090
15091    fn len(&self) -> usize;
15092
15093    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15094}
15095
15096impl RowRangeExt for Range<MultiBufferRow> {
15097    type Row = MultiBufferRow;
15098
15099    fn len(&self) -> usize {
15100        (self.end.0 - self.start.0) as usize
15101    }
15102
15103    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15104        (self.start.0..self.end.0).map(MultiBufferRow)
15105    }
15106}
15107
15108impl RowRangeExt for Range<DisplayRow> {
15109    type Row = DisplayRow;
15110
15111    fn len(&self) -> usize {
15112        (self.end.0 - self.start.0) as usize
15113    }
15114
15115    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15116        (self.start.0..self.end.0).map(DisplayRow)
15117    }
15118}
15119
15120fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15121    if hunk.diff_base_byte_range.is_empty() {
15122        DiffHunkStatus::Added
15123    } else if hunk.row_range.is_empty() {
15124        DiffHunkStatus::Removed
15125    } else {
15126        DiffHunkStatus::Modified
15127    }
15128}
15129
15130/// If select range has more than one line, we
15131/// just point the cursor to range.start.
15132fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15133    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15134        range
15135    } else {
15136        range.start..range.start
15137    }
15138}
15139
15140const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);