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)| {
 1040                StringMatchCandidate::new(
 1041                    id,
 1042                    completion.label.text[completion.label.filter_range.clone()].into(),
 1043                )
 1044            })
 1045            .collect();
 1046
 1047        Self {
 1048            id,
 1049            sort_completions,
 1050            initial_position,
 1051            buffer,
 1052            completions: Arc::new(RwLock::new(completions)),
 1053            match_candidates,
 1054            matches: Vec::new().into(),
 1055            selected_item: 0,
 1056            scroll_handle: UniformListScrollHandle::new(),
 1057            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1058                DebouncedDelay::new(),
 1059            ))),
 1060        }
 1061    }
 1062
 1063    fn new_snippet_choices(
 1064        id: CompletionId,
 1065        sort_completions: bool,
 1066        choices: &Vec<String>,
 1067        selection: Range<Anchor>,
 1068        buffer: Model<Buffer>,
 1069    ) -> Self {
 1070        let completions = choices
 1071            .iter()
 1072            .map(|choice| Completion {
 1073                old_range: selection.start.text_anchor..selection.end.text_anchor,
 1074                new_text: choice.to_string(),
 1075                label: CodeLabel {
 1076                    text: choice.to_string(),
 1077                    runs: Default::default(),
 1078                    filter_range: Default::default(),
 1079                },
 1080                server_id: LanguageServerId(usize::MAX),
 1081                documentation: None,
 1082                lsp_completion: Default::default(),
 1083                confirm: None,
 1084            })
 1085            .collect();
 1086
 1087        let match_candidates = choices
 1088            .iter()
 1089            .enumerate()
 1090            .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
 1091            .collect();
 1092        let matches = choices
 1093            .iter()
 1094            .enumerate()
 1095            .map(|(id, completion)| StringMatch {
 1096                candidate_id: id,
 1097                score: 1.,
 1098                positions: vec![],
 1099                string: completion.clone(),
 1100            })
 1101            .collect();
 1102        Self {
 1103            id,
 1104            sort_completions,
 1105            initial_position: selection.start,
 1106            buffer,
 1107            completions: Arc::new(RwLock::new(completions)),
 1108            match_candidates,
 1109            matches,
 1110            selected_item: 0,
 1111            scroll_handle: UniformListScrollHandle::new(),
 1112            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1113                DebouncedDelay::new(),
 1114            ))),
 1115        }
 1116    }
 1117
 1118    fn suppress_documentation_resolution(mut self) -> Self {
 1119        self.selected_completion_documentation_resolve_debounce
 1120            .take();
 1121        self
 1122    }
 1123
 1124    fn select_first(
 1125        &mut self,
 1126        provider: Option<&dyn CompletionProvider>,
 1127        cx: &mut ViewContext<Editor>,
 1128    ) {
 1129        self.selected_item = 0;
 1130        self.scroll_handle
 1131            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1132        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1133        cx.notify();
 1134    }
 1135
 1136    fn select_prev(
 1137        &mut self,
 1138        provider: Option<&dyn CompletionProvider>,
 1139        cx: &mut ViewContext<Editor>,
 1140    ) {
 1141        if self.selected_item > 0 {
 1142            self.selected_item -= 1;
 1143        } else {
 1144            self.selected_item = self.matches.len() - 1;
 1145        }
 1146        self.scroll_handle
 1147            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1148        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1149        cx.notify();
 1150    }
 1151
 1152    fn select_next(
 1153        &mut self,
 1154        provider: Option<&dyn CompletionProvider>,
 1155        cx: &mut ViewContext<Editor>,
 1156    ) {
 1157        if self.selected_item + 1 < self.matches.len() {
 1158            self.selected_item += 1;
 1159        } else {
 1160            self.selected_item = 0;
 1161        }
 1162        self.scroll_handle
 1163            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1164        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1165        cx.notify();
 1166    }
 1167
 1168    fn select_last(
 1169        &mut self,
 1170        provider: Option<&dyn CompletionProvider>,
 1171        cx: &mut ViewContext<Editor>,
 1172    ) {
 1173        self.selected_item = self.matches.len() - 1;
 1174        self.scroll_handle
 1175            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1176        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1177        cx.notify();
 1178    }
 1179
 1180    fn pre_resolve_completion_documentation(
 1181        buffer: Model<Buffer>,
 1182        completions: Arc<RwLock<Box<[Completion]>>>,
 1183        matches: Arc<[StringMatch]>,
 1184        editor: &Editor,
 1185        cx: &mut ViewContext<Editor>,
 1186    ) -> Task<()> {
 1187        let settings = EditorSettings::get_global(cx);
 1188        if !settings.show_completion_documentation {
 1189            return Task::ready(());
 1190        }
 1191
 1192        let Some(provider) = editor.completion_provider.as_ref() else {
 1193            return Task::ready(());
 1194        };
 1195
 1196        let resolve_task = provider.resolve_completions(
 1197            buffer,
 1198            matches.iter().map(|m| m.candidate_id).collect(),
 1199            completions.clone(),
 1200            cx,
 1201        );
 1202
 1203        cx.spawn(move |this, mut cx| async move {
 1204            if let Some(true) = resolve_task.await.log_err() {
 1205                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1206            }
 1207        })
 1208    }
 1209
 1210    fn attempt_resolve_selected_completion_documentation(
 1211        &mut self,
 1212        provider: Option<&dyn CompletionProvider>,
 1213        cx: &mut ViewContext<Editor>,
 1214    ) {
 1215        let settings = EditorSettings::get_global(cx);
 1216        if !settings.show_completion_documentation {
 1217            return;
 1218        }
 1219
 1220        let completion_index = self.matches[self.selected_item].candidate_id;
 1221        let Some(provider) = provider else {
 1222            return;
 1223        };
 1224        let Some(documentation_resolve) = self
 1225            .selected_completion_documentation_resolve_debounce
 1226            .as_ref()
 1227        else {
 1228            return;
 1229        };
 1230
 1231        let resolve_task = provider.resolve_completions(
 1232            self.buffer.clone(),
 1233            vec![completion_index],
 1234            self.completions.clone(),
 1235            cx,
 1236        );
 1237
 1238        let delay_ms =
 1239            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1240        let delay = Duration::from_millis(delay_ms);
 1241
 1242        documentation_resolve.lock().fire_new(delay, cx, |_, cx| {
 1243            cx.spawn(move |this, mut cx| async move {
 1244                if let Some(true) = resolve_task.await.log_err() {
 1245                    this.update(&mut cx, |_, cx| cx.notify()).ok();
 1246                }
 1247            })
 1248        });
 1249    }
 1250
 1251    fn visible(&self) -> bool {
 1252        !self.matches.is_empty()
 1253    }
 1254
 1255    fn render(
 1256        &self,
 1257        style: &EditorStyle,
 1258        max_height: Pixels,
 1259        workspace: Option<WeakView<Workspace>>,
 1260        cx: &mut ViewContext<Editor>,
 1261    ) -> AnyElement {
 1262        let settings = EditorSettings::get_global(cx);
 1263        let show_completion_documentation = settings.show_completion_documentation;
 1264
 1265        let widest_completion_ix = self
 1266            .matches
 1267            .iter()
 1268            .enumerate()
 1269            .max_by_key(|(_, mat)| {
 1270                let completions = self.completions.read();
 1271                let completion = &completions[mat.candidate_id];
 1272                let documentation = &completion.documentation;
 1273
 1274                let mut len = completion.label.text.chars().count();
 1275                if let Some(Documentation::SingleLine(text)) = documentation {
 1276                    if show_completion_documentation {
 1277                        len += text.chars().count();
 1278                    }
 1279                }
 1280
 1281                len
 1282            })
 1283            .map(|(ix, _)| ix);
 1284
 1285        let completions = self.completions.clone();
 1286        let matches = self.matches.clone();
 1287        let selected_item = self.selected_item;
 1288        let style = style.clone();
 1289
 1290        let multiline_docs = if show_completion_documentation {
 1291            let mat = &self.matches[selected_item];
 1292            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1293                Some(Documentation::MultiLinePlainText(text)) => {
 1294                    Some(div().child(SharedString::from(text.clone())))
 1295                }
 1296                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1297                    Some(div().child(render_parsed_markdown(
 1298                        "completions_markdown",
 1299                        parsed,
 1300                        &style,
 1301                        workspace,
 1302                        cx,
 1303                    )))
 1304                }
 1305                _ => None,
 1306            };
 1307            multiline_docs.map(|div| {
 1308                div.id("multiline_docs")
 1309                    .max_h(max_height)
 1310                    .flex_1()
 1311                    .px_1p5()
 1312                    .py_1()
 1313                    .min_w(px(260.))
 1314                    .max_w(px(640.))
 1315                    .w(px(500.))
 1316                    .overflow_y_scroll()
 1317                    .occlude()
 1318            })
 1319        } else {
 1320            None
 1321        };
 1322
 1323        let list = uniform_list(
 1324            cx.view().clone(),
 1325            "completions",
 1326            matches.len(),
 1327            move |_editor, range, cx| {
 1328                let start_ix = range.start;
 1329                let completions_guard = completions.read();
 1330
 1331                matches[range]
 1332                    .iter()
 1333                    .enumerate()
 1334                    .map(|(ix, mat)| {
 1335                        let item_ix = start_ix + ix;
 1336                        let candidate_id = mat.candidate_id;
 1337                        let completion = &completions_guard[candidate_id];
 1338
 1339                        let documentation = if show_completion_documentation {
 1340                            &completion.documentation
 1341                        } else {
 1342                            &None
 1343                        };
 1344
 1345                        let highlights = gpui::combine_highlights(
 1346                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1347                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1348                                |(range, mut highlight)| {
 1349                                    // Ignore font weight for syntax highlighting, as we'll use it
 1350                                    // for fuzzy matches.
 1351                                    highlight.font_weight = None;
 1352
 1353                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1354                                        highlight.strikethrough = Some(StrikethroughStyle {
 1355                                            thickness: 1.0.into(),
 1356                                            ..Default::default()
 1357                                        });
 1358                                        highlight.color = Some(cx.theme().colors().text_muted);
 1359                                    }
 1360
 1361                                    (range, highlight)
 1362                                },
 1363                            ),
 1364                        );
 1365                        let completion_label = StyledText::new(completion.label.text.clone())
 1366                            .with_highlights(&style.text, highlights);
 1367                        let documentation_label =
 1368                            if let Some(Documentation::SingleLine(text)) = documentation {
 1369                                if text.trim().is_empty() {
 1370                                    None
 1371                                } else {
 1372                                    Some(
 1373                                        Label::new(text.clone())
 1374                                            .ml_4()
 1375                                            .size(LabelSize::Small)
 1376                                            .color(Color::Muted),
 1377                                    )
 1378                                }
 1379                            } else {
 1380                                None
 1381                            };
 1382
 1383                        let color_swatch = completion
 1384                            .color()
 1385                            .map(|color| div().size_4().bg(color).rounded_sm());
 1386
 1387                        div().min_w(px(220.)).max_w(px(540.)).child(
 1388                            ListItem::new(mat.candidate_id)
 1389                                .inset(true)
 1390                                .selected(item_ix == selected_item)
 1391                                .on_click(cx.listener(move |editor, _event, cx| {
 1392                                    cx.stop_propagation();
 1393                                    if let Some(task) = editor.confirm_completion(
 1394                                        &ConfirmCompletion {
 1395                                            item_ix: Some(item_ix),
 1396                                        },
 1397                                        cx,
 1398                                    ) {
 1399                                        task.detach_and_log_err(cx)
 1400                                    }
 1401                                }))
 1402                                .start_slot::<Div>(color_swatch)
 1403                                .child(h_flex().overflow_hidden().child(completion_label))
 1404                                .end_slot::<Label>(documentation_label),
 1405                        )
 1406                    })
 1407                    .collect()
 1408            },
 1409        )
 1410        .occlude()
 1411        .max_h(max_height)
 1412        .track_scroll(self.scroll_handle.clone())
 1413        .with_width_from_item(widest_completion_ix)
 1414        .with_sizing_behavior(ListSizingBehavior::Infer);
 1415
 1416        Popover::new()
 1417            .child(list)
 1418            .when_some(multiline_docs, |popover, multiline_docs| {
 1419                popover.aside(multiline_docs)
 1420            })
 1421            .into_any_element()
 1422    }
 1423
 1424    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1425        let mut matches = if let Some(query) = query {
 1426            fuzzy::match_strings(
 1427                &self.match_candidates,
 1428                query,
 1429                query.chars().any(|c| c.is_uppercase()),
 1430                100,
 1431                &Default::default(),
 1432                executor,
 1433            )
 1434            .await
 1435        } else {
 1436            self.match_candidates
 1437                .iter()
 1438                .enumerate()
 1439                .map(|(candidate_id, candidate)| StringMatch {
 1440                    candidate_id,
 1441                    score: Default::default(),
 1442                    positions: Default::default(),
 1443                    string: candidate.string.clone(),
 1444                })
 1445                .collect()
 1446        };
 1447
 1448        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1449        if let Some(query) = query {
 1450            if let Some(query_start) = query.chars().next() {
 1451                matches.retain(|string_match| {
 1452                    split_words(&string_match.string).any(|word| {
 1453                        // Check that the first codepoint of the word as lowercase matches the first
 1454                        // codepoint of the query as lowercase
 1455                        word.chars()
 1456                            .flat_map(|codepoint| codepoint.to_lowercase())
 1457                            .zip(query_start.to_lowercase())
 1458                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1459                    })
 1460                });
 1461            }
 1462        }
 1463
 1464        let completions = self.completions.read();
 1465        if self.sort_completions {
 1466            matches.sort_unstable_by_key(|mat| {
 1467                // We do want to strike a balance here between what the language server tells us
 1468                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1469                // `Creat` and there is a local variable called `CreateComponent`).
 1470                // So what we do is: we bucket all matches into two buckets
 1471                // - Strong matches
 1472                // - Weak matches
 1473                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1474                // and the Weak matches are the rest.
 1475                //
 1476                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1477                // matches, we prefer language-server sort_text first.
 1478                //
 1479                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1480                // Rest of the matches(weak) can be sorted as language-server expects.
 1481
 1482                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1483                enum MatchScore<'a> {
 1484                    Strong {
 1485                        score: Reverse<OrderedFloat<f64>>,
 1486                        sort_text: Option<&'a str>,
 1487                        sort_key: (usize, &'a str),
 1488                    },
 1489                    Weak {
 1490                        sort_text: Option<&'a str>,
 1491                        score: Reverse<OrderedFloat<f64>>,
 1492                        sort_key: (usize, &'a str),
 1493                    },
 1494                }
 1495
 1496                let completion = &completions[mat.candidate_id];
 1497                let sort_key = completion.sort_key();
 1498                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1499                let score = Reverse(OrderedFloat(mat.score));
 1500
 1501                if mat.score >= 0.2 {
 1502                    MatchScore::Strong {
 1503                        score,
 1504                        sort_text,
 1505                        sort_key,
 1506                    }
 1507                } else {
 1508                    MatchScore::Weak {
 1509                        sort_text,
 1510                        score,
 1511                        sort_key,
 1512                    }
 1513                }
 1514            });
 1515        }
 1516
 1517        for mat in &mut matches {
 1518            let completion = &completions[mat.candidate_id];
 1519            mat.string.clone_from(&completion.label.text);
 1520            for position in &mut mat.positions {
 1521                *position += completion.label.filter_range.start;
 1522            }
 1523        }
 1524        drop(completions);
 1525
 1526        self.matches = matches.into();
 1527        self.selected_item = 0;
 1528    }
 1529}
 1530
 1531#[derive(Clone)]
 1532struct AvailableCodeAction {
 1533    excerpt_id: ExcerptId,
 1534    action: CodeAction,
 1535    provider: Arc<dyn CodeActionProvider>,
 1536}
 1537
 1538#[derive(Clone)]
 1539struct CodeActionContents {
 1540    tasks: Option<Arc<ResolvedTasks>>,
 1541    actions: Option<Arc<[AvailableCodeAction]>>,
 1542}
 1543
 1544impl CodeActionContents {
 1545    fn len(&self) -> usize {
 1546        match (&self.tasks, &self.actions) {
 1547            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1548            (Some(tasks), None) => tasks.templates.len(),
 1549            (None, Some(actions)) => actions.len(),
 1550            (None, None) => 0,
 1551        }
 1552    }
 1553
 1554    fn is_empty(&self) -> bool {
 1555        match (&self.tasks, &self.actions) {
 1556            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1557            (Some(tasks), None) => tasks.templates.is_empty(),
 1558            (None, Some(actions)) => actions.is_empty(),
 1559            (None, None) => true,
 1560        }
 1561    }
 1562
 1563    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1564        self.tasks
 1565            .iter()
 1566            .flat_map(|tasks| {
 1567                tasks
 1568                    .templates
 1569                    .iter()
 1570                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1571            })
 1572            .chain(self.actions.iter().flat_map(|actions| {
 1573                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1574                    excerpt_id: available.excerpt_id,
 1575                    action: available.action.clone(),
 1576                    provider: available.provider.clone(),
 1577                })
 1578            }))
 1579    }
 1580    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1581        match (&self.tasks, &self.actions) {
 1582            (Some(tasks), Some(actions)) => {
 1583                if index < tasks.templates.len() {
 1584                    tasks
 1585                        .templates
 1586                        .get(index)
 1587                        .cloned()
 1588                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1589                } else {
 1590                    actions.get(index - tasks.templates.len()).map(|available| {
 1591                        CodeActionsItem::CodeAction {
 1592                            excerpt_id: available.excerpt_id,
 1593                            action: available.action.clone(),
 1594                            provider: available.provider.clone(),
 1595                        }
 1596                    })
 1597                }
 1598            }
 1599            (Some(tasks), None) => tasks
 1600                .templates
 1601                .get(index)
 1602                .cloned()
 1603                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1604            (None, Some(actions)) => {
 1605                actions
 1606                    .get(index)
 1607                    .map(|available| CodeActionsItem::CodeAction {
 1608                        excerpt_id: available.excerpt_id,
 1609                        action: available.action.clone(),
 1610                        provider: available.provider.clone(),
 1611                    })
 1612            }
 1613            (None, None) => None,
 1614        }
 1615    }
 1616}
 1617
 1618#[allow(clippy::large_enum_variant)]
 1619#[derive(Clone)]
 1620enum CodeActionsItem {
 1621    Task(TaskSourceKind, ResolvedTask),
 1622    CodeAction {
 1623        excerpt_id: ExcerptId,
 1624        action: CodeAction,
 1625        provider: Arc<dyn CodeActionProvider>,
 1626    },
 1627}
 1628
 1629impl CodeActionsItem {
 1630    fn as_task(&self) -> Option<&ResolvedTask> {
 1631        let Self::Task(_, task) = self else {
 1632            return None;
 1633        };
 1634        Some(task)
 1635    }
 1636    fn as_code_action(&self) -> Option<&CodeAction> {
 1637        let Self::CodeAction { action, .. } = self else {
 1638            return None;
 1639        };
 1640        Some(action)
 1641    }
 1642    fn label(&self) -> String {
 1643        match self {
 1644            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1645            Self::Task(_, task) => task.resolved_label.clone(),
 1646        }
 1647    }
 1648}
 1649
 1650struct CodeActionsMenu {
 1651    actions: CodeActionContents,
 1652    buffer: Model<Buffer>,
 1653    selected_item: usize,
 1654    scroll_handle: UniformListScrollHandle,
 1655    deployed_from_indicator: Option<DisplayRow>,
 1656}
 1657
 1658impl CodeActionsMenu {
 1659    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1660        self.selected_item = 0;
 1661        self.scroll_handle
 1662            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1663        cx.notify()
 1664    }
 1665
 1666    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1667        if self.selected_item > 0 {
 1668            self.selected_item -= 1;
 1669        } else {
 1670            self.selected_item = self.actions.len() - 1;
 1671        }
 1672        self.scroll_handle
 1673            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1674        cx.notify();
 1675    }
 1676
 1677    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1678        if self.selected_item + 1 < self.actions.len() {
 1679            self.selected_item += 1;
 1680        } else {
 1681            self.selected_item = 0;
 1682        }
 1683        self.scroll_handle
 1684            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1685        cx.notify();
 1686    }
 1687
 1688    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1689        self.selected_item = self.actions.len() - 1;
 1690        self.scroll_handle
 1691            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1692        cx.notify()
 1693    }
 1694
 1695    fn visible(&self) -> bool {
 1696        !self.actions.is_empty()
 1697    }
 1698
 1699    fn render(
 1700        &self,
 1701        cursor_position: DisplayPoint,
 1702        _style: &EditorStyle,
 1703        max_height: Pixels,
 1704        cx: &mut ViewContext<Editor>,
 1705    ) -> (ContextMenuOrigin, AnyElement) {
 1706        let actions = self.actions.clone();
 1707        let selected_item = self.selected_item;
 1708        let element = uniform_list(
 1709            cx.view().clone(),
 1710            "code_actions_menu",
 1711            self.actions.len(),
 1712            move |_this, range, cx| {
 1713                actions
 1714                    .iter()
 1715                    .skip(range.start)
 1716                    .take(range.end - range.start)
 1717                    .enumerate()
 1718                    .map(|(ix, action)| {
 1719                        let item_ix = range.start + ix;
 1720                        let selected = selected_item == item_ix;
 1721                        let colors = cx.theme().colors();
 1722                        div()
 1723                            .px_1()
 1724                            .rounded_md()
 1725                            .text_color(colors.text)
 1726                            .when(selected, |style| {
 1727                                style
 1728                                    .bg(colors.element_active)
 1729                                    .text_color(colors.text_accent)
 1730                            })
 1731                            .hover(|style| {
 1732                                style
 1733                                    .bg(colors.element_hover)
 1734                                    .text_color(colors.text_accent)
 1735                            })
 1736                            .whitespace_nowrap()
 1737                            .when_some(action.as_code_action(), |this, action| {
 1738                                this.on_mouse_down(
 1739                                    MouseButton::Left,
 1740                                    cx.listener(move |editor, _, cx| {
 1741                                        cx.stop_propagation();
 1742                                        if let Some(task) = editor.confirm_code_action(
 1743                                            &ConfirmCodeAction {
 1744                                                item_ix: Some(item_ix),
 1745                                            },
 1746                                            cx,
 1747                                        ) {
 1748                                            task.detach_and_log_err(cx)
 1749                                        }
 1750                                    }),
 1751                                )
 1752                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1753                                .child(SharedString::from(action.lsp_action.title.clone()))
 1754                            })
 1755                            .when_some(action.as_task(), |this, task| {
 1756                                this.on_mouse_down(
 1757                                    MouseButton::Left,
 1758                                    cx.listener(move |editor, _, cx| {
 1759                                        cx.stop_propagation();
 1760                                        if let Some(task) = editor.confirm_code_action(
 1761                                            &ConfirmCodeAction {
 1762                                                item_ix: Some(item_ix),
 1763                                            },
 1764                                            cx,
 1765                                        ) {
 1766                                            task.detach_and_log_err(cx)
 1767                                        }
 1768                                    }),
 1769                                )
 1770                                .child(SharedString::from(task.resolved_label.clone()))
 1771                            })
 1772                    })
 1773                    .collect()
 1774            },
 1775        )
 1776        .elevation_1(cx)
 1777        .p_1()
 1778        .max_h(max_height)
 1779        .occlude()
 1780        .track_scroll(self.scroll_handle.clone())
 1781        .with_width_from_item(
 1782            self.actions
 1783                .iter()
 1784                .enumerate()
 1785                .max_by_key(|(_, action)| match action {
 1786                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1787                    CodeActionsItem::CodeAction { action, .. } => {
 1788                        action.lsp_action.title.chars().count()
 1789                    }
 1790                })
 1791                .map(|(ix, _)| ix),
 1792        )
 1793        .with_sizing_behavior(ListSizingBehavior::Infer)
 1794        .into_any_element();
 1795
 1796        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1797            ContextMenuOrigin::GutterIndicator(row)
 1798        } else {
 1799            ContextMenuOrigin::EditorPoint(cursor_position)
 1800        };
 1801
 1802        (cursor_position, element)
 1803    }
 1804}
 1805
 1806#[derive(Debug)]
 1807struct ActiveDiagnosticGroup {
 1808    primary_range: Range<Anchor>,
 1809    primary_message: String,
 1810    group_id: usize,
 1811    blocks: HashMap<CustomBlockId, Diagnostic>,
 1812    is_valid: bool,
 1813}
 1814
 1815#[derive(Serialize, Deserialize, Clone, Debug)]
 1816pub struct ClipboardSelection {
 1817    pub len: usize,
 1818    pub is_entire_line: bool,
 1819    pub first_line_indent: u32,
 1820}
 1821
 1822#[derive(Debug)]
 1823pub(crate) struct NavigationData {
 1824    cursor_anchor: Anchor,
 1825    cursor_position: Point,
 1826    scroll_anchor: ScrollAnchor,
 1827    scroll_top_row: u32,
 1828}
 1829
 1830#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1831pub enum GotoDefinitionKind {
 1832    Symbol,
 1833    Declaration,
 1834    Type,
 1835    Implementation,
 1836}
 1837
 1838#[derive(Debug, Clone)]
 1839enum InlayHintRefreshReason {
 1840    Toggle(bool),
 1841    SettingsChange(InlayHintSettings),
 1842    NewLinesShown,
 1843    BufferEdited(HashSet<Arc<Language>>),
 1844    RefreshRequested,
 1845    ExcerptsRemoved(Vec<ExcerptId>),
 1846}
 1847
 1848impl InlayHintRefreshReason {
 1849    fn description(&self) -> &'static str {
 1850        match self {
 1851            Self::Toggle(_) => "toggle",
 1852            Self::SettingsChange(_) => "settings change",
 1853            Self::NewLinesShown => "new lines shown",
 1854            Self::BufferEdited(_) => "buffer edited",
 1855            Self::RefreshRequested => "refresh requested",
 1856            Self::ExcerptsRemoved(_) => "excerpts removed",
 1857        }
 1858    }
 1859}
 1860
 1861pub(crate) struct FocusedBlock {
 1862    id: BlockId,
 1863    focus_handle: WeakFocusHandle,
 1864}
 1865
 1866#[derive(Clone)]
 1867struct JumpData {
 1868    excerpt_id: ExcerptId,
 1869    position: Point,
 1870    anchor: text::Anchor,
 1871    path: Option<project::ProjectPath>,
 1872    line_offset_from_top: u32,
 1873}
 1874
 1875impl Editor {
 1876    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1877        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1878        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1879        Self::new(
 1880            EditorMode::SingleLine { auto_width: false },
 1881            buffer,
 1882            None,
 1883            false,
 1884            cx,
 1885        )
 1886    }
 1887
 1888    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1889        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1890        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1891        Self::new(EditorMode::Full, buffer, None, false, cx)
 1892    }
 1893
 1894    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1895        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1896        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1897        Self::new(
 1898            EditorMode::SingleLine { auto_width: true },
 1899            buffer,
 1900            None,
 1901            false,
 1902            cx,
 1903        )
 1904    }
 1905
 1906    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1907        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1908        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1909        Self::new(
 1910            EditorMode::AutoHeight { max_lines },
 1911            buffer,
 1912            None,
 1913            false,
 1914            cx,
 1915        )
 1916    }
 1917
 1918    pub fn for_buffer(
 1919        buffer: Model<Buffer>,
 1920        project: Option<Model<Project>>,
 1921        cx: &mut ViewContext<Self>,
 1922    ) -> Self {
 1923        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1924        Self::new(EditorMode::Full, buffer, project, false, cx)
 1925    }
 1926
 1927    pub fn for_multibuffer(
 1928        buffer: Model<MultiBuffer>,
 1929        project: Option<Model<Project>>,
 1930        show_excerpt_controls: bool,
 1931        cx: &mut ViewContext<Self>,
 1932    ) -> Self {
 1933        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1934    }
 1935
 1936    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1937        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1938        let mut clone = Self::new(
 1939            self.mode,
 1940            self.buffer.clone(),
 1941            self.project.clone(),
 1942            show_excerpt_controls,
 1943            cx,
 1944        );
 1945        self.display_map.update(cx, |display_map, cx| {
 1946            let snapshot = display_map.snapshot(cx);
 1947            clone.display_map.update(cx, |display_map, cx| {
 1948                display_map.set_state(&snapshot, cx);
 1949            });
 1950        });
 1951        clone.selections.clone_state(&self.selections);
 1952        clone.scroll_manager.clone_state(&self.scroll_manager);
 1953        clone.searchable = self.searchable;
 1954        clone
 1955    }
 1956
 1957    pub fn new(
 1958        mode: EditorMode,
 1959        buffer: Model<MultiBuffer>,
 1960        project: Option<Model<Project>>,
 1961        show_excerpt_controls: bool,
 1962        cx: &mut ViewContext<Self>,
 1963    ) -> Self {
 1964        let style = cx.text_style();
 1965        let font_size = style.font_size.to_pixels(cx.rem_size());
 1966        let editor = cx.view().downgrade();
 1967        let fold_placeholder = FoldPlaceholder {
 1968            constrain_width: true,
 1969            render: Arc::new(move |fold_id, fold_range, cx| {
 1970                let editor = editor.clone();
 1971                div()
 1972                    .id(fold_id)
 1973                    .bg(cx.theme().colors().ghost_element_background)
 1974                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1975                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1976                    .rounded_sm()
 1977                    .size_full()
 1978                    .cursor_pointer()
 1979                    .child("")
 1980                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1981                    .on_click(move |_, cx| {
 1982                        editor
 1983                            .update(cx, |editor, cx| {
 1984                                editor.unfold_ranges(
 1985                                    &[fold_range.start..fold_range.end],
 1986                                    true,
 1987                                    false,
 1988                                    cx,
 1989                                );
 1990                                cx.stop_propagation();
 1991                            })
 1992                            .ok();
 1993                    })
 1994                    .into_any()
 1995            }),
 1996            merge_adjacent: true,
 1997            ..Default::default()
 1998        };
 1999        let display_map = cx.new_model(|cx| {
 2000            DisplayMap::new(
 2001                buffer.clone(),
 2002                style.font(),
 2003                font_size,
 2004                None,
 2005                show_excerpt_controls,
 2006                FILE_HEADER_HEIGHT,
 2007                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 2008                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 2009                fold_placeholder,
 2010                cx,
 2011            )
 2012        });
 2013
 2014        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 2015
 2016        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 2017
 2018        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 2019            .then(|| language_settings::SoftWrap::None);
 2020
 2021        let mut project_subscriptions = Vec::new();
 2022        if mode == EditorMode::Full {
 2023            if let Some(project) = project.as_ref() {
 2024                if buffer.read(cx).is_singleton() {
 2025                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 2026                        cx.emit(EditorEvent::TitleChanged);
 2027                    }));
 2028                }
 2029                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 2030                    if let project::Event::RefreshInlayHints = event {
 2031                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 2032                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 2033                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 2034                            let focus_handle = editor.focus_handle(cx);
 2035                            if focus_handle.is_focused(cx) {
 2036                                let snapshot = buffer.read(cx).snapshot();
 2037                                for (range, snippet) in snippet_edits {
 2038                                    let editor_range =
 2039                                        language::range_from_lsp(*range).to_offset(&snapshot);
 2040                                    editor
 2041                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 2042                                        .ok();
 2043                                }
 2044                            }
 2045                        }
 2046                    }
 2047                }));
 2048                if let Some(task_inventory) = project
 2049                    .read(cx)
 2050                    .task_store()
 2051                    .read(cx)
 2052                    .task_inventory()
 2053                    .cloned()
 2054                {
 2055                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 2056                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 2057                    }));
 2058                }
 2059            }
 2060        }
 2061
 2062        let inlay_hint_settings = inlay_hint_settings(
 2063            selections.newest_anchor().head(),
 2064            &buffer.read(cx).snapshot(cx),
 2065            cx,
 2066        );
 2067        let focus_handle = cx.focus_handle();
 2068        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 2069        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 2070            .detach();
 2071        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 2072            .detach();
 2073        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 2074
 2075        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 2076            Some(false)
 2077        } else {
 2078            None
 2079        };
 2080
 2081        let mut code_action_providers = Vec::new();
 2082        if let Some(project) = project.clone() {
 2083            code_action_providers.push(Arc::new(project) as Arc<_>);
 2084        }
 2085
 2086        let mut this = Self {
 2087            focus_handle,
 2088            show_cursor_when_unfocused: false,
 2089            last_focused_descendant: None,
 2090            buffer: buffer.clone(),
 2091            display_map: display_map.clone(),
 2092            selections,
 2093            scroll_manager: ScrollManager::new(cx),
 2094            columnar_selection_tail: None,
 2095            add_selections_state: None,
 2096            select_next_state: None,
 2097            select_prev_state: None,
 2098            selection_history: Default::default(),
 2099            autoclose_regions: Default::default(),
 2100            snippet_stack: Default::default(),
 2101            select_larger_syntax_node_stack: Vec::new(),
 2102            ime_transaction: Default::default(),
 2103            active_diagnostics: None,
 2104            soft_wrap_mode_override,
 2105            completion_provider: project.clone().map(|project| Box::new(project) as _),
 2106            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 2107            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 2108            project,
 2109            blink_manager: blink_manager.clone(),
 2110            show_local_selections: true,
 2111            mode,
 2112            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2113            show_gutter: mode == EditorMode::Full,
 2114            show_line_numbers: None,
 2115            use_relative_line_numbers: None,
 2116            show_git_diff_gutter: None,
 2117            show_code_actions: None,
 2118            show_runnables: None,
 2119            show_wrap_guides: None,
 2120            show_indent_guides,
 2121            placeholder_text: None,
 2122            highlight_order: 0,
 2123            highlighted_rows: HashMap::default(),
 2124            background_highlights: Default::default(),
 2125            gutter_highlights: TreeMap::default(),
 2126            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2127            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2128            nav_history: None,
 2129            context_menu: RwLock::new(None),
 2130            mouse_context_menu: None,
 2131            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2132            completion_tasks: Default::default(),
 2133            signature_help_state: SignatureHelpState::default(),
 2134            auto_signature_help: None,
 2135            find_all_references_task_sources: Vec::new(),
 2136            next_completion_id: 0,
 2137            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2138            next_inlay_id: 0,
 2139            code_action_providers,
 2140            available_code_actions: Default::default(),
 2141            code_actions_task: Default::default(),
 2142            document_highlights_task: Default::default(),
 2143            linked_editing_range_task: Default::default(),
 2144            pending_rename: Default::default(),
 2145            searchable: true,
 2146            cursor_shape: EditorSettings::get_global(cx)
 2147                .cursor_shape
 2148                .unwrap_or_default(),
 2149            current_line_highlight: None,
 2150            autoindent_mode: Some(AutoindentMode::EachLine),
 2151            collapse_matches: false,
 2152            workspace: None,
 2153            input_enabled: true,
 2154            use_modal_editing: mode == EditorMode::Full,
 2155            read_only: false,
 2156            use_autoclose: true,
 2157            use_auto_surround: true,
 2158            auto_replace_emoji_shortcode: false,
 2159            leader_peer_id: None,
 2160            remote_id: None,
 2161            hover_state: Default::default(),
 2162            hovered_link_state: Default::default(),
 2163            inline_completion_provider: None,
 2164            active_inline_completion: None,
 2165            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2166            expanded_hunks: ExpandedHunks::default(),
 2167            gutter_hovered: false,
 2168            pixel_position_of_newest_cursor: None,
 2169            last_bounds: None,
 2170            expect_bounds_change: None,
 2171            gutter_dimensions: GutterDimensions::default(),
 2172            style: None,
 2173            show_cursor_names: false,
 2174            hovered_cursors: Default::default(),
 2175            next_editor_action_id: EditorActionId::default(),
 2176            editor_actions: Rc::default(),
 2177            show_inline_completions_override: None,
 2178            enable_inline_completions: true,
 2179            custom_context_menu: None,
 2180            show_git_blame_gutter: false,
 2181            show_git_blame_inline: false,
 2182            show_selection_menu: None,
 2183            show_git_blame_inline_delay_task: None,
 2184            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2185            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2186                .session
 2187                .restore_unsaved_buffers,
 2188            blame: None,
 2189            blame_subscription: None,
 2190            tasks: Default::default(),
 2191            _subscriptions: vec![
 2192                cx.observe(&buffer, Self::on_buffer_changed),
 2193                cx.subscribe(&buffer, Self::on_buffer_event),
 2194                cx.observe(&display_map, Self::on_display_map_changed),
 2195                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2196                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2197                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2198                cx.observe_window_activation(|editor, cx| {
 2199                    let active = cx.is_window_active();
 2200                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2201                        if active {
 2202                            blink_manager.enable(cx);
 2203                        } else {
 2204                            blink_manager.disable(cx);
 2205                        }
 2206                    });
 2207                }),
 2208            ],
 2209            tasks_update_task: None,
 2210            linked_edit_ranges: Default::default(),
 2211            previous_search_ranges: None,
 2212            breadcrumb_header: None,
 2213            focused_block: None,
 2214            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2215            addons: HashMap::default(),
 2216            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2217            text_style_refinement: None,
 2218            active_line_trailer_provider: None,
 2219        };
 2220        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2221        this._subscriptions.extend(project_subscriptions);
 2222
 2223        this.end_selection(cx);
 2224        this.scroll_manager.show_scrollbar(cx);
 2225
 2226        if mode == EditorMode::Full {
 2227            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2228            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2229
 2230            if this.git_blame_inline_enabled {
 2231                this.git_blame_inline_enabled = true;
 2232                this.start_git_blame_inline(false, cx);
 2233            }
 2234        }
 2235
 2236        this.report_editor_event("open", None, cx);
 2237        this
 2238    }
 2239
 2240    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2241        self.mouse_context_menu
 2242            .as_ref()
 2243            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2244    }
 2245
 2246    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2247        let mut key_context = KeyContext::new_with_defaults();
 2248        key_context.add("Editor");
 2249        let mode = match self.mode {
 2250            EditorMode::SingleLine { .. } => "single_line",
 2251            EditorMode::AutoHeight { .. } => "auto_height",
 2252            EditorMode::Full => "full",
 2253        };
 2254
 2255        if EditorSettings::jupyter_enabled(cx) {
 2256            key_context.add("jupyter");
 2257        }
 2258
 2259        key_context.set("mode", mode);
 2260        if self.pending_rename.is_some() {
 2261            key_context.add("renaming");
 2262        }
 2263        if self.context_menu_visible() {
 2264            match self.context_menu.read().as_ref() {
 2265                Some(ContextMenu::Completions(_)) => {
 2266                    key_context.add("menu");
 2267                    key_context.add("showing_completions")
 2268                }
 2269                Some(ContextMenu::CodeActions(_)) => {
 2270                    key_context.add("menu");
 2271                    key_context.add("showing_code_actions")
 2272                }
 2273                None => {}
 2274            }
 2275        }
 2276
 2277        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2278        if !self.focus_handle(cx).contains_focused(cx)
 2279            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2280        {
 2281            for addon in self.addons.values() {
 2282                addon.extend_key_context(&mut key_context, cx)
 2283            }
 2284        }
 2285
 2286        if let Some(extension) = self
 2287            .buffer
 2288            .read(cx)
 2289            .as_singleton()
 2290            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2291        {
 2292            key_context.set("extension", extension.to_string());
 2293        }
 2294
 2295        if self.has_active_inline_completion(cx) {
 2296            key_context.add("copilot_suggestion");
 2297            key_context.add("inline_completion");
 2298        }
 2299
 2300        key_context
 2301    }
 2302
 2303    pub fn new_file(
 2304        workspace: &mut Workspace,
 2305        _: &workspace::NewFile,
 2306        cx: &mut ViewContext<Workspace>,
 2307    ) {
 2308        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2309            "Failed to create buffer",
 2310            cx,
 2311            |e, _| match e.error_code() {
 2312                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2313                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2314                e.error_tag("required").unwrap_or("the latest version")
 2315            )),
 2316                _ => None,
 2317            },
 2318        );
 2319    }
 2320
 2321    pub fn new_in_workspace(
 2322        workspace: &mut Workspace,
 2323        cx: &mut ViewContext<Workspace>,
 2324    ) -> Task<Result<View<Editor>>> {
 2325        let project = workspace.project().clone();
 2326        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2327
 2328        cx.spawn(|workspace, mut cx| async move {
 2329            let buffer = create.await?;
 2330            workspace.update(&mut cx, |workspace, cx| {
 2331                let editor =
 2332                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2333                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2334                editor
 2335            })
 2336        })
 2337    }
 2338
 2339    fn new_file_vertical(
 2340        workspace: &mut Workspace,
 2341        _: &workspace::NewFileSplitVertical,
 2342        cx: &mut ViewContext<Workspace>,
 2343    ) {
 2344        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2345    }
 2346
 2347    fn new_file_horizontal(
 2348        workspace: &mut Workspace,
 2349        _: &workspace::NewFileSplitHorizontal,
 2350        cx: &mut ViewContext<Workspace>,
 2351    ) {
 2352        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2353    }
 2354
 2355    fn new_file_in_direction(
 2356        workspace: &mut Workspace,
 2357        direction: SplitDirection,
 2358        cx: &mut ViewContext<Workspace>,
 2359    ) {
 2360        let project = workspace.project().clone();
 2361        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2362
 2363        cx.spawn(|workspace, mut cx| async move {
 2364            let buffer = create.await?;
 2365            workspace.update(&mut cx, move |workspace, cx| {
 2366                workspace.split_item(
 2367                    direction,
 2368                    Box::new(
 2369                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2370                    ),
 2371                    cx,
 2372                )
 2373            })?;
 2374            anyhow::Ok(())
 2375        })
 2376        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2377            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2378                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2379                e.error_tag("required").unwrap_or("the latest version")
 2380            )),
 2381            _ => None,
 2382        });
 2383    }
 2384
 2385    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2386        self.leader_peer_id
 2387    }
 2388
 2389    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2390        &self.buffer
 2391    }
 2392
 2393    pub fn workspace(&self) -> Option<View<Workspace>> {
 2394        self.workspace.as_ref()?.0.upgrade()
 2395    }
 2396
 2397    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2398        self.buffer().read(cx).title(cx)
 2399    }
 2400
 2401    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2402        let git_blame_gutter_max_author_length = self
 2403            .render_git_blame_gutter(cx)
 2404            .then(|| {
 2405                if let Some(blame) = self.blame.as_ref() {
 2406                    let max_author_length =
 2407                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2408                    Some(max_author_length)
 2409                } else {
 2410                    None
 2411                }
 2412            })
 2413            .flatten();
 2414
 2415        EditorSnapshot {
 2416            mode: self.mode,
 2417            show_gutter: self.show_gutter,
 2418            show_line_numbers: self.show_line_numbers,
 2419            show_git_diff_gutter: self.show_git_diff_gutter,
 2420            show_code_actions: self.show_code_actions,
 2421            show_runnables: self.show_runnables,
 2422            git_blame_gutter_max_author_length,
 2423            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2424            scroll_anchor: self.scroll_manager.anchor(),
 2425            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2426            placeholder_text: self.placeholder_text.clone(),
 2427            is_focused: self.focus_handle.is_focused(cx),
 2428            current_line_highlight: self
 2429                .current_line_highlight
 2430                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2431            gutter_hovered: self.gutter_hovered,
 2432        }
 2433    }
 2434
 2435    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2436        self.buffer.read(cx).language_at(point, cx)
 2437    }
 2438
 2439    pub fn file_at<T: ToOffset>(
 2440        &self,
 2441        point: T,
 2442        cx: &AppContext,
 2443    ) -> Option<Arc<dyn language::File>> {
 2444        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2445    }
 2446
 2447    pub fn active_excerpt(
 2448        &self,
 2449        cx: &AppContext,
 2450    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2451        self.buffer
 2452            .read(cx)
 2453            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2454    }
 2455
 2456    pub fn mode(&self) -> EditorMode {
 2457        self.mode
 2458    }
 2459
 2460    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2461        self.collaboration_hub.as_deref()
 2462    }
 2463
 2464    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2465        self.collaboration_hub = Some(hub);
 2466    }
 2467
 2468    pub fn set_custom_context_menu(
 2469        &mut self,
 2470        f: impl 'static
 2471            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2472    ) {
 2473        self.custom_context_menu = Some(Box::new(f))
 2474    }
 2475
 2476    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2477        self.completion_provider = provider;
 2478    }
 2479
 2480    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2481        self.semantics_provider.clone()
 2482    }
 2483
 2484    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2485        self.semantics_provider = provider;
 2486    }
 2487
 2488    pub fn set_inline_completion_provider<T>(
 2489        &mut self,
 2490        provider: Option<Model<T>>,
 2491        cx: &mut ViewContext<Self>,
 2492    ) where
 2493        T: InlineCompletionProvider,
 2494    {
 2495        self.inline_completion_provider =
 2496            provider.map(|provider| RegisteredInlineCompletionProvider {
 2497                _subscription: cx.observe(&provider, |this, _, cx| {
 2498                    if this.focus_handle.is_focused(cx) {
 2499                        this.update_visible_inline_completion(cx);
 2500                    }
 2501                }),
 2502                provider: Arc::new(provider),
 2503            });
 2504        self.refresh_inline_completion(false, false, cx);
 2505    }
 2506
 2507    pub fn set_active_line_trailer_provider<T>(
 2508        &mut self,
 2509        provider: Option<T>,
 2510        _cx: &mut ViewContext<Self>,
 2511    ) where
 2512        T: ActiveLineTrailerProvider + 'static,
 2513    {
 2514        self.active_line_trailer_provider = provider.map(|provider| Box::new(provider) as Box<_>);
 2515    }
 2516
 2517    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2518        self.placeholder_text.as_deref()
 2519    }
 2520
 2521    pub fn set_placeholder_text(
 2522        &mut self,
 2523        placeholder_text: impl Into<Arc<str>>,
 2524        cx: &mut ViewContext<Self>,
 2525    ) {
 2526        let placeholder_text = Some(placeholder_text.into());
 2527        if self.placeholder_text != placeholder_text {
 2528            self.placeholder_text = placeholder_text;
 2529            cx.notify();
 2530        }
 2531    }
 2532
 2533    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2534        self.cursor_shape = cursor_shape;
 2535
 2536        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2537        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2538
 2539        cx.notify();
 2540    }
 2541
 2542    pub fn set_current_line_highlight(
 2543        &mut self,
 2544        current_line_highlight: Option<CurrentLineHighlight>,
 2545    ) {
 2546        self.current_line_highlight = current_line_highlight;
 2547    }
 2548
 2549    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2550        self.collapse_matches = collapse_matches;
 2551    }
 2552
 2553    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2554        if self.collapse_matches {
 2555            return range.start..range.start;
 2556        }
 2557        range.clone()
 2558    }
 2559
 2560    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2561        if self.display_map.read(cx).clip_at_line_ends != clip {
 2562            self.display_map
 2563                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2564        }
 2565    }
 2566
 2567    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2568        self.input_enabled = input_enabled;
 2569    }
 2570
 2571    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2572        self.enable_inline_completions = enabled;
 2573    }
 2574
 2575    pub fn set_autoindent(&mut self, autoindent: bool) {
 2576        if autoindent {
 2577            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2578        } else {
 2579            self.autoindent_mode = None;
 2580        }
 2581    }
 2582
 2583    pub fn read_only(&self, cx: &AppContext) -> bool {
 2584        self.read_only || self.buffer.read(cx).read_only()
 2585    }
 2586
 2587    pub fn set_read_only(&mut self, read_only: bool) {
 2588        self.read_only = read_only;
 2589    }
 2590
 2591    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2592        self.use_autoclose = autoclose;
 2593    }
 2594
 2595    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2596        self.use_auto_surround = auto_surround;
 2597    }
 2598
 2599    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2600        self.auto_replace_emoji_shortcode = auto_replace;
 2601    }
 2602
 2603    pub fn toggle_inline_completions(
 2604        &mut self,
 2605        _: &ToggleInlineCompletions,
 2606        cx: &mut ViewContext<Self>,
 2607    ) {
 2608        if self.show_inline_completions_override.is_some() {
 2609            self.set_show_inline_completions(None, cx);
 2610        } else {
 2611            let cursor = self.selections.newest_anchor().head();
 2612            if let Some((buffer, cursor_buffer_position)) =
 2613                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2614            {
 2615                let show_inline_completions =
 2616                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2617                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2618            }
 2619        }
 2620    }
 2621
 2622    pub fn set_show_inline_completions(
 2623        &mut self,
 2624        show_inline_completions: Option<bool>,
 2625        cx: &mut ViewContext<Self>,
 2626    ) {
 2627        self.show_inline_completions_override = show_inline_completions;
 2628        self.refresh_inline_completion(false, true, cx);
 2629    }
 2630
 2631    fn should_show_inline_completions(
 2632        &self,
 2633        buffer: &Model<Buffer>,
 2634        buffer_position: language::Anchor,
 2635        cx: &AppContext,
 2636    ) -> bool {
 2637        if !self.snippet_stack.is_empty() {
 2638            return false;
 2639        }
 2640
 2641        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2642            return false;
 2643        }
 2644
 2645        if let Some(provider) = self.inline_completion_provider() {
 2646            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2647                show_inline_completions
 2648            } else {
 2649                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2650            }
 2651        } else {
 2652            false
 2653        }
 2654    }
 2655
 2656    fn inline_completions_disabled_in_scope(
 2657        &self,
 2658        buffer: &Model<Buffer>,
 2659        buffer_position: language::Anchor,
 2660        cx: &AppContext,
 2661    ) -> bool {
 2662        let snapshot = buffer.read(cx).snapshot();
 2663        let settings = snapshot.settings_at(buffer_position, cx);
 2664
 2665        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2666            return false;
 2667        };
 2668
 2669        scope.override_name().map_or(false, |scope_name| {
 2670            settings
 2671                .inline_completions_disabled_in
 2672                .iter()
 2673                .any(|s| s == scope_name)
 2674        })
 2675    }
 2676
 2677    pub fn set_use_modal_editing(&mut self, to: bool) {
 2678        self.use_modal_editing = to;
 2679    }
 2680
 2681    pub fn use_modal_editing(&self) -> bool {
 2682        self.use_modal_editing
 2683    }
 2684
 2685    fn selections_did_change(
 2686        &mut self,
 2687        local: bool,
 2688        old_cursor_position: &Anchor,
 2689        show_completions: bool,
 2690        cx: &mut ViewContext<Self>,
 2691    ) {
 2692        cx.invalidate_character_coordinates();
 2693
 2694        // Copy selections to primary selection buffer
 2695        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2696        if local {
 2697            let selections = self.selections.all::<usize>(cx);
 2698            let buffer_handle = self.buffer.read(cx).read(cx);
 2699
 2700            let mut text = String::new();
 2701            for (index, selection) in selections.iter().enumerate() {
 2702                let text_for_selection = buffer_handle
 2703                    .text_for_range(selection.start..selection.end)
 2704                    .collect::<String>();
 2705
 2706                text.push_str(&text_for_selection);
 2707                if index != selections.len() - 1 {
 2708                    text.push('\n');
 2709                }
 2710            }
 2711
 2712            if !text.is_empty() {
 2713                cx.write_to_primary(ClipboardItem::new_string(text));
 2714            }
 2715        }
 2716
 2717        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2718            self.buffer.update(cx, |buffer, cx| {
 2719                buffer.set_active_selections(
 2720                    &self.selections.disjoint_anchors(),
 2721                    self.selections.line_mode,
 2722                    self.cursor_shape,
 2723                    cx,
 2724                )
 2725            });
 2726        }
 2727        let display_map = self
 2728            .display_map
 2729            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2730        let buffer = &display_map.buffer_snapshot;
 2731        self.add_selections_state = None;
 2732        self.select_next_state = None;
 2733        self.select_prev_state = None;
 2734        self.select_larger_syntax_node_stack.clear();
 2735        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2736        self.snippet_stack
 2737            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2738        self.take_rename(false, cx);
 2739
 2740        let new_cursor_position = self.selections.newest_anchor().head();
 2741
 2742        self.push_to_nav_history(
 2743            *old_cursor_position,
 2744            Some(new_cursor_position.to_point(buffer)),
 2745            cx,
 2746        );
 2747
 2748        if local {
 2749            let new_cursor_position = self.selections.newest_anchor().head();
 2750            let mut context_menu = self.context_menu.write();
 2751            let completion_menu = match context_menu.as_ref() {
 2752                Some(ContextMenu::Completions(menu)) => Some(menu),
 2753
 2754                _ => {
 2755                    *context_menu = None;
 2756                    None
 2757                }
 2758            };
 2759
 2760            if let Some(completion_menu) = completion_menu {
 2761                let cursor_position = new_cursor_position.to_offset(buffer);
 2762                let (word_range, kind) =
 2763                    buffer.surrounding_word(completion_menu.initial_position, true);
 2764                if kind == Some(CharKind::Word)
 2765                    && word_range.to_inclusive().contains(&cursor_position)
 2766                {
 2767                    let mut completion_menu = completion_menu.clone();
 2768                    drop(context_menu);
 2769
 2770                    let query = Self::completion_query(buffer, cursor_position);
 2771                    cx.spawn(move |this, mut cx| async move {
 2772                        completion_menu
 2773                            .filter(query.as_deref(), cx.background_executor().clone())
 2774                            .await;
 2775
 2776                        this.update(&mut cx, |this, cx| {
 2777                            let mut context_menu = this.context_menu.write();
 2778                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2779                                return;
 2780                            };
 2781
 2782                            if menu.id > completion_menu.id {
 2783                                return;
 2784                            }
 2785
 2786                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2787                            drop(context_menu);
 2788                            cx.notify();
 2789                        })
 2790                    })
 2791                    .detach();
 2792
 2793                    if show_completions {
 2794                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2795                    }
 2796                } else {
 2797                    drop(context_menu);
 2798                    self.hide_context_menu(cx);
 2799                }
 2800            } else {
 2801                drop(context_menu);
 2802            }
 2803
 2804            hide_hover(self, cx);
 2805
 2806            if old_cursor_position.to_display_point(&display_map).row()
 2807                != new_cursor_position.to_display_point(&display_map).row()
 2808            {
 2809                self.available_code_actions.take();
 2810            }
 2811            self.refresh_code_actions(cx);
 2812            self.refresh_document_highlights(cx);
 2813            refresh_matching_bracket_highlights(self, cx);
 2814            self.discard_inline_completion(false, cx);
 2815            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2816            if self.git_blame_inline_enabled {
 2817                self.start_inline_blame_timer(cx);
 2818            }
 2819        }
 2820
 2821        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2822        cx.emit(EditorEvent::SelectionsChanged { local });
 2823
 2824        if self.selections.disjoint_anchors().len() == 1 {
 2825            cx.emit(SearchEvent::ActiveMatchChanged)
 2826        }
 2827        cx.notify();
 2828    }
 2829
 2830    pub fn change_selections<R>(
 2831        &mut self,
 2832        autoscroll: Option<Autoscroll>,
 2833        cx: &mut ViewContext<Self>,
 2834        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2835    ) -> R {
 2836        self.change_selections_inner(autoscroll, true, cx, change)
 2837    }
 2838
 2839    pub fn change_selections_inner<R>(
 2840        &mut self,
 2841        autoscroll: Option<Autoscroll>,
 2842        request_completions: bool,
 2843        cx: &mut ViewContext<Self>,
 2844        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2845    ) -> R {
 2846        let old_cursor_position = self.selections.newest_anchor().head();
 2847        self.push_to_selection_history();
 2848
 2849        let (changed, result) = self.selections.change_with(cx, change);
 2850
 2851        if changed {
 2852            if let Some(autoscroll) = autoscroll {
 2853                self.request_autoscroll(autoscroll, cx);
 2854            }
 2855            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2856
 2857            if self.should_open_signature_help_automatically(
 2858                &old_cursor_position,
 2859                self.signature_help_state.backspace_pressed(),
 2860                cx,
 2861            ) {
 2862                self.show_signature_help(&ShowSignatureHelp, cx);
 2863            }
 2864            self.signature_help_state.set_backspace_pressed(false);
 2865        }
 2866
 2867        result
 2868    }
 2869
 2870    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2871    where
 2872        I: IntoIterator<Item = (Range<S>, T)>,
 2873        S: ToOffset,
 2874        T: Into<Arc<str>>,
 2875    {
 2876        if self.read_only(cx) {
 2877            return;
 2878        }
 2879
 2880        self.buffer
 2881            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2882    }
 2883
 2884    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2885    where
 2886        I: IntoIterator<Item = (Range<S>, T)>,
 2887        S: ToOffset,
 2888        T: Into<Arc<str>>,
 2889    {
 2890        if self.read_only(cx) {
 2891            return;
 2892        }
 2893
 2894        self.buffer.update(cx, |buffer, cx| {
 2895            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2896        });
 2897    }
 2898
 2899    pub fn edit_with_block_indent<I, S, T>(
 2900        &mut self,
 2901        edits: I,
 2902        original_indent_columns: Vec<u32>,
 2903        cx: &mut ViewContext<Self>,
 2904    ) where
 2905        I: IntoIterator<Item = (Range<S>, T)>,
 2906        S: ToOffset,
 2907        T: Into<Arc<str>>,
 2908    {
 2909        if self.read_only(cx) {
 2910            return;
 2911        }
 2912
 2913        self.buffer.update(cx, |buffer, cx| {
 2914            buffer.edit(
 2915                edits,
 2916                Some(AutoindentMode::Block {
 2917                    original_indent_columns,
 2918                }),
 2919                cx,
 2920            )
 2921        });
 2922    }
 2923
 2924    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2925        self.hide_context_menu(cx);
 2926
 2927        match phase {
 2928            SelectPhase::Begin {
 2929                position,
 2930                add,
 2931                click_count,
 2932            } => self.begin_selection(position, add, click_count, cx),
 2933            SelectPhase::BeginColumnar {
 2934                position,
 2935                goal_column,
 2936                reset,
 2937            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2938            SelectPhase::Extend {
 2939                position,
 2940                click_count,
 2941            } => self.extend_selection(position, click_count, cx),
 2942            SelectPhase::Update {
 2943                position,
 2944                goal_column,
 2945                scroll_delta,
 2946            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2947            SelectPhase::End => self.end_selection(cx),
 2948        }
 2949    }
 2950
 2951    fn extend_selection(
 2952        &mut self,
 2953        position: DisplayPoint,
 2954        click_count: usize,
 2955        cx: &mut ViewContext<Self>,
 2956    ) {
 2957        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2958        let tail = self.selections.newest::<usize>(cx).tail();
 2959        self.begin_selection(position, false, click_count, cx);
 2960
 2961        let position = position.to_offset(&display_map, Bias::Left);
 2962        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2963
 2964        let mut pending_selection = self
 2965            .selections
 2966            .pending_anchor()
 2967            .expect("extend_selection not called with pending selection");
 2968        if position >= tail {
 2969            pending_selection.start = tail_anchor;
 2970        } else {
 2971            pending_selection.end = tail_anchor;
 2972            pending_selection.reversed = true;
 2973        }
 2974
 2975        let mut pending_mode = self.selections.pending_mode().unwrap();
 2976        match &mut pending_mode {
 2977            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2978            _ => {}
 2979        }
 2980
 2981        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2982            s.set_pending(pending_selection, pending_mode)
 2983        });
 2984    }
 2985
 2986    fn begin_selection(
 2987        &mut self,
 2988        position: DisplayPoint,
 2989        add: bool,
 2990        click_count: usize,
 2991        cx: &mut ViewContext<Self>,
 2992    ) {
 2993        if !self.focus_handle.is_focused(cx) {
 2994            self.last_focused_descendant = None;
 2995            cx.focus(&self.focus_handle);
 2996        }
 2997
 2998        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2999        let buffer = &display_map.buffer_snapshot;
 3000        let newest_selection = self.selections.newest_anchor().clone();
 3001        let position = display_map.clip_point(position, Bias::Left);
 3002
 3003        let start;
 3004        let end;
 3005        let mode;
 3006        let auto_scroll;
 3007        match click_count {
 3008            1 => {
 3009                start = buffer.anchor_before(position.to_point(&display_map));
 3010                end = start;
 3011                mode = SelectMode::Character;
 3012                auto_scroll = true;
 3013            }
 3014            2 => {
 3015                let range = movement::surrounding_word(&display_map, position);
 3016                start = buffer.anchor_before(range.start.to_point(&display_map));
 3017                end = buffer.anchor_before(range.end.to_point(&display_map));
 3018                mode = SelectMode::Word(start..end);
 3019                auto_scroll = true;
 3020            }
 3021            3 => {
 3022                let position = display_map
 3023                    .clip_point(position, Bias::Left)
 3024                    .to_point(&display_map);
 3025                let line_start = display_map.prev_line_boundary(position).0;
 3026                let next_line_start = buffer.clip_point(
 3027                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3028                    Bias::Left,
 3029                );
 3030                start = buffer.anchor_before(line_start);
 3031                end = buffer.anchor_before(next_line_start);
 3032                mode = SelectMode::Line(start..end);
 3033                auto_scroll = true;
 3034            }
 3035            _ => {
 3036                start = buffer.anchor_before(0);
 3037                end = buffer.anchor_before(buffer.len());
 3038                mode = SelectMode::All;
 3039                auto_scroll = false;
 3040            }
 3041        }
 3042
 3043        let point_to_delete: Option<usize> = {
 3044            let selected_points: Vec<Selection<Point>> =
 3045                self.selections.disjoint_in_range(start..end, cx);
 3046
 3047            if !add || click_count > 1 {
 3048                None
 3049            } else if !selected_points.is_empty() {
 3050                Some(selected_points[0].id)
 3051            } else {
 3052                let clicked_point_already_selected =
 3053                    self.selections.disjoint.iter().find(|selection| {
 3054                        selection.start.to_point(buffer) == start.to_point(buffer)
 3055                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3056                    });
 3057
 3058                clicked_point_already_selected.map(|selection| selection.id)
 3059            }
 3060        };
 3061
 3062        let selections_count = self.selections.count();
 3063
 3064        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 3065            if let Some(point_to_delete) = point_to_delete {
 3066                s.delete(point_to_delete);
 3067
 3068                if selections_count == 1 {
 3069                    s.set_pending_anchor_range(start..end, mode);
 3070                }
 3071            } else {
 3072                if !add {
 3073                    s.clear_disjoint();
 3074                } else if click_count > 1 {
 3075                    s.delete(newest_selection.id)
 3076                }
 3077
 3078                s.set_pending_anchor_range(start..end, mode);
 3079            }
 3080        });
 3081    }
 3082
 3083    fn begin_columnar_selection(
 3084        &mut self,
 3085        position: DisplayPoint,
 3086        goal_column: u32,
 3087        reset: bool,
 3088        cx: &mut ViewContext<Self>,
 3089    ) {
 3090        if !self.focus_handle.is_focused(cx) {
 3091            self.last_focused_descendant = None;
 3092            cx.focus(&self.focus_handle);
 3093        }
 3094
 3095        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3096
 3097        if reset {
 3098            let pointer_position = display_map
 3099                .buffer_snapshot
 3100                .anchor_before(position.to_point(&display_map));
 3101
 3102            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 3103                s.clear_disjoint();
 3104                s.set_pending_anchor_range(
 3105                    pointer_position..pointer_position,
 3106                    SelectMode::Character,
 3107                );
 3108            });
 3109        }
 3110
 3111        let tail = self.selections.newest::<Point>(cx).tail();
 3112        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3113
 3114        if !reset {
 3115            self.select_columns(
 3116                tail.to_display_point(&display_map),
 3117                position,
 3118                goal_column,
 3119                &display_map,
 3120                cx,
 3121            );
 3122        }
 3123    }
 3124
 3125    fn update_selection(
 3126        &mut self,
 3127        position: DisplayPoint,
 3128        goal_column: u32,
 3129        scroll_delta: gpui::Point<f32>,
 3130        cx: &mut ViewContext<Self>,
 3131    ) {
 3132        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3133
 3134        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3135            let tail = tail.to_display_point(&display_map);
 3136            self.select_columns(tail, position, goal_column, &display_map, cx);
 3137        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3138            let buffer = self.buffer.read(cx).snapshot(cx);
 3139            let head;
 3140            let tail;
 3141            let mode = self.selections.pending_mode().unwrap();
 3142            match &mode {
 3143                SelectMode::Character => {
 3144                    head = position.to_point(&display_map);
 3145                    tail = pending.tail().to_point(&buffer);
 3146                }
 3147                SelectMode::Word(original_range) => {
 3148                    let original_display_range = original_range.start.to_display_point(&display_map)
 3149                        ..original_range.end.to_display_point(&display_map);
 3150                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3151                        ..original_display_range.end.to_point(&display_map);
 3152                    if movement::is_inside_word(&display_map, position)
 3153                        || original_display_range.contains(&position)
 3154                    {
 3155                        let word_range = movement::surrounding_word(&display_map, position);
 3156                        if word_range.start < original_display_range.start {
 3157                            head = word_range.start.to_point(&display_map);
 3158                        } else {
 3159                            head = word_range.end.to_point(&display_map);
 3160                        }
 3161                    } else {
 3162                        head = position.to_point(&display_map);
 3163                    }
 3164
 3165                    if head <= original_buffer_range.start {
 3166                        tail = original_buffer_range.end;
 3167                    } else {
 3168                        tail = original_buffer_range.start;
 3169                    }
 3170                }
 3171                SelectMode::Line(original_range) => {
 3172                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3173
 3174                    let position = display_map
 3175                        .clip_point(position, Bias::Left)
 3176                        .to_point(&display_map);
 3177                    let line_start = display_map.prev_line_boundary(position).0;
 3178                    let next_line_start = buffer.clip_point(
 3179                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3180                        Bias::Left,
 3181                    );
 3182
 3183                    if line_start < original_range.start {
 3184                        head = line_start
 3185                    } else {
 3186                        head = next_line_start
 3187                    }
 3188
 3189                    if head <= original_range.start {
 3190                        tail = original_range.end;
 3191                    } else {
 3192                        tail = original_range.start;
 3193                    }
 3194                }
 3195                SelectMode::All => {
 3196                    return;
 3197                }
 3198            };
 3199
 3200            if head < tail {
 3201                pending.start = buffer.anchor_before(head);
 3202                pending.end = buffer.anchor_before(tail);
 3203                pending.reversed = true;
 3204            } else {
 3205                pending.start = buffer.anchor_before(tail);
 3206                pending.end = buffer.anchor_before(head);
 3207                pending.reversed = false;
 3208            }
 3209
 3210            self.change_selections(None, cx, |s| {
 3211                s.set_pending(pending, mode);
 3212            });
 3213        } else {
 3214            log::error!("update_selection dispatched with no pending selection");
 3215            return;
 3216        }
 3217
 3218        self.apply_scroll_delta(scroll_delta, cx);
 3219        cx.notify();
 3220    }
 3221
 3222    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3223        self.columnar_selection_tail.take();
 3224        if self.selections.pending_anchor().is_some() {
 3225            let selections = self.selections.all::<usize>(cx);
 3226            self.change_selections(None, cx, |s| {
 3227                s.select(selections);
 3228                s.clear_pending();
 3229            });
 3230        }
 3231    }
 3232
 3233    fn select_columns(
 3234        &mut self,
 3235        tail: DisplayPoint,
 3236        head: DisplayPoint,
 3237        goal_column: u32,
 3238        display_map: &DisplaySnapshot,
 3239        cx: &mut ViewContext<Self>,
 3240    ) {
 3241        let start_row = cmp::min(tail.row(), head.row());
 3242        let end_row = cmp::max(tail.row(), head.row());
 3243        let start_column = cmp::min(tail.column(), goal_column);
 3244        let end_column = cmp::max(tail.column(), goal_column);
 3245        let reversed = start_column < tail.column();
 3246
 3247        let selection_ranges = (start_row.0..=end_row.0)
 3248            .map(DisplayRow)
 3249            .filter_map(|row| {
 3250                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3251                    let start = display_map
 3252                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3253                        .to_point(display_map);
 3254                    let end = display_map
 3255                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3256                        .to_point(display_map);
 3257                    if reversed {
 3258                        Some(end..start)
 3259                    } else {
 3260                        Some(start..end)
 3261                    }
 3262                } else {
 3263                    None
 3264                }
 3265            })
 3266            .collect::<Vec<_>>();
 3267
 3268        self.change_selections(None, cx, |s| {
 3269            s.select_ranges(selection_ranges);
 3270        });
 3271        cx.notify();
 3272    }
 3273
 3274    pub fn has_pending_nonempty_selection(&self) -> bool {
 3275        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3276            Some(Selection { start, end, .. }) => start != end,
 3277            None => false,
 3278        };
 3279
 3280        pending_nonempty_selection
 3281            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3282    }
 3283
 3284    pub fn has_pending_selection(&self) -> bool {
 3285        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3286    }
 3287
 3288    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3289        if self.clear_expanded_diff_hunks(cx) {
 3290            cx.notify();
 3291            return;
 3292        }
 3293        if self.dismiss_menus_and_popups(true, cx) {
 3294            return;
 3295        }
 3296
 3297        if self.mode == EditorMode::Full
 3298            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3299        {
 3300            return;
 3301        }
 3302
 3303        cx.propagate();
 3304    }
 3305
 3306    pub fn dismiss_menus_and_popups(
 3307        &mut self,
 3308        should_report_inline_completion_event: bool,
 3309        cx: &mut ViewContext<Self>,
 3310    ) -> bool {
 3311        if self.take_rename(false, cx).is_some() {
 3312            return true;
 3313        }
 3314
 3315        if hide_hover(self, cx) {
 3316            return true;
 3317        }
 3318
 3319        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3320            return true;
 3321        }
 3322
 3323        if self.hide_context_menu(cx).is_some() {
 3324            return true;
 3325        }
 3326
 3327        if self.mouse_context_menu.take().is_some() {
 3328            return true;
 3329        }
 3330
 3331        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3332            return true;
 3333        }
 3334
 3335        if self.snippet_stack.pop().is_some() {
 3336            return true;
 3337        }
 3338
 3339        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3340            self.dismiss_diagnostics(cx);
 3341            return true;
 3342        }
 3343
 3344        false
 3345    }
 3346
 3347    fn linked_editing_ranges_for(
 3348        &self,
 3349        selection: Range<text::Anchor>,
 3350        cx: &AppContext,
 3351    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3352        if self.linked_edit_ranges.is_empty() {
 3353            return None;
 3354        }
 3355        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3356            selection.end.buffer_id.and_then(|end_buffer_id| {
 3357                if selection.start.buffer_id != Some(end_buffer_id) {
 3358                    return None;
 3359                }
 3360                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3361                let snapshot = buffer.read(cx).snapshot();
 3362                self.linked_edit_ranges
 3363                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3364                    .map(|ranges| (ranges, snapshot, buffer))
 3365            })?;
 3366        use text::ToOffset as TO;
 3367        // find offset from the start of current range to current cursor position
 3368        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3369
 3370        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3371        let start_difference = start_offset - start_byte_offset;
 3372        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3373        let end_difference = end_offset - start_byte_offset;
 3374        // Current range has associated linked ranges.
 3375        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3376        for range in linked_ranges.iter() {
 3377            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3378            let end_offset = start_offset + end_difference;
 3379            let start_offset = start_offset + start_difference;
 3380            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3381                continue;
 3382            }
 3383            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3384                if s.start.buffer_id != selection.start.buffer_id
 3385                    || s.end.buffer_id != selection.end.buffer_id
 3386                {
 3387                    return false;
 3388                }
 3389                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3390                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3391            }) {
 3392                continue;
 3393            }
 3394            let start = buffer_snapshot.anchor_after(start_offset);
 3395            let end = buffer_snapshot.anchor_after(end_offset);
 3396            linked_edits
 3397                .entry(buffer.clone())
 3398                .or_default()
 3399                .push(start..end);
 3400        }
 3401        Some(linked_edits)
 3402    }
 3403
 3404    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3405        let text: Arc<str> = text.into();
 3406
 3407        if self.read_only(cx) {
 3408            return;
 3409        }
 3410
 3411        let selections = self.selections.all_adjusted(cx);
 3412        let mut bracket_inserted = false;
 3413        let mut edits = Vec::new();
 3414        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3415        let mut new_selections = Vec::with_capacity(selections.len());
 3416        let mut new_autoclose_regions = Vec::new();
 3417        let snapshot = self.buffer.read(cx).read(cx);
 3418
 3419        for (selection, autoclose_region) in
 3420            self.selections_with_autoclose_regions(selections, &snapshot)
 3421        {
 3422            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3423                // Determine if the inserted text matches the opening or closing
 3424                // bracket of any of this language's bracket pairs.
 3425                let mut bracket_pair = None;
 3426                let mut is_bracket_pair_start = false;
 3427                let mut is_bracket_pair_end = false;
 3428                if !text.is_empty() {
 3429                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3430                    //  and they are removing the character that triggered IME popup.
 3431                    for (pair, enabled) in scope.brackets() {
 3432                        if !pair.close && !pair.surround {
 3433                            continue;
 3434                        }
 3435
 3436                        if enabled && pair.start.ends_with(text.as_ref()) {
 3437                            let prefix_len = pair.start.len() - text.len();
 3438                            let preceding_text_matches_prefix = prefix_len == 0
 3439                                || (selection.start.column >= (prefix_len as u32)
 3440                                    && snapshot.contains_str_at(
 3441                                        Point::new(
 3442                                            selection.start.row,
 3443                                            selection.start.column - (prefix_len as u32),
 3444                                        ),
 3445                                        &pair.start[..prefix_len],
 3446                                    ));
 3447                            if preceding_text_matches_prefix {
 3448                                bracket_pair = Some(pair.clone());
 3449                                is_bracket_pair_start = true;
 3450                                break;
 3451                            }
 3452                        }
 3453                        if pair.end.as_str() == text.as_ref() {
 3454                            bracket_pair = Some(pair.clone());
 3455                            is_bracket_pair_end = true;
 3456                            break;
 3457                        }
 3458                    }
 3459                }
 3460
 3461                if let Some(bracket_pair) = bracket_pair {
 3462                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3463                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3464                    let auto_surround =
 3465                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3466                    if selection.is_empty() {
 3467                        if is_bracket_pair_start {
 3468                            // If the inserted text is a suffix of an opening bracket and the
 3469                            // selection is preceded by the rest of the opening bracket, then
 3470                            // insert the closing bracket.
 3471                            let following_text_allows_autoclose = snapshot
 3472                                .chars_at(selection.start)
 3473                                .next()
 3474                                .map_or(true, |c| scope.should_autoclose_before(c));
 3475
 3476                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3477                                && bracket_pair.start.len() == 1
 3478                            {
 3479                                let target = bracket_pair.start.chars().next().unwrap();
 3480                                let current_line_count = snapshot
 3481                                    .reversed_chars_at(selection.start)
 3482                                    .take_while(|&c| c != '\n')
 3483                                    .filter(|&c| c == target)
 3484                                    .count();
 3485                                current_line_count % 2 == 1
 3486                            } else {
 3487                                false
 3488                            };
 3489
 3490                            if autoclose
 3491                                && bracket_pair.close
 3492                                && following_text_allows_autoclose
 3493                                && !is_closing_quote
 3494                            {
 3495                                let anchor = snapshot.anchor_before(selection.end);
 3496                                new_selections.push((selection.map(|_| anchor), text.len()));
 3497                                new_autoclose_regions.push((
 3498                                    anchor,
 3499                                    text.len(),
 3500                                    selection.id,
 3501                                    bracket_pair.clone(),
 3502                                ));
 3503                                edits.push((
 3504                                    selection.range(),
 3505                                    format!("{}{}", text, bracket_pair.end).into(),
 3506                                ));
 3507                                bracket_inserted = true;
 3508                                continue;
 3509                            }
 3510                        }
 3511
 3512                        if let Some(region) = autoclose_region {
 3513                            // If the selection is followed by an auto-inserted closing bracket,
 3514                            // then don't insert that closing bracket again; just move the selection
 3515                            // past the closing bracket.
 3516                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3517                                && text.as_ref() == region.pair.end.as_str();
 3518                            if should_skip {
 3519                                let anchor = snapshot.anchor_after(selection.end);
 3520                                new_selections
 3521                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3522                                continue;
 3523                            }
 3524                        }
 3525
 3526                        let always_treat_brackets_as_autoclosed = snapshot
 3527                            .settings_at(selection.start, cx)
 3528                            .always_treat_brackets_as_autoclosed;
 3529                        if always_treat_brackets_as_autoclosed
 3530                            && is_bracket_pair_end
 3531                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3532                        {
 3533                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3534                            // and the inserted text is a closing bracket and the selection is followed
 3535                            // by the closing bracket then move the selection past the closing bracket.
 3536                            let anchor = snapshot.anchor_after(selection.end);
 3537                            new_selections.push((selection.map(|_| anchor), text.len()));
 3538                            continue;
 3539                        }
 3540                    }
 3541                    // If an opening bracket is 1 character long and is typed while
 3542                    // text is selected, then surround that text with the bracket pair.
 3543                    else if auto_surround
 3544                        && bracket_pair.surround
 3545                        && is_bracket_pair_start
 3546                        && bracket_pair.start.chars().count() == 1
 3547                    {
 3548                        edits.push((selection.start..selection.start, text.clone()));
 3549                        edits.push((
 3550                            selection.end..selection.end,
 3551                            bracket_pair.end.as_str().into(),
 3552                        ));
 3553                        bracket_inserted = true;
 3554                        new_selections.push((
 3555                            Selection {
 3556                                id: selection.id,
 3557                                start: snapshot.anchor_after(selection.start),
 3558                                end: snapshot.anchor_before(selection.end),
 3559                                reversed: selection.reversed,
 3560                                goal: selection.goal,
 3561                            },
 3562                            0,
 3563                        ));
 3564                        continue;
 3565                    }
 3566                }
 3567            }
 3568
 3569            if self.auto_replace_emoji_shortcode
 3570                && selection.is_empty()
 3571                && text.as_ref().ends_with(':')
 3572            {
 3573                if let Some(possible_emoji_short_code) =
 3574                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3575                {
 3576                    if !possible_emoji_short_code.is_empty() {
 3577                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3578                            let emoji_shortcode_start = Point::new(
 3579                                selection.start.row,
 3580                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3581                            );
 3582
 3583                            // Remove shortcode from buffer
 3584                            edits.push((
 3585                                emoji_shortcode_start..selection.start,
 3586                                "".to_string().into(),
 3587                            ));
 3588                            new_selections.push((
 3589                                Selection {
 3590                                    id: selection.id,
 3591                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3592                                    end: snapshot.anchor_before(selection.start),
 3593                                    reversed: selection.reversed,
 3594                                    goal: selection.goal,
 3595                                },
 3596                                0,
 3597                            ));
 3598
 3599                            // Insert emoji
 3600                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3601                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3602                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3603
 3604                            continue;
 3605                        }
 3606                    }
 3607                }
 3608            }
 3609
 3610            // If not handling any auto-close operation, then just replace the selected
 3611            // text with the given input and move the selection to the end of the
 3612            // newly inserted text.
 3613            let anchor = snapshot.anchor_after(selection.end);
 3614            if !self.linked_edit_ranges.is_empty() {
 3615                let start_anchor = snapshot.anchor_before(selection.start);
 3616
 3617                let is_word_char = text.chars().next().map_or(true, |char| {
 3618                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3619                    classifier.is_word(char)
 3620                });
 3621
 3622                if is_word_char {
 3623                    if let Some(ranges) = self
 3624                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3625                    {
 3626                        for (buffer, edits) in ranges {
 3627                            linked_edits
 3628                                .entry(buffer.clone())
 3629                                .or_default()
 3630                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3631                        }
 3632                    }
 3633                }
 3634            }
 3635
 3636            new_selections.push((selection.map(|_| anchor), 0));
 3637            edits.push((selection.start..selection.end, text.clone()));
 3638        }
 3639
 3640        drop(snapshot);
 3641
 3642        self.transact(cx, |this, cx| {
 3643            this.buffer.update(cx, |buffer, cx| {
 3644                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3645            });
 3646            for (buffer, edits) in linked_edits {
 3647                buffer.update(cx, |buffer, cx| {
 3648                    let snapshot = buffer.snapshot();
 3649                    let edits = edits
 3650                        .into_iter()
 3651                        .map(|(range, text)| {
 3652                            use text::ToPoint as TP;
 3653                            let end_point = TP::to_point(&range.end, &snapshot);
 3654                            let start_point = TP::to_point(&range.start, &snapshot);
 3655                            (start_point..end_point, text)
 3656                        })
 3657                        .sorted_by_key(|(range, _)| range.start)
 3658                        .collect::<Vec<_>>();
 3659                    buffer.edit(edits, None, cx);
 3660                })
 3661            }
 3662            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3663            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3664            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3665            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3666                .zip(new_selection_deltas)
 3667                .map(|(selection, delta)| Selection {
 3668                    id: selection.id,
 3669                    start: selection.start + delta,
 3670                    end: selection.end + delta,
 3671                    reversed: selection.reversed,
 3672                    goal: SelectionGoal::None,
 3673                })
 3674                .collect::<Vec<_>>();
 3675
 3676            let mut i = 0;
 3677            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3678                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3679                let start = map.buffer_snapshot.anchor_before(position);
 3680                let end = map.buffer_snapshot.anchor_after(position);
 3681                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3682                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3683                        Ordering::Less => i += 1,
 3684                        Ordering::Greater => break,
 3685                        Ordering::Equal => {
 3686                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3687                                Ordering::Less => i += 1,
 3688                                Ordering::Equal => break,
 3689                                Ordering::Greater => break,
 3690                            }
 3691                        }
 3692                    }
 3693                }
 3694                this.autoclose_regions.insert(
 3695                    i,
 3696                    AutocloseRegion {
 3697                        selection_id,
 3698                        range: start..end,
 3699                        pair,
 3700                    },
 3701                );
 3702            }
 3703
 3704            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3705            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3706                s.select(new_selections)
 3707            });
 3708
 3709            if !bracket_inserted {
 3710                if let Some(on_type_format_task) =
 3711                    this.trigger_on_type_formatting(text.to_string(), cx)
 3712                {
 3713                    on_type_format_task.detach_and_log_err(cx);
 3714                }
 3715            }
 3716
 3717            let editor_settings = EditorSettings::get_global(cx);
 3718            if bracket_inserted
 3719                && (editor_settings.auto_signature_help
 3720                    || editor_settings.show_signature_help_after_edits)
 3721            {
 3722                this.show_signature_help(&ShowSignatureHelp, cx);
 3723            }
 3724
 3725            let trigger_in_words = !had_active_inline_completion;
 3726            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3727            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3728            this.refresh_inline_completion(true, false, cx);
 3729        });
 3730    }
 3731
 3732    fn find_possible_emoji_shortcode_at_position(
 3733        snapshot: &MultiBufferSnapshot,
 3734        position: Point,
 3735    ) -> Option<String> {
 3736        let mut chars = Vec::new();
 3737        let mut found_colon = false;
 3738        for char in snapshot.reversed_chars_at(position).take(100) {
 3739            // Found a possible emoji shortcode in the middle of the buffer
 3740            if found_colon {
 3741                if char.is_whitespace() {
 3742                    chars.reverse();
 3743                    return Some(chars.iter().collect());
 3744                }
 3745                // If the previous character is not a whitespace, we are in the middle of a word
 3746                // and we only want to complete the shortcode if the word is made up of other emojis
 3747                let mut containing_word = String::new();
 3748                for ch in snapshot
 3749                    .reversed_chars_at(position)
 3750                    .skip(chars.len() + 1)
 3751                    .take(100)
 3752                {
 3753                    if ch.is_whitespace() {
 3754                        break;
 3755                    }
 3756                    containing_word.push(ch);
 3757                }
 3758                let containing_word = containing_word.chars().rev().collect::<String>();
 3759                if util::word_consists_of_emojis(containing_word.as_str()) {
 3760                    chars.reverse();
 3761                    return Some(chars.iter().collect());
 3762                }
 3763            }
 3764
 3765            if char.is_whitespace() || !char.is_ascii() {
 3766                return None;
 3767            }
 3768            if char == ':' {
 3769                found_colon = true;
 3770            } else {
 3771                chars.push(char);
 3772            }
 3773        }
 3774        // Found a possible emoji shortcode at the beginning of the buffer
 3775        chars.reverse();
 3776        Some(chars.iter().collect())
 3777    }
 3778
 3779    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3780        self.transact(cx, |this, cx| {
 3781            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3782                let selections = this.selections.all::<usize>(cx);
 3783                let multi_buffer = this.buffer.read(cx);
 3784                let buffer = multi_buffer.snapshot(cx);
 3785                selections
 3786                    .iter()
 3787                    .map(|selection| {
 3788                        let start_point = selection.start.to_point(&buffer);
 3789                        let mut indent =
 3790                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3791                        indent.len = cmp::min(indent.len, start_point.column);
 3792                        let start = selection.start;
 3793                        let end = selection.end;
 3794                        let selection_is_empty = start == end;
 3795                        let language_scope = buffer.language_scope_at(start);
 3796                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3797                            &language_scope
 3798                        {
 3799                            let leading_whitespace_len = buffer
 3800                                .reversed_chars_at(start)
 3801                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3802                                .map(|c| c.len_utf8())
 3803                                .sum::<usize>();
 3804
 3805                            let trailing_whitespace_len = buffer
 3806                                .chars_at(end)
 3807                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3808                                .map(|c| c.len_utf8())
 3809                                .sum::<usize>();
 3810
 3811                            let insert_extra_newline =
 3812                                language.brackets().any(|(pair, enabled)| {
 3813                                    let pair_start = pair.start.trim_end();
 3814                                    let pair_end = pair.end.trim_start();
 3815
 3816                                    enabled
 3817                                        && pair.newline
 3818                                        && buffer.contains_str_at(
 3819                                            end + trailing_whitespace_len,
 3820                                            pair_end,
 3821                                        )
 3822                                        && buffer.contains_str_at(
 3823                                            (start - leading_whitespace_len)
 3824                                                .saturating_sub(pair_start.len()),
 3825                                            pair_start,
 3826                                        )
 3827                                });
 3828
 3829                            // Comment extension on newline is allowed only for cursor selections
 3830                            let comment_delimiter = maybe!({
 3831                                if !selection_is_empty {
 3832                                    return None;
 3833                                }
 3834
 3835                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3836                                    return None;
 3837                                }
 3838
 3839                                let delimiters = language.line_comment_prefixes();
 3840                                let max_len_of_delimiter =
 3841                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3842                                let (snapshot, range) =
 3843                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3844
 3845                                let mut index_of_first_non_whitespace = 0;
 3846                                let comment_candidate = snapshot
 3847                                    .chars_for_range(range)
 3848                                    .skip_while(|c| {
 3849                                        let should_skip = c.is_whitespace();
 3850                                        if should_skip {
 3851                                            index_of_first_non_whitespace += 1;
 3852                                        }
 3853                                        should_skip
 3854                                    })
 3855                                    .take(max_len_of_delimiter)
 3856                                    .collect::<String>();
 3857                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3858                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3859                                })?;
 3860                                let cursor_is_placed_after_comment_marker =
 3861                                    index_of_first_non_whitespace + comment_prefix.len()
 3862                                        <= start_point.column as usize;
 3863                                if cursor_is_placed_after_comment_marker {
 3864                                    Some(comment_prefix.clone())
 3865                                } else {
 3866                                    None
 3867                                }
 3868                            });
 3869                            (comment_delimiter, insert_extra_newline)
 3870                        } else {
 3871                            (None, false)
 3872                        };
 3873
 3874                        let capacity_for_delimiter = comment_delimiter
 3875                            .as_deref()
 3876                            .map(str::len)
 3877                            .unwrap_or_default();
 3878                        let mut new_text =
 3879                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3880                        new_text.push('\n');
 3881                        new_text.extend(indent.chars());
 3882                        if let Some(delimiter) = &comment_delimiter {
 3883                            new_text.push_str(delimiter);
 3884                        }
 3885                        if insert_extra_newline {
 3886                            new_text = new_text.repeat(2);
 3887                        }
 3888
 3889                        let anchor = buffer.anchor_after(end);
 3890                        let new_selection = selection.map(|_| anchor);
 3891                        (
 3892                            (start..end, new_text),
 3893                            (insert_extra_newline, new_selection),
 3894                        )
 3895                    })
 3896                    .unzip()
 3897            };
 3898
 3899            this.edit_with_autoindent(edits, cx);
 3900            let buffer = this.buffer.read(cx).snapshot(cx);
 3901            let new_selections = selection_fixup_info
 3902                .into_iter()
 3903                .map(|(extra_newline_inserted, new_selection)| {
 3904                    let mut cursor = new_selection.end.to_point(&buffer);
 3905                    if extra_newline_inserted {
 3906                        cursor.row -= 1;
 3907                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3908                    }
 3909                    new_selection.map(|_| cursor)
 3910                })
 3911                .collect();
 3912
 3913            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3914            this.refresh_inline_completion(true, false, cx);
 3915        });
 3916    }
 3917
 3918    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3919        let buffer = self.buffer.read(cx);
 3920        let snapshot = buffer.snapshot(cx);
 3921
 3922        let mut edits = Vec::new();
 3923        let mut rows = Vec::new();
 3924
 3925        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3926            let cursor = selection.head();
 3927            let row = cursor.row;
 3928
 3929            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3930
 3931            let newline = "\n".to_string();
 3932            edits.push((start_of_line..start_of_line, newline));
 3933
 3934            rows.push(row + rows_inserted as u32);
 3935        }
 3936
 3937        self.transact(cx, |editor, cx| {
 3938            editor.edit(edits, cx);
 3939
 3940            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3941                let mut index = 0;
 3942                s.move_cursors_with(|map, _, _| {
 3943                    let row = rows[index];
 3944                    index += 1;
 3945
 3946                    let point = Point::new(row, 0);
 3947                    let boundary = map.next_line_boundary(point).1;
 3948                    let clipped = map.clip_point(boundary, Bias::Left);
 3949
 3950                    (clipped, SelectionGoal::None)
 3951                });
 3952            });
 3953
 3954            let mut indent_edits = Vec::new();
 3955            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3956            for row in rows {
 3957                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3958                for (row, indent) in indents {
 3959                    if indent.len == 0 {
 3960                        continue;
 3961                    }
 3962
 3963                    let text = match indent.kind {
 3964                        IndentKind::Space => " ".repeat(indent.len as usize),
 3965                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3966                    };
 3967                    let point = Point::new(row.0, 0);
 3968                    indent_edits.push((point..point, text));
 3969                }
 3970            }
 3971            editor.edit(indent_edits, cx);
 3972        });
 3973    }
 3974
 3975    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3976        let buffer = self.buffer.read(cx);
 3977        let snapshot = buffer.snapshot(cx);
 3978
 3979        let mut edits = Vec::new();
 3980        let mut rows = Vec::new();
 3981        let mut rows_inserted = 0;
 3982
 3983        for selection in self.selections.all_adjusted(cx) {
 3984            let cursor = selection.head();
 3985            let row = cursor.row;
 3986
 3987            let point = Point::new(row + 1, 0);
 3988            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3989
 3990            let newline = "\n".to_string();
 3991            edits.push((start_of_line..start_of_line, newline));
 3992
 3993            rows_inserted += 1;
 3994            rows.push(row + rows_inserted);
 3995        }
 3996
 3997        self.transact(cx, |editor, cx| {
 3998            editor.edit(edits, cx);
 3999
 4000            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4001                let mut index = 0;
 4002                s.move_cursors_with(|map, _, _| {
 4003                    let row = rows[index];
 4004                    index += 1;
 4005
 4006                    let point = Point::new(row, 0);
 4007                    let boundary = map.next_line_boundary(point).1;
 4008                    let clipped = map.clip_point(boundary, Bias::Left);
 4009
 4010                    (clipped, SelectionGoal::None)
 4011                });
 4012            });
 4013
 4014            let mut indent_edits = Vec::new();
 4015            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4016            for row in rows {
 4017                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4018                for (row, indent) in indents {
 4019                    if indent.len == 0 {
 4020                        continue;
 4021                    }
 4022
 4023                    let text = match indent.kind {
 4024                        IndentKind::Space => " ".repeat(indent.len as usize),
 4025                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4026                    };
 4027                    let point = Point::new(row.0, 0);
 4028                    indent_edits.push((point..point, text));
 4029                }
 4030            }
 4031            editor.edit(indent_edits, cx);
 4032        });
 4033    }
 4034
 4035    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 4036        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4037            original_indent_columns: Vec::new(),
 4038        });
 4039        self.insert_with_autoindent_mode(text, autoindent, cx);
 4040    }
 4041
 4042    fn insert_with_autoindent_mode(
 4043        &mut self,
 4044        text: &str,
 4045        autoindent_mode: Option<AutoindentMode>,
 4046        cx: &mut ViewContext<Self>,
 4047    ) {
 4048        if self.read_only(cx) {
 4049            return;
 4050        }
 4051
 4052        let text: Arc<str> = text.into();
 4053        self.transact(cx, |this, cx| {
 4054            let old_selections = this.selections.all_adjusted(cx);
 4055            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4056                let anchors = {
 4057                    let snapshot = buffer.read(cx);
 4058                    old_selections
 4059                        .iter()
 4060                        .map(|s| {
 4061                            let anchor = snapshot.anchor_after(s.head());
 4062                            s.map(|_| anchor)
 4063                        })
 4064                        .collect::<Vec<_>>()
 4065                };
 4066                buffer.edit(
 4067                    old_selections
 4068                        .iter()
 4069                        .map(|s| (s.start..s.end, text.clone())),
 4070                    autoindent_mode,
 4071                    cx,
 4072                );
 4073                anchors
 4074            });
 4075
 4076            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4077                s.select_anchors(selection_anchors);
 4078            })
 4079        });
 4080    }
 4081
 4082    fn trigger_completion_on_input(
 4083        &mut self,
 4084        text: &str,
 4085        trigger_in_words: bool,
 4086        cx: &mut ViewContext<Self>,
 4087    ) {
 4088        if self.is_completion_trigger(text, trigger_in_words, cx) {
 4089            self.show_completions(
 4090                &ShowCompletions {
 4091                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4092                },
 4093                cx,
 4094            );
 4095        } else {
 4096            self.hide_context_menu(cx);
 4097        }
 4098    }
 4099
 4100    fn is_completion_trigger(
 4101        &self,
 4102        text: &str,
 4103        trigger_in_words: bool,
 4104        cx: &mut ViewContext<Self>,
 4105    ) -> bool {
 4106        let position = self.selections.newest_anchor().head();
 4107        let multibuffer = self.buffer.read(cx);
 4108        let Some(buffer) = position
 4109            .buffer_id
 4110            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4111        else {
 4112            return false;
 4113        };
 4114
 4115        if let Some(completion_provider) = &self.completion_provider {
 4116            completion_provider.is_completion_trigger(
 4117                &buffer,
 4118                position.text_anchor,
 4119                text,
 4120                trigger_in_words,
 4121                cx,
 4122            )
 4123        } else {
 4124            false
 4125        }
 4126    }
 4127
 4128    /// If any empty selections is touching the start of its innermost containing autoclose
 4129    /// region, expand it to select the brackets.
 4130    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4131        let selections = self.selections.all::<usize>(cx);
 4132        let buffer = self.buffer.read(cx).read(cx);
 4133        let new_selections = self
 4134            .selections_with_autoclose_regions(selections, &buffer)
 4135            .map(|(mut selection, region)| {
 4136                if !selection.is_empty() {
 4137                    return selection;
 4138                }
 4139
 4140                if let Some(region) = region {
 4141                    let mut range = region.range.to_offset(&buffer);
 4142                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4143                        range.start -= region.pair.start.len();
 4144                        if buffer.contains_str_at(range.start, &region.pair.start)
 4145                            && buffer.contains_str_at(range.end, &region.pair.end)
 4146                        {
 4147                            range.end += region.pair.end.len();
 4148                            selection.start = range.start;
 4149                            selection.end = range.end;
 4150
 4151                            return selection;
 4152                        }
 4153                    }
 4154                }
 4155
 4156                let always_treat_brackets_as_autoclosed = buffer
 4157                    .settings_at(selection.start, cx)
 4158                    .always_treat_brackets_as_autoclosed;
 4159
 4160                if !always_treat_brackets_as_autoclosed {
 4161                    return selection;
 4162                }
 4163
 4164                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4165                    for (pair, enabled) in scope.brackets() {
 4166                        if !enabled || !pair.close {
 4167                            continue;
 4168                        }
 4169
 4170                        if buffer.contains_str_at(selection.start, &pair.end) {
 4171                            let pair_start_len = pair.start.len();
 4172                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 4173                            {
 4174                                selection.start -= pair_start_len;
 4175                                selection.end += pair.end.len();
 4176
 4177                                return selection;
 4178                            }
 4179                        }
 4180                    }
 4181                }
 4182
 4183                selection
 4184            })
 4185            .collect();
 4186
 4187        drop(buffer);
 4188        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4189    }
 4190
 4191    /// Iterate the given selections, and for each one, find the smallest surrounding
 4192    /// autoclose region. This uses the ordering of the selections and the autoclose
 4193    /// regions to avoid repeated comparisons.
 4194    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4195        &'a self,
 4196        selections: impl IntoIterator<Item = Selection<D>>,
 4197        buffer: &'a MultiBufferSnapshot,
 4198    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4199        let mut i = 0;
 4200        let mut regions = self.autoclose_regions.as_slice();
 4201        selections.into_iter().map(move |selection| {
 4202            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4203
 4204            let mut enclosing = None;
 4205            while let Some(pair_state) = regions.get(i) {
 4206                if pair_state.range.end.to_offset(buffer) < range.start {
 4207                    regions = &regions[i + 1..];
 4208                    i = 0;
 4209                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4210                    break;
 4211                } else {
 4212                    if pair_state.selection_id == selection.id {
 4213                        enclosing = Some(pair_state);
 4214                    }
 4215                    i += 1;
 4216                }
 4217            }
 4218
 4219            (selection, enclosing)
 4220        })
 4221    }
 4222
 4223    /// Remove any autoclose regions that no longer contain their selection.
 4224    fn invalidate_autoclose_regions(
 4225        &mut self,
 4226        mut selections: &[Selection<Anchor>],
 4227        buffer: &MultiBufferSnapshot,
 4228    ) {
 4229        self.autoclose_regions.retain(|state| {
 4230            let mut i = 0;
 4231            while let Some(selection) = selections.get(i) {
 4232                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4233                    selections = &selections[1..];
 4234                    continue;
 4235                }
 4236                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4237                    break;
 4238                }
 4239                if selection.id == state.selection_id {
 4240                    return true;
 4241                } else {
 4242                    i += 1;
 4243                }
 4244            }
 4245            false
 4246        });
 4247    }
 4248
 4249    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4250        let offset = position.to_offset(buffer);
 4251        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4252        if offset > word_range.start && kind == Some(CharKind::Word) {
 4253            Some(
 4254                buffer
 4255                    .text_for_range(word_range.start..offset)
 4256                    .collect::<String>(),
 4257            )
 4258        } else {
 4259            None
 4260        }
 4261    }
 4262
 4263    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4264        self.refresh_inlay_hints(
 4265            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4266            cx,
 4267        );
 4268    }
 4269
 4270    pub fn inlay_hints_enabled(&self) -> bool {
 4271        self.inlay_hint_cache.enabled
 4272    }
 4273
 4274    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4275        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4276            return;
 4277        }
 4278
 4279        let reason_description = reason.description();
 4280        let ignore_debounce = matches!(
 4281            reason,
 4282            InlayHintRefreshReason::SettingsChange(_)
 4283                | InlayHintRefreshReason::Toggle(_)
 4284                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4285        );
 4286        let (invalidate_cache, required_languages) = match reason {
 4287            InlayHintRefreshReason::Toggle(enabled) => {
 4288                self.inlay_hint_cache.enabled = enabled;
 4289                if enabled {
 4290                    (InvalidationStrategy::RefreshRequested, None)
 4291                } else {
 4292                    self.inlay_hint_cache.clear();
 4293                    self.splice_inlays(
 4294                        self.visible_inlay_hints(cx)
 4295                            .iter()
 4296                            .map(|inlay| inlay.id)
 4297                            .collect(),
 4298                        Vec::new(),
 4299                        cx,
 4300                    );
 4301                    return;
 4302                }
 4303            }
 4304            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4305                match self.inlay_hint_cache.update_settings(
 4306                    &self.buffer,
 4307                    new_settings,
 4308                    self.visible_inlay_hints(cx),
 4309                    cx,
 4310                ) {
 4311                    ControlFlow::Break(Some(InlaySplice {
 4312                        to_remove,
 4313                        to_insert,
 4314                    })) => {
 4315                        self.splice_inlays(to_remove, to_insert, cx);
 4316                        return;
 4317                    }
 4318                    ControlFlow::Break(None) => return,
 4319                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4320                }
 4321            }
 4322            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4323                if let Some(InlaySplice {
 4324                    to_remove,
 4325                    to_insert,
 4326                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4327                {
 4328                    self.splice_inlays(to_remove, to_insert, cx);
 4329                }
 4330                return;
 4331            }
 4332            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4333            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4334                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4335            }
 4336            InlayHintRefreshReason::RefreshRequested => {
 4337                (InvalidationStrategy::RefreshRequested, None)
 4338            }
 4339        };
 4340
 4341        if let Some(InlaySplice {
 4342            to_remove,
 4343            to_insert,
 4344        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4345            reason_description,
 4346            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4347            invalidate_cache,
 4348            ignore_debounce,
 4349            cx,
 4350        ) {
 4351            self.splice_inlays(to_remove, to_insert, cx);
 4352        }
 4353    }
 4354
 4355    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4356        self.display_map
 4357            .read(cx)
 4358            .current_inlays()
 4359            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4360            .cloned()
 4361            .collect()
 4362    }
 4363
 4364    pub fn excerpts_for_inlay_hints_query(
 4365        &self,
 4366        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4367        cx: &mut ViewContext<Editor>,
 4368    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4369        let Some(project) = self.project.as_ref() else {
 4370            return HashMap::default();
 4371        };
 4372        let project = project.read(cx);
 4373        let multi_buffer = self.buffer().read(cx);
 4374        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4375        let multi_buffer_visible_start = self
 4376            .scroll_manager
 4377            .anchor()
 4378            .anchor
 4379            .to_point(&multi_buffer_snapshot);
 4380        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4381            multi_buffer_visible_start
 4382                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4383            Bias::Left,
 4384        );
 4385        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4386        multi_buffer
 4387            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4388            .into_iter()
 4389            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4390            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4391                let buffer = buffer_handle.read(cx);
 4392                let buffer_file = project::File::from_dyn(buffer.file())?;
 4393                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4394                let worktree_entry = buffer_worktree
 4395                    .read(cx)
 4396                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4397                if worktree_entry.is_ignored {
 4398                    return None;
 4399                }
 4400
 4401                let language = buffer.language()?;
 4402                if let Some(restrict_to_languages) = restrict_to_languages {
 4403                    if !restrict_to_languages.contains(language) {
 4404                        return None;
 4405                    }
 4406                }
 4407                Some((
 4408                    excerpt_id,
 4409                    (
 4410                        buffer_handle,
 4411                        buffer.version().clone(),
 4412                        excerpt_visible_range,
 4413                    ),
 4414                ))
 4415            })
 4416            .collect()
 4417    }
 4418
 4419    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4420        TextLayoutDetails {
 4421            text_system: cx.text_system().clone(),
 4422            editor_style: self.style.clone().unwrap(),
 4423            rem_size: cx.rem_size(),
 4424            scroll_anchor: self.scroll_manager.anchor(),
 4425            visible_rows: self.visible_line_count(),
 4426            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4427        }
 4428    }
 4429
 4430    fn splice_inlays(
 4431        &self,
 4432        to_remove: Vec<InlayId>,
 4433        to_insert: Vec<Inlay>,
 4434        cx: &mut ViewContext<Self>,
 4435    ) {
 4436        self.display_map.update(cx, |display_map, cx| {
 4437            display_map.splice_inlays(to_remove, to_insert, cx);
 4438        });
 4439        cx.notify();
 4440    }
 4441
 4442    fn trigger_on_type_formatting(
 4443        &self,
 4444        input: String,
 4445        cx: &mut ViewContext<Self>,
 4446    ) -> Option<Task<Result<()>>> {
 4447        if input.len() != 1 {
 4448            return None;
 4449        }
 4450
 4451        let project = self.project.as_ref()?;
 4452        let position = self.selections.newest_anchor().head();
 4453        let (buffer, buffer_position) = self
 4454            .buffer
 4455            .read(cx)
 4456            .text_anchor_for_position(position, cx)?;
 4457
 4458        let settings = language_settings::language_settings(
 4459            buffer
 4460                .read(cx)
 4461                .language_at(buffer_position)
 4462                .map(|l| l.name()),
 4463            buffer.read(cx).file(),
 4464            cx,
 4465        );
 4466        if !settings.use_on_type_format {
 4467            return None;
 4468        }
 4469
 4470        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4471        // hence we do LSP request & edit on host side only — add formats to host's history.
 4472        let push_to_lsp_host_history = true;
 4473        // If this is not the host, append its history with new edits.
 4474        let push_to_client_history = project.read(cx).is_via_collab();
 4475
 4476        let on_type_formatting = project.update(cx, |project, cx| {
 4477            project.on_type_format(
 4478                buffer.clone(),
 4479                buffer_position,
 4480                input,
 4481                push_to_lsp_host_history,
 4482                cx,
 4483            )
 4484        });
 4485        Some(cx.spawn(|editor, mut cx| async move {
 4486            if let Some(transaction) = on_type_formatting.await? {
 4487                if push_to_client_history {
 4488                    buffer
 4489                        .update(&mut cx, |buffer, _| {
 4490                            buffer.push_transaction(transaction, Instant::now());
 4491                        })
 4492                        .ok();
 4493                }
 4494                editor.update(&mut cx, |editor, cx| {
 4495                    editor.refresh_document_highlights(cx);
 4496                })?;
 4497            }
 4498            Ok(())
 4499        }))
 4500    }
 4501
 4502    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4503        if self.pending_rename.is_some() {
 4504            return;
 4505        }
 4506
 4507        let Some(provider) = self.completion_provider.as_ref() else {
 4508            return;
 4509        };
 4510
 4511        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4512            return;
 4513        }
 4514
 4515        let position = self.selections.newest_anchor().head();
 4516        let (buffer, buffer_position) =
 4517            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4518                output
 4519            } else {
 4520                return;
 4521            };
 4522
 4523        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4524        let is_followup_invoke = {
 4525            let context_menu_state = self.context_menu.read();
 4526            matches!(
 4527                context_menu_state.deref(),
 4528                Some(ContextMenu::Completions(_))
 4529            )
 4530        };
 4531        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4532            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4533            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4534                CompletionTriggerKind::TRIGGER_CHARACTER
 4535            }
 4536
 4537            _ => CompletionTriggerKind::INVOKED,
 4538        };
 4539        let completion_context = CompletionContext {
 4540            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4541                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4542                    Some(String::from(trigger))
 4543                } else {
 4544                    None
 4545                }
 4546            }),
 4547            trigger_kind,
 4548        };
 4549        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4550        let sort_completions = provider.sort_completions();
 4551
 4552        let id = post_inc(&mut self.next_completion_id);
 4553        let task = cx.spawn(|this, mut cx| {
 4554            async move {
 4555                this.update(&mut cx, |this, _| {
 4556                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4557                })?;
 4558                let completions = completions.await.log_err();
 4559                let menu = if let Some(completions) = completions {
 4560                    let mut menu = CompletionsMenu::new(
 4561                        id,
 4562                        sort_completions,
 4563                        position,
 4564                        buffer.clone(),
 4565                        completions.into(),
 4566                    );
 4567                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4568                        .await;
 4569
 4570                    if menu.matches.is_empty() {
 4571                        None
 4572                    } else {
 4573                        this.update(&mut cx, |editor, cx| {
 4574                            let completions = menu.completions.clone();
 4575                            let matches = menu.matches.clone();
 4576
 4577                            let delay_ms = EditorSettings::get_global(cx)
 4578                                .completion_documentation_secondary_query_debounce;
 4579                            let delay = Duration::from_millis(delay_ms);
 4580                            editor
 4581                                .completion_documentation_pre_resolve_debounce
 4582                                .fire_new(delay, cx, |editor, cx| {
 4583                                    CompletionsMenu::pre_resolve_completion_documentation(
 4584                                        buffer,
 4585                                        completions,
 4586                                        matches,
 4587                                        editor,
 4588                                        cx,
 4589                                    )
 4590                                });
 4591                        })
 4592                        .ok();
 4593                        Some(menu)
 4594                    }
 4595                } else {
 4596                    None
 4597                };
 4598
 4599                this.update(&mut cx, |this, cx| {
 4600                    let mut context_menu = this.context_menu.write();
 4601                    match context_menu.as_ref() {
 4602                        None => {}
 4603
 4604                        Some(ContextMenu::Completions(prev_menu)) => {
 4605                            if prev_menu.id > id {
 4606                                return;
 4607                            }
 4608                        }
 4609
 4610                        _ => return,
 4611                    }
 4612
 4613                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4614                        let menu = menu.unwrap();
 4615                        *context_menu = Some(ContextMenu::Completions(menu));
 4616                        drop(context_menu);
 4617                        this.discard_inline_completion(false, cx);
 4618                        cx.notify();
 4619                    } else if this.completion_tasks.len() <= 1 {
 4620                        // If there are no more completion tasks and the last menu was
 4621                        // empty, we should hide it. If it was already hidden, we should
 4622                        // also show the copilot completion when available.
 4623                        drop(context_menu);
 4624                        if this.hide_context_menu(cx).is_none() {
 4625                            this.update_visible_inline_completion(cx);
 4626                        }
 4627                    }
 4628                })?;
 4629
 4630                Ok::<_, anyhow::Error>(())
 4631            }
 4632            .log_err()
 4633        });
 4634
 4635        self.completion_tasks.push((id, task));
 4636    }
 4637
 4638    pub fn confirm_completion(
 4639        &mut self,
 4640        action: &ConfirmCompletion,
 4641        cx: &mut ViewContext<Self>,
 4642    ) -> Option<Task<Result<()>>> {
 4643        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4644    }
 4645
 4646    pub fn compose_completion(
 4647        &mut self,
 4648        action: &ComposeCompletion,
 4649        cx: &mut ViewContext<Self>,
 4650    ) -> Option<Task<Result<()>>> {
 4651        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4652    }
 4653
 4654    fn do_completion(
 4655        &mut self,
 4656        item_ix: Option<usize>,
 4657        intent: CompletionIntent,
 4658        cx: &mut ViewContext<Editor>,
 4659    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4660        use language::ToOffset as _;
 4661
 4662        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4663            menu
 4664        } else {
 4665            return None;
 4666        };
 4667
 4668        let mat = completions_menu
 4669            .matches
 4670            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4671        let buffer_handle = completions_menu.buffer;
 4672        let completions = completions_menu.completions.read();
 4673        let completion = completions.get(mat.candidate_id)?;
 4674        cx.stop_propagation();
 4675
 4676        let snippet;
 4677        let text;
 4678
 4679        if completion.is_snippet() {
 4680            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4681            text = snippet.as_ref().unwrap().text.clone();
 4682        } else {
 4683            snippet = None;
 4684            text = completion.new_text.clone();
 4685        };
 4686        let selections = self.selections.all::<usize>(cx);
 4687        let buffer = buffer_handle.read(cx);
 4688        let old_range = completion.old_range.to_offset(buffer);
 4689        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4690
 4691        let newest_selection = self.selections.newest_anchor();
 4692        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4693            return None;
 4694        }
 4695
 4696        let lookbehind = newest_selection
 4697            .start
 4698            .text_anchor
 4699            .to_offset(buffer)
 4700            .saturating_sub(old_range.start);
 4701        let lookahead = old_range
 4702            .end
 4703            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4704        let mut common_prefix_len = old_text
 4705            .bytes()
 4706            .zip(text.bytes())
 4707            .take_while(|(a, b)| a == b)
 4708            .count();
 4709
 4710        let snapshot = self.buffer.read(cx).snapshot(cx);
 4711        let mut range_to_replace: Option<Range<isize>> = None;
 4712        let mut ranges = Vec::new();
 4713        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4714        for selection in &selections {
 4715            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4716                let start = selection.start.saturating_sub(lookbehind);
 4717                let end = selection.end + lookahead;
 4718                if selection.id == newest_selection.id {
 4719                    range_to_replace = Some(
 4720                        ((start + common_prefix_len) as isize - selection.start as isize)
 4721                            ..(end as isize - selection.start as isize),
 4722                    );
 4723                }
 4724                ranges.push(start + common_prefix_len..end);
 4725            } else {
 4726                common_prefix_len = 0;
 4727                ranges.clear();
 4728                ranges.extend(selections.iter().map(|s| {
 4729                    if s.id == newest_selection.id {
 4730                        range_to_replace = Some(
 4731                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4732                                - selection.start as isize
 4733                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4734                                    - selection.start as isize,
 4735                        );
 4736                        old_range.clone()
 4737                    } else {
 4738                        s.start..s.end
 4739                    }
 4740                }));
 4741                break;
 4742            }
 4743            if !self.linked_edit_ranges.is_empty() {
 4744                let start_anchor = snapshot.anchor_before(selection.head());
 4745                let end_anchor = snapshot.anchor_after(selection.tail());
 4746                if let Some(ranges) = self
 4747                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4748                {
 4749                    for (buffer, edits) in ranges {
 4750                        linked_edits.entry(buffer.clone()).or_default().extend(
 4751                            edits
 4752                                .into_iter()
 4753                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4754                        );
 4755                    }
 4756                }
 4757            }
 4758        }
 4759        let text = &text[common_prefix_len..];
 4760
 4761        cx.emit(EditorEvent::InputHandled {
 4762            utf16_range_to_replace: range_to_replace,
 4763            text: text.into(),
 4764        });
 4765
 4766        self.transact(cx, |this, cx| {
 4767            if let Some(mut snippet) = snippet {
 4768                snippet.text = text.to_string();
 4769                for tabstop in snippet
 4770                    .tabstops
 4771                    .iter_mut()
 4772                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4773                {
 4774                    tabstop.start -= common_prefix_len as isize;
 4775                    tabstop.end -= common_prefix_len as isize;
 4776                }
 4777
 4778                this.insert_snippet(&ranges, snippet, cx).log_err();
 4779            } else {
 4780                this.buffer.update(cx, |buffer, cx| {
 4781                    buffer.edit(
 4782                        ranges.iter().map(|range| (range.clone(), text)),
 4783                        this.autoindent_mode.clone(),
 4784                        cx,
 4785                    );
 4786                });
 4787            }
 4788            for (buffer, edits) in linked_edits {
 4789                buffer.update(cx, |buffer, cx| {
 4790                    let snapshot = buffer.snapshot();
 4791                    let edits = edits
 4792                        .into_iter()
 4793                        .map(|(range, text)| {
 4794                            use text::ToPoint as TP;
 4795                            let end_point = TP::to_point(&range.end, &snapshot);
 4796                            let start_point = TP::to_point(&range.start, &snapshot);
 4797                            (start_point..end_point, text)
 4798                        })
 4799                        .sorted_by_key(|(range, _)| range.start)
 4800                        .collect::<Vec<_>>();
 4801                    buffer.edit(edits, None, cx);
 4802                })
 4803            }
 4804
 4805            this.refresh_inline_completion(true, false, cx);
 4806        });
 4807
 4808        let show_new_completions_on_confirm = completion
 4809            .confirm
 4810            .as_ref()
 4811            .map_or(false, |confirm| confirm(intent, cx));
 4812        if show_new_completions_on_confirm {
 4813            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4814        }
 4815
 4816        let provider = self.completion_provider.as_ref()?;
 4817        let apply_edits = provider.apply_additional_edits_for_completion(
 4818            buffer_handle,
 4819            completion.clone(),
 4820            true,
 4821            cx,
 4822        );
 4823
 4824        let editor_settings = EditorSettings::get_global(cx);
 4825        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4826            // After the code completion is finished, users often want to know what signatures are needed.
 4827            // so we should automatically call signature_help
 4828            self.show_signature_help(&ShowSignatureHelp, cx);
 4829        }
 4830
 4831        Some(cx.foreground_executor().spawn(async move {
 4832            apply_edits.await?;
 4833            Ok(())
 4834        }))
 4835    }
 4836
 4837    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4838        let mut context_menu = self.context_menu.write();
 4839        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4840            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4841                // Toggle if we're selecting the same one
 4842                *context_menu = None;
 4843                cx.notify();
 4844                return;
 4845            } else {
 4846                // Otherwise, clear it and start a new one
 4847                *context_menu = None;
 4848                cx.notify();
 4849            }
 4850        }
 4851        drop(context_menu);
 4852        let snapshot = self.snapshot(cx);
 4853        let deployed_from_indicator = action.deployed_from_indicator;
 4854        let mut task = self.code_actions_task.take();
 4855        let action = action.clone();
 4856        cx.spawn(|editor, mut cx| async move {
 4857            while let Some(prev_task) = task {
 4858                prev_task.await.log_err();
 4859                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4860            }
 4861
 4862            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4863                if editor.focus_handle.is_focused(cx) {
 4864                    let multibuffer_point = action
 4865                        .deployed_from_indicator
 4866                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4867                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4868                    let (buffer, buffer_row) = snapshot
 4869                        .buffer_snapshot
 4870                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4871                        .and_then(|(buffer_snapshot, range)| {
 4872                            editor
 4873                                .buffer
 4874                                .read(cx)
 4875                                .buffer(buffer_snapshot.remote_id())
 4876                                .map(|buffer| (buffer, range.start.row))
 4877                        })?;
 4878                    let (_, code_actions) = editor
 4879                        .available_code_actions
 4880                        .clone()
 4881                        .and_then(|(location, code_actions)| {
 4882                            let snapshot = location.buffer.read(cx).snapshot();
 4883                            let point_range = location.range.to_point(&snapshot);
 4884                            let point_range = point_range.start.row..=point_range.end.row;
 4885                            if point_range.contains(&buffer_row) {
 4886                                Some((location, code_actions))
 4887                            } else {
 4888                                None
 4889                            }
 4890                        })
 4891                        .unzip();
 4892                    let buffer_id = buffer.read(cx).remote_id();
 4893                    let tasks = editor
 4894                        .tasks
 4895                        .get(&(buffer_id, buffer_row))
 4896                        .map(|t| Arc::new(t.to_owned()));
 4897                    if tasks.is_none() && code_actions.is_none() {
 4898                        return None;
 4899                    }
 4900
 4901                    editor.completion_tasks.clear();
 4902                    editor.discard_inline_completion(false, cx);
 4903                    let task_context =
 4904                        tasks
 4905                            .as_ref()
 4906                            .zip(editor.project.clone())
 4907                            .map(|(tasks, project)| {
 4908                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4909                            });
 4910
 4911                    Some(cx.spawn(|editor, mut cx| async move {
 4912                        let task_context = match task_context {
 4913                            Some(task_context) => task_context.await,
 4914                            None => None,
 4915                        };
 4916                        let resolved_tasks =
 4917                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4918                                Arc::new(ResolvedTasks {
 4919                                    templates: tasks.resolve(&task_context).collect(),
 4920                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4921                                        multibuffer_point.row,
 4922                                        tasks.column,
 4923                                    )),
 4924                                })
 4925                            });
 4926                        let spawn_straight_away = resolved_tasks
 4927                            .as_ref()
 4928                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4929                            && code_actions
 4930                                .as_ref()
 4931                                .map_or(true, |actions| actions.is_empty());
 4932                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4933                            *editor.context_menu.write() =
 4934                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4935                                    buffer,
 4936                                    actions: CodeActionContents {
 4937                                        tasks: resolved_tasks,
 4938                                        actions: code_actions,
 4939                                    },
 4940                                    selected_item: Default::default(),
 4941                                    scroll_handle: UniformListScrollHandle::default(),
 4942                                    deployed_from_indicator,
 4943                                }));
 4944                            if spawn_straight_away {
 4945                                if let Some(task) = editor.confirm_code_action(
 4946                                    &ConfirmCodeAction { item_ix: Some(0) },
 4947                                    cx,
 4948                                ) {
 4949                                    cx.notify();
 4950                                    return task;
 4951                                }
 4952                            }
 4953                            cx.notify();
 4954                            Task::ready(Ok(()))
 4955                        }) {
 4956                            task.await
 4957                        } else {
 4958                            Ok(())
 4959                        }
 4960                    }))
 4961                } else {
 4962                    Some(Task::ready(Ok(())))
 4963                }
 4964            })?;
 4965            if let Some(task) = spawned_test_task {
 4966                task.await?;
 4967            }
 4968
 4969            Ok::<_, anyhow::Error>(())
 4970        })
 4971        .detach_and_log_err(cx);
 4972    }
 4973
 4974    pub fn confirm_code_action(
 4975        &mut self,
 4976        action: &ConfirmCodeAction,
 4977        cx: &mut ViewContext<Self>,
 4978    ) -> Option<Task<Result<()>>> {
 4979        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4980            menu
 4981        } else {
 4982            return None;
 4983        };
 4984        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4985        let action = actions_menu.actions.get(action_ix)?;
 4986        let title = action.label();
 4987        let buffer = actions_menu.buffer;
 4988        let workspace = self.workspace()?;
 4989
 4990        match action {
 4991            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4992                workspace.update(cx, |workspace, cx| {
 4993                    workspace::tasks::schedule_resolved_task(
 4994                        workspace,
 4995                        task_source_kind,
 4996                        resolved_task,
 4997                        false,
 4998                        cx,
 4999                    );
 5000
 5001                    Some(Task::ready(Ok(())))
 5002                })
 5003            }
 5004            CodeActionsItem::CodeAction {
 5005                excerpt_id,
 5006                action,
 5007                provider,
 5008            } => {
 5009                let apply_code_action =
 5010                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 5011                let workspace = workspace.downgrade();
 5012                Some(cx.spawn(|editor, cx| async move {
 5013                    let project_transaction = apply_code_action.await?;
 5014                    Self::open_project_transaction(
 5015                        &editor,
 5016                        workspace,
 5017                        project_transaction,
 5018                        title,
 5019                        cx,
 5020                    )
 5021                    .await
 5022                }))
 5023            }
 5024        }
 5025    }
 5026
 5027    pub async fn open_project_transaction(
 5028        this: &WeakView<Editor>,
 5029        workspace: WeakView<Workspace>,
 5030        transaction: ProjectTransaction,
 5031        title: String,
 5032        mut cx: AsyncWindowContext,
 5033    ) -> Result<()> {
 5034        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5035        cx.update(|cx| {
 5036            entries.sort_unstable_by_key(|(buffer, _)| {
 5037                buffer.read(cx).file().map(|f| f.path().clone())
 5038            });
 5039        })?;
 5040
 5041        // If the project transaction's edits are all contained within this editor, then
 5042        // avoid opening a new editor to display them.
 5043
 5044        if let Some((buffer, transaction)) = entries.first() {
 5045            if entries.len() == 1 {
 5046                let excerpt = this.update(&mut cx, |editor, cx| {
 5047                    editor
 5048                        .buffer()
 5049                        .read(cx)
 5050                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5051                })?;
 5052                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5053                    if excerpted_buffer == *buffer {
 5054                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 5055                            let excerpt_range = excerpt_range.to_offset(buffer);
 5056                            buffer
 5057                                .edited_ranges_for_transaction::<usize>(transaction)
 5058                                .all(|range| {
 5059                                    excerpt_range.start <= range.start
 5060                                        && excerpt_range.end >= range.end
 5061                                })
 5062                        })?;
 5063
 5064                        if all_edits_within_excerpt {
 5065                            return Ok(());
 5066                        }
 5067                    }
 5068                }
 5069            }
 5070        } else {
 5071            return Ok(());
 5072        }
 5073
 5074        let mut ranges_to_highlight = Vec::new();
 5075        let excerpt_buffer = cx.new_model(|cx| {
 5076            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5077            for (buffer_handle, transaction) in &entries {
 5078                let buffer = buffer_handle.read(cx);
 5079                ranges_to_highlight.extend(
 5080                    multibuffer.push_excerpts_with_context_lines(
 5081                        buffer_handle.clone(),
 5082                        buffer
 5083                            .edited_ranges_for_transaction::<usize>(transaction)
 5084                            .collect(),
 5085                        DEFAULT_MULTIBUFFER_CONTEXT,
 5086                        cx,
 5087                    ),
 5088                );
 5089            }
 5090            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5091            multibuffer
 5092        })?;
 5093
 5094        workspace.update(&mut cx, |workspace, cx| {
 5095            let project = workspace.project().clone();
 5096            let editor =
 5097                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5098            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5099            editor.update(cx, |editor, cx| {
 5100                editor.highlight_background::<Self>(
 5101                    &ranges_to_highlight,
 5102                    |theme| theme.editor_highlighted_line_background,
 5103                    cx,
 5104                );
 5105            });
 5106        })?;
 5107
 5108        Ok(())
 5109    }
 5110
 5111    pub fn clear_code_action_providers(&mut self) {
 5112        self.code_action_providers.clear();
 5113        self.available_code_actions.take();
 5114    }
 5115
 5116    pub fn push_code_action_provider(
 5117        &mut self,
 5118        provider: Arc<dyn CodeActionProvider>,
 5119        cx: &mut ViewContext<Self>,
 5120    ) {
 5121        self.code_action_providers.push(provider);
 5122        self.refresh_code_actions(cx);
 5123    }
 5124
 5125    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5126        let buffer = self.buffer.read(cx);
 5127        let newest_selection = self.selections.newest_anchor().clone();
 5128        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5129        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5130        if start_buffer != end_buffer {
 5131            return None;
 5132        }
 5133
 5134        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5135            cx.background_executor()
 5136                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5137                .await;
 5138
 5139            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5140                let providers = this.code_action_providers.clone();
 5141                let tasks = this
 5142                    .code_action_providers
 5143                    .iter()
 5144                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5145                    .collect::<Vec<_>>();
 5146                (providers, tasks)
 5147            })?;
 5148
 5149            let mut actions = Vec::new();
 5150            for (provider, provider_actions) in
 5151                providers.into_iter().zip(future::join_all(tasks).await)
 5152            {
 5153                if let Some(provider_actions) = provider_actions.log_err() {
 5154                    actions.extend(provider_actions.into_iter().map(|action| {
 5155                        AvailableCodeAction {
 5156                            excerpt_id: newest_selection.start.excerpt_id,
 5157                            action,
 5158                            provider: provider.clone(),
 5159                        }
 5160                    }));
 5161                }
 5162            }
 5163
 5164            this.update(&mut cx, |this, cx| {
 5165                this.available_code_actions = if actions.is_empty() {
 5166                    None
 5167                } else {
 5168                    Some((
 5169                        Location {
 5170                            buffer: start_buffer,
 5171                            range: start..end,
 5172                        },
 5173                        actions.into(),
 5174                    ))
 5175                };
 5176                cx.notify();
 5177            })
 5178        }));
 5179        None
 5180    }
 5181
 5182    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5183        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5184            self.show_git_blame_inline = false;
 5185
 5186            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5187                cx.background_executor().timer(delay).await;
 5188
 5189                this.update(&mut cx, |this, cx| {
 5190                    this.show_git_blame_inline = true;
 5191                    cx.notify();
 5192                })
 5193                .log_err();
 5194            }));
 5195        }
 5196    }
 5197
 5198    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5199        if self.pending_rename.is_some() {
 5200            return None;
 5201        }
 5202
 5203        let provider = self.semantics_provider.clone()?;
 5204        let buffer = self.buffer.read(cx);
 5205        let newest_selection = self.selections.newest_anchor().clone();
 5206        let cursor_position = newest_selection.head();
 5207        let (cursor_buffer, cursor_buffer_position) =
 5208            buffer.text_anchor_for_position(cursor_position, cx)?;
 5209        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5210        if cursor_buffer != tail_buffer {
 5211            return None;
 5212        }
 5213
 5214        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5215            cx.background_executor()
 5216                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5217                .await;
 5218
 5219            let highlights = if let Some(highlights) = cx
 5220                .update(|cx| {
 5221                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5222                })
 5223                .ok()
 5224                .flatten()
 5225            {
 5226                highlights.await.log_err()
 5227            } else {
 5228                None
 5229            };
 5230
 5231            if let Some(highlights) = highlights {
 5232                this.update(&mut cx, |this, cx| {
 5233                    if this.pending_rename.is_some() {
 5234                        return;
 5235                    }
 5236
 5237                    let buffer_id = cursor_position.buffer_id;
 5238                    let buffer = this.buffer.read(cx);
 5239                    if !buffer
 5240                        .text_anchor_for_position(cursor_position, cx)
 5241                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5242                    {
 5243                        return;
 5244                    }
 5245
 5246                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5247                    let mut write_ranges = Vec::new();
 5248                    let mut read_ranges = Vec::new();
 5249                    for highlight in highlights {
 5250                        for (excerpt_id, excerpt_range) in
 5251                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5252                        {
 5253                            let start = highlight
 5254                                .range
 5255                                .start
 5256                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5257                            let end = highlight
 5258                                .range
 5259                                .end
 5260                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5261                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5262                                continue;
 5263                            }
 5264
 5265                            let range = Anchor {
 5266                                buffer_id,
 5267                                excerpt_id,
 5268                                text_anchor: start,
 5269                            }..Anchor {
 5270                                buffer_id,
 5271                                excerpt_id,
 5272                                text_anchor: end,
 5273                            };
 5274                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5275                                write_ranges.push(range);
 5276                            } else {
 5277                                read_ranges.push(range);
 5278                            }
 5279                        }
 5280                    }
 5281
 5282                    this.highlight_background::<DocumentHighlightRead>(
 5283                        &read_ranges,
 5284                        |theme| theme.editor_document_highlight_read_background,
 5285                        cx,
 5286                    );
 5287                    this.highlight_background::<DocumentHighlightWrite>(
 5288                        &write_ranges,
 5289                        |theme| theme.editor_document_highlight_write_background,
 5290                        cx,
 5291                    );
 5292                    cx.notify();
 5293                })
 5294                .log_err();
 5295            }
 5296        }));
 5297        None
 5298    }
 5299
 5300    pub fn refresh_inline_completion(
 5301        &mut self,
 5302        debounce: bool,
 5303        user_requested: bool,
 5304        cx: &mut ViewContext<Self>,
 5305    ) -> Option<()> {
 5306        let provider = self.inline_completion_provider()?;
 5307        let cursor = self.selections.newest_anchor().head();
 5308        let (buffer, cursor_buffer_position) =
 5309            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5310
 5311        if !user_requested
 5312            && (!self.enable_inline_completions
 5313                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5314        {
 5315            self.discard_inline_completion(false, cx);
 5316            return None;
 5317        }
 5318
 5319        self.update_visible_inline_completion(cx);
 5320        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5321        Some(())
 5322    }
 5323
 5324    fn cycle_inline_completion(
 5325        &mut self,
 5326        direction: Direction,
 5327        cx: &mut ViewContext<Self>,
 5328    ) -> Option<()> {
 5329        let provider = self.inline_completion_provider()?;
 5330        let cursor = self.selections.newest_anchor().head();
 5331        let (buffer, cursor_buffer_position) =
 5332            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5333        if !self.enable_inline_completions
 5334            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5335        {
 5336            return None;
 5337        }
 5338
 5339        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5340        self.update_visible_inline_completion(cx);
 5341
 5342        Some(())
 5343    }
 5344
 5345    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5346        if !self.has_active_inline_completion(cx) {
 5347            self.refresh_inline_completion(false, true, cx);
 5348            return;
 5349        }
 5350
 5351        self.update_visible_inline_completion(cx);
 5352    }
 5353
 5354    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5355        self.show_cursor_names(cx);
 5356    }
 5357
 5358    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5359        self.show_cursor_names = true;
 5360        cx.notify();
 5361        cx.spawn(|this, mut cx| async move {
 5362            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5363            this.update(&mut cx, |this, cx| {
 5364                this.show_cursor_names = false;
 5365                cx.notify()
 5366            })
 5367            .ok()
 5368        })
 5369        .detach();
 5370    }
 5371
 5372    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5373        if self.has_active_inline_completion(cx) {
 5374            self.cycle_inline_completion(Direction::Next, cx);
 5375        } else {
 5376            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5377            if is_copilot_disabled {
 5378                cx.propagate();
 5379            }
 5380        }
 5381    }
 5382
 5383    pub fn previous_inline_completion(
 5384        &mut self,
 5385        _: &PreviousInlineCompletion,
 5386        cx: &mut ViewContext<Self>,
 5387    ) {
 5388        if self.has_active_inline_completion(cx) {
 5389            self.cycle_inline_completion(Direction::Prev, cx);
 5390        } else {
 5391            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5392            if is_copilot_disabled {
 5393                cx.propagate();
 5394            }
 5395        }
 5396    }
 5397
 5398    pub fn accept_inline_completion(
 5399        &mut self,
 5400        _: &AcceptInlineCompletion,
 5401        cx: &mut ViewContext<Self>,
 5402    ) {
 5403        let Some(completion) = self.take_active_inline_completion(cx) else {
 5404            return;
 5405        };
 5406        if let Some(provider) = self.inline_completion_provider() {
 5407            provider.accept(cx);
 5408        }
 5409
 5410        cx.emit(EditorEvent::InputHandled {
 5411            utf16_range_to_replace: None,
 5412            text: completion.text.to_string().into(),
 5413        });
 5414
 5415        if let Some(range) = completion.delete_range {
 5416            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5417        }
 5418        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5419        self.refresh_inline_completion(true, true, cx);
 5420        cx.notify();
 5421    }
 5422
 5423    pub fn accept_partial_inline_completion(
 5424        &mut self,
 5425        _: &AcceptPartialInlineCompletion,
 5426        cx: &mut ViewContext<Self>,
 5427    ) {
 5428        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5429            if let Some(completion) = self.take_active_inline_completion(cx) {
 5430                let mut partial_completion = completion
 5431                    .text
 5432                    .chars()
 5433                    .by_ref()
 5434                    .take_while(|c| c.is_alphabetic())
 5435                    .collect::<String>();
 5436                if partial_completion.is_empty() {
 5437                    partial_completion = completion
 5438                        .text
 5439                        .chars()
 5440                        .by_ref()
 5441                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5442                        .collect::<String>();
 5443                }
 5444
 5445                cx.emit(EditorEvent::InputHandled {
 5446                    utf16_range_to_replace: None,
 5447                    text: partial_completion.clone().into(),
 5448                });
 5449
 5450                if let Some(range) = completion.delete_range {
 5451                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5452                }
 5453                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5454
 5455                self.refresh_inline_completion(true, true, cx);
 5456                cx.notify();
 5457            }
 5458        }
 5459    }
 5460
 5461    fn discard_inline_completion(
 5462        &mut self,
 5463        should_report_inline_completion_event: bool,
 5464        cx: &mut ViewContext<Self>,
 5465    ) -> bool {
 5466        if let Some(provider) = self.inline_completion_provider() {
 5467            provider.discard(should_report_inline_completion_event, cx);
 5468        }
 5469
 5470        self.take_active_inline_completion(cx).is_some()
 5471    }
 5472
 5473    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5474        if let Some(completion) = self.active_inline_completion.as_ref() {
 5475            let buffer = self.buffer.read(cx).read(cx);
 5476            completion.position.is_valid(&buffer)
 5477        } else {
 5478            false
 5479        }
 5480    }
 5481
 5482    fn take_active_inline_completion(
 5483        &mut self,
 5484        cx: &mut ViewContext<Self>,
 5485    ) -> Option<CompletionState> {
 5486        let completion = self.active_inline_completion.take()?;
 5487        let render_inlay_ids = completion.render_inlay_ids.clone();
 5488        self.display_map.update(cx, |map, cx| {
 5489            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5490        });
 5491        let buffer = self.buffer.read(cx).read(cx);
 5492
 5493        if completion.position.is_valid(&buffer) {
 5494            Some(completion)
 5495        } else {
 5496            None
 5497        }
 5498    }
 5499
 5500    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5501        let selection = self.selections.newest_anchor();
 5502        let cursor = selection.head();
 5503
 5504        let excerpt_id = cursor.excerpt_id;
 5505
 5506        if self.context_menu.read().is_none()
 5507            && self.completion_tasks.is_empty()
 5508            && selection.start == selection.end
 5509        {
 5510            if let Some(provider) = self.inline_completion_provider() {
 5511                if let Some((buffer, cursor_buffer_position)) =
 5512                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5513                {
 5514                    if let Some(proposal) =
 5515                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5516                    {
 5517                        let mut to_remove = Vec::new();
 5518                        if let Some(completion) = self.active_inline_completion.take() {
 5519                            to_remove.extend(completion.render_inlay_ids.iter());
 5520                        }
 5521
 5522                        let to_add = proposal
 5523                            .inlays
 5524                            .iter()
 5525                            .filter_map(|inlay| {
 5526                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5527                                let id = post_inc(&mut self.next_inlay_id);
 5528                                match inlay {
 5529                                    InlayProposal::Hint(position, hint) => {
 5530                                        let position =
 5531                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5532                                        Some(Inlay::hint(id, position, hint))
 5533                                    }
 5534                                    InlayProposal::Suggestion(position, text) => {
 5535                                        let position =
 5536                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5537                                        Some(Inlay::suggestion(id, position, text.clone()))
 5538                                    }
 5539                                }
 5540                            })
 5541                            .collect_vec();
 5542
 5543                        self.active_inline_completion = Some(CompletionState {
 5544                            position: cursor,
 5545                            text: proposal.text,
 5546                            delete_range: proposal.delete_range.and_then(|range| {
 5547                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5548                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5549                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5550                                Some(start?..end?)
 5551                            }),
 5552                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5553                        });
 5554
 5555                        self.display_map
 5556                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5557
 5558                        cx.notify();
 5559                        return;
 5560                    }
 5561                }
 5562            }
 5563        }
 5564
 5565        self.discard_inline_completion(false, cx);
 5566    }
 5567
 5568    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5569        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5570    }
 5571
 5572    fn render_code_actions_indicator(
 5573        &self,
 5574        _style: &EditorStyle,
 5575        row: DisplayRow,
 5576        is_active: bool,
 5577        cx: &mut ViewContext<Self>,
 5578    ) -> Option<IconButton> {
 5579        if self.available_code_actions.is_some() {
 5580            Some(
 5581                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5582                    .shape(ui::IconButtonShape::Square)
 5583                    .icon_size(IconSize::XSmall)
 5584                    .icon_color(Color::Muted)
 5585                    .selected(is_active)
 5586                    .tooltip({
 5587                        let focus_handle = self.focus_handle.clone();
 5588                        move |cx| {
 5589                            Tooltip::for_action_in(
 5590                                "Toggle Code Actions",
 5591                                &ToggleCodeActions {
 5592                                    deployed_from_indicator: None,
 5593                                },
 5594                                &focus_handle,
 5595                                cx,
 5596                            )
 5597                        }
 5598                    })
 5599                    .on_click(cx.listener(move |editor, _e, cx| {
 5600                        editor.focus(cx);
 5601                        editor.toggle_code_actions(
 5602                            &ToggleCodeActions {
 5603                                deployed_from_indicator: Some(row),
 5604                            },
 5605                            cx,
 5606                        );
 5607                    })),
 5608            )
 5609        } else {
 5610            None
 5611        }
 5612    }
 5613
 5614    fn clear_tasks(&mut self) {
 5615        self.tasks.clear()
 5616    }
 5617
 5618    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5619        if self.tasks.insert(key, value).is_some() {
 5620            // This case should hopefully be rare, but just in case...
 5621            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5622        }
 5623    }
 5624
 5625    fn build_tasks_context(
 5626        project: &Model<Project>,
 5627        buffer: &Model<Buffer>,
 5628        buffer_row: u32,
 5629        tasks: &Arc<RunnableTasks>,
 5630        cx: &mut ViewContext<Self>,
 5631    ) -> Task<Option<task::TaskContext>> {
 5632        let position = Point::new(buffer_row, tasks.column);
 5633        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5634        let location = Location {
 5635            buffer: buffer.clone(),
 5636            range: range_start..range_start,
 5637        };
 5638        // Fill in the environmental variables from the tree-sitter captures
 5639        let mut captured_task_variables = TaskVariables::default();
 5640        for (capture_name, value) in tasks.extra_variables.clone() {
 5641            captured_task_variables.insert(
 5642                task::VariableName::Custom(capture_name.into()),
 5643                value.clone(),
 5644            );
 5645        }
 5646        project.update(cx, |project, cx| {
 5647            project.task_store().update(cx, |task_store, cx| {
 5648                task_store.task_context_for_location(captured_task_variables, location, cx)
 5649            })
 5650        })
 5651    }
 5652
 5653    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5654        let Some((workspace, _)) = self.workspace.clone() else {
 5655            return;
 5656        };
 5657        let Some(project) = self.project.clone() else {
 5658            return;
 5659        };
 5660
 5661        // Try to find a closest, enclosing node using tree-sitter that has a
 5662        // task
 5663        let Some((buffer, buffer_row, tasks)) = self
 5664            .find_enclosing_node_task(cx)
 5665            // Or find the task that's closest in row-distance.
 5666            .or_else(|| self.find_closest_task(cx))
 5667        else {
 5668            return;
 5669        };
 5670
 5671        let reveal_strategy = action.reveal;
 5672        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5673        cx.spawn(|_, mut cx| async move {
 5674            let context = task_context.await?;
 5675            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5676
 5677            let resolved = resolved_task.resolved.as_mut()?;
 5678            resolved.reveal = reveal_strategy;
 5679
 5680            workspace
 5681                .update(&mut cx, |workspace, cx| {
 5682                    workspace::tasks::schedule_resolved_task(
 5683                        workspace,
 5684                        task_source_kind,
 5685                        resolved_task,
 5686                        false,
 5687                        cx,
 5688                    );
 5689                })
 5690                .ok()
 5691        })
 5692        .detach();
 5693    }
 5694
 5695    fn find_closest_task(
 5696        &mut self,
 5697        cx: &mut ViewContext<Self>,
 5698    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5699        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5700
 5701        let ((buffer_id, row), tasks) = self
 5702            .tasks
 5703            .iter()
 5704            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5705
 5706        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5707        let tasks = Arc::new(tasks.to_owned());
 5708        Some((buffer, *row, tasks))
 5709    }
 5710
 5711    fn find_enclosing_node_task(
 5712        &mut self,
 5713        cx: &mut ViewContext<Self>,
 5714    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5715        let snapshot = self.buffer.read(cx).snapshot(cx);
 5716        let offset = self.selections.newest::<usize>(cx).head();
 5717        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5718        let buffer_id = excerpt.buffer().remote_id();
 5719
 5720        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5721        let mut cursor = layer.node().walk();
 5722
 5723        while cursor.goto_first_child_for_byte(offset).is_some() {
 5724            if cursor.node().end_byte() == offset {
 5725                cursor.goto_next_sibling();
 5726            }
 5727        }
 5728
 5729        // Ascend to the smallest ancestor that contains the range and has a task.
 5730        loop {
 5731            let node = cursor.node();
 5732            let node_range = node.byte_range();
 5733            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5734
 5735            // Check if this node contains our offset
 5736            if node_range.start <= offset && node_range.end >= offset {
 5737                // If it contains offset, check for task
 5738                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5739                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5740                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5741                }
 5742            }
 5743
 5744            if !cursor.goto_parent() {
 5745                break;
 5746            }
 5747        }
 5748        None
 5749    }
 5750
 5751    fn render_run_indicator(
 5752        &self,
 5753        _style: &EditorStyle,
 5754        is_active: bool,
 5755        row: DisplayRow,
 5756        cx: &mut ViewContext<Self>,
 5757    ) -> IconButton {
 5758        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5759            .shape(ui::IconButtonShape::Square)
 5760            .icon_size(IconSize::XSmall)
 5761            .icon_color(Color::Muted)
 5762            .selected(is_active)
 5763            .on_click(cx.listener(move |editor, _e, cx| {
 5764                editor.focus(cx);
 5765                editor.toggle_code_actions(
 5766                    &ToggleCodeActions {
 5767                        deployed_from_indicator: Some(row),
 5768                    },
 5769                    cx,
 5770                );
 5771            }))
 5772    }
 5773
 5774    pub fn context_menu_visible(&self) -> bool {
 5775        self.context_menu
 5776            .read()
 5777            .as_ref()
 5778            .map_or(false, |menu| menu.visible())
 5779    }
 5780
 5781    fn render_context_menu(
 5782        &self,
 5783        cursor_position: DisplayPoint,
 5784        style: &EditorStyle,
 5785        max_height: Pixels,
 5786        cx: &mut ViewContext<Editor>,
 5787    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5788        self.context_menu.read().as_ref().map(|menu| {
 5789            menu.render(
 5790                cursor_position,
 5791                style,
 5792                max_height,
 5793                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5794                cx,
 5795            )
 5796        })
 5797    }
 5798
 5799    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5800        cx.notify();
 5801        self.completion_tasks.clear();
 5802        let context_menu = self.context_menu.write().take();
 5803        if context_menu.is_some() {
 5804            self.update_visible_inline_completion(cx);
 5805        }
 5806        context_menu
 5807    }
 5808
 5809    fn show_snippet_choices(
 5810        &mut self,
 5811        choices: &Vec<String>,
 5812        selection: Range<Anchor>,
 5813        cx: &mut ViewContext<Self>,
 5814    ) {
 5815        if selection.start.buffer_id.is_none() {
 5816            return;
 5817        }
 5818        let buffer_id = selection.start.buffer_id.unwrap();
 5819        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5820        let id = post_inc(&mut self.next_completion_id);
 5821
 5822        if let Some(buffer) = buffer {
 5823            *self.context_menu.write() = Some(ContextMenu::Completions(
 5824                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
 5825                    .suppress_documentation_resolution(),
 5826            ));
 5827        }
 5828    }
 5829
 5830    pub fn insert_snippet(
 5831        &mut self,
 5832        insertion_ranges: &[Range<usize>],
 5833        snippet: Snippet,
 5834        cx: &mut ViewContext<Self>,
 5835    ) -> Result<()> {
 5836        struct Tabstop<T> {
 5837            is_end_tabstop: bool,
 5838            ranges: Vec<Range<T>>,
 5839            choices: Option<Vec<String>>,
 5840        }
 5841
 5842        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5843            let snippet_text: Arc<str> = snippet.text.clone().into();
 5844            buffer.edit(
 5845                insertion_ranges
 5846                    .iter()
 5847                    .cloned()
 5848                    .map(|range| (range, snippet_text.clone())),
 5849                Some(AutoindentMode::EachLine),
 5850                cx,
 5851            );
 5852
 5853            let snapshot = &*buffer.read(cx);
 5854            let snippet = &snippet;
 5855            snippet
 5856                .tabstops
 5857                .iter()
 5858                .map(|tabstop| {
 5859                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5860                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5861                    });
 5862                    let mut tabstop_ranges = tabstop
 5863                        .ranges
 5864                        .iter()
 5865                        .flat_map(|tabstop_range| {
 5866                            let mut delta = 0_isize;
 5867                            insertion_ranges.iter().map(move |insertion_range| {
 5868                                let insertion_start = insertion_range.start as isize + delta;
 5869                                delta +=
 5870                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5871
 5872                                let start = ((insertion_start + tabstop_range.start) as usize)
 5873                                    .min(snapshot.len());
 5874                                let end = ((insertion_start + tabstop_range.end) as usize)
 5875                                    .min(snapshot.len());
 5876                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5877                            })
 5878                        })
 5879                        .collect::<Vec<_>>();
 5880                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5881
 5882                    Tabstop {
 5883                        is_end_tabstop,
 5884                        ranges: tabstop_ranges,
 5885                        choices: tabstop.choices.clone(),
 5886                    }
 5887                })
 5888                .collect::<Vec<_>>()
 5889        });
 5890        if let Some(tabstop) = tabstops.first() {
 5891            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5892                s.select_ranges(tabstop.ranges.iter().cloned());
 5893            });
 5894
 5895            if let Some(choices) = &tabstop.choices {
 5896                if let Some(selection) = tabstop.ranges.first() {
 5897                    self.show_snippet_choices(choices, selection.clone(), cx)
 5898                }
 5899            }
 5900
 5901            // If we're already at the last tabstop and it's at the end of the snippet,
 5902            // we're done, we don't need to keep the state around.
 5903            if !tabstop.is_end_tabstop {
 5904                let choices = tabstops
 5905                    .iter()
 5906                    .map(|tabstop| tabstop.choices.clone())
 5907                    .collect();
 5908
 5909                let ranges = tabstops
 5910                    .into_iter()
 5911                    .map(|tabstop| tabstop.ranges)
 5912                    .collect::<Vec<_>>();
 5913
 5914                self.snippet_stack.push(SnippetState {
 5915                    active_index: 0,
 5916                    ranges,
 5917                    choices,
 5918                });
 5919            }
 5920
 5921            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5922            if self.autoclose_regions.is_empty() {
 5923                let snapshot = self.buffer.read(cx).snapshot(cx);
 5924                for selection in &mut self.selections.all::<Point>(cx) {
 5925                    let selection_head = selection.head();
 5926                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5927                        continue;
 5928                    };
 5929
 5930                    let mut bracket_pair = None;
 5931                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5932                    let prev_chars = snapshot
 5933                        .reversed_chars_at(selection_head)
 5934                        .collect::<String>();
 5935                    for (pair, enabled) in scope.brackets() {
 5936                        if enabled
 5937                            && pair.close
 5938                            && prev_chars.starts_with(pair.start.as_str())
 5939                            && next_chars.starts_with(pair.end.as_str())
 5940                        {
 5941                            bracket_pair = Some(pair.clone());
 5942                            break;
 5943                        }
 5944                    }
 5945                    if let Some(pair) = bracket_pair {
 5946                        let start = snapshot.anchor_after(selection_head);
 5947                        let end = snapshot.anchor_after(selection_head);
 5948                        self.autoclose_regions.push(AutocloseRegion {
 5949                            selection_id: selection.id,
 5950                            range: start..end,
 5951                            pair,
 5952                        });
 5953                    }
 5954                }
 5955            }
 5956        }
 5957        Ok(())
 5958    }
 5959
 5960    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5961        self.move_to_snippet_tabstop(Bias::Right, cx)
 5962    }
 5963
 5964    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5965        self.move_to_snippet_tabstop(Bias::Left, cx)
 5966    }
 5967
 5968    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5969        if let Some(mut snippet) = self.snippet_stack.pop() {
 5970            match bias {
 5971                Bias::Left => {
 5972                    if snippet.active_index > 0 {
 5973                        snippet.active_index -= 1;
 5974                    } else {
 5975                        self.snippet_stack.push(snippet);
 5976                        return false;
 5977                    }
 5978                }
 5979                Bias::Right => {
 5980                    if snippet.active_index + 1 < snippet.ranges.len() {
 5981                        snippet.active_index += 1;
 5982                    } else {
 5983                        self.snippet_stack.push(snippet);
 5984                        return false;
 5985                    }
 5986                }
 5987            }
 5988            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5989                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5990                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5991                });
 5992
 5993                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5994                    if let Some(selection) = current_ranges.first() {
 5995                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5996                    }
 5997                }
 5998
 5999                // If snippet state is not at the last tabstop, push it back on the stack
 6000                if snippet.active_index + 1 < snippet.ranges.len() {
 6001                    self.snippet_stack.push(snippet);
 6002                }
 6003                return true;
 6004            }
 6005        }
 6006
 6007        false
 6008    }
 6009
 6010    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 6011        self.transact(cx, |this, cx| {
 6012            this.select_all(&SelectAll, cx);
 6013            this.insert("", cx);
 6014        });
 6015    }
 6016
 6017    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 6018        self.transact(cx, |this, cx| {
 6019            this.select_autoclose_pair(cx);
 6020            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6021            if !this.linked_edit_ranges.is_empty() {
 6022                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6023                let snapshot = this.buffer.read(cx).snapshot(cx);
 6024
 6025                for selection in selections.iter() {
 6026                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6027                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6028                    if selection_start.buffer_id != selection_end.buffer_id {
 6029                        continue;
 6030                    }
 6031                    if let Some(ranges) =
 6032                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6033                    {
 6034                        for (buffer, entries) in ranges {
 6035                            linked_ranges.entry(buffer).or_default().extend(entries);
 6036                        }
 6037                    }
 6038                }
 6039            }
 6040
 6041            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6042            if !this.selections.line_mode {
 6043                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6044                for selection in &mut selections {
 6045                    if selection.is_empty() {
 6046                        let old_head = selection.head();
 6047                        let mut new_head =
 6048                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6049                                .to_point(&display_map);
 6050                        if let Some((buffer, line_buffer_range)) = display_map
 6051                            .buffer_snapshot
 6052                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6053                        {
 6054                            let indent_size =
 6055                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6056                            let indent_len = match indent_size.kind {
 6057                                IndentKind::Space => {
 6058                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6059                                }
 6060                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6061                            };
 6062                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6063                                let indent_len = indent_len.get();
 6064                                new_head = cmp::min(
 6065                                    new_head,
 6066                                    MultiBufferPoint::new(
 6067                                        old_head.row,
 6068                                        ((old_head.column - 1) / indent_len) * indent_len,
 6069                                    ),
 6070                                );
 6071                            }
 6072                        }
 6073
 6074                        selection.set_head(new_head, SelectionGoal::None);
 6075                    }
 6076                }
 6077            }
 6078
 6079            this.signature_help_state.set_backspace_pressed(true);
 6080            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6081            this.insert("", cx);
 6082            let empty_str: Arc<str> = Arc::from("");
 6083            for (buffer, edits) in linked_ranges {
 6084                let snapshot = buffer.read(cx).snapshot();
 6085                use text::ToPoint as TP;
 6086
 6087                let edits = edits
 6088                    .into_iter()
 6089                    .map(|range| {
 6090                        let end_point = TP::to_point(&range.end, &snapshot);
 6091                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6092
 6093                        if end_point == start_point {
 6094                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6095                                .saturating_sub(1);
 6096                            start_point = TP::to_point(&offset, &snapshot);
 6097                        };
 6098
 6099                        (start_point..end_point, empty_str.clone())
 6100                    })
 6101                    .sorted_by_key(|(range, _)| range.start)
 6102                    .collect::<Vec<_>>();
 6103                buffer.update(cx, |this, cx| {
 6104                    this.edit(edits, None, cx);
 6105                })
 6106            }
 6107            this.refresh_inline_completion(true, false, cx);
 6108            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6109        });
 6110    }
 6111
 6112    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6113        self.transact(cx, |this, cx| {
 6114            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6115                let line_mode = s.line_mode;
 6116                s.move_with(|map, selection| {
 6117                    if selection.is_empty() && !line_mode {
 6118                        let cursor = movement::right(map, selection.head());
 6119                        selection.end = cursor;
 6120                        selection.reversed = true;
 6121                        selection.goal = SelectionGoal::None;
 6122                    }
 6123                })
 6124            });
 6125            this.insert("", cx);
 6126            this.refresh_inline_completion(true, false, cx);
 6127        });
 6128    }
 6129
 6130    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6131        if self.move_to_prev_snippet_tabstop(cx) {
 6132            return;
 6133        }
 6134
 6135        self.outdent(&Outdent, cx);
 6136    }
 6137
 6138    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6139        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6140            return;
 6141        }
 6142
 6143        let mut selections = self.selections.all_adjusted(cx);
 6144        let buffer = self.buffer.read(cx);
 6145        let snapshot = buffer.snapshot(cx);
 6146        let rows_iter = selections.iter().map(|s| s.head().row);
 6147        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6148
 6149        let mut edits = Vec::new();
 6150        let mut prev_edited_row = 0;
 6151        let mut row_delta = 0;
 6152        for selection in &mut selections {
 6153            if selection.start.row != prev_edited_row {
 6154                row_delta = 0;
 6155            }
 6156            prev_edited_row = selection.end.row;
 6157
 6158            // If the selection is non-empty, then increase the indentation of the selected lines.
 6159            if !selection.is_empty() {
 6160                row_delta =
 6161                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6162                continue;
 6163            }
 6164
 6165            // If the selection is empty and the cursor is in the leading whitespace before the
 6166            // suggested indentation, then auto-indent the line.
 6167            let cursor = selection.head();
 6168            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6169            if let Some(suggested_indent) =
 6170                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6171            {
 6172                if cursor.column < suggested_indent.len
 6173                    && cursor.column <= current_indent.len
 6174                    && current_indent.len <= suggested_indent.len
 6175                {
 6176                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6177                    selection.end = selection.start;
 6178                    if row_delta == 0 {
 6179                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6180                            cursor.row,
 6181                            current_indent,
 6182                            suggested_indent,
 6183                        ));
 6184                        row_delta = suggested_indent.len - current_indent.len;
 6185                    }
 6186                    continue;
 6187                }
 6188            }
 6189
 6190            // Otherwise, insert a hard or soft tab.
 6191            let settings = buffer.settings_at(cursor, cx);
 6192            let tab_size = if settings.hard_tabs {
 6193                IndentSize::tab()
 6194            } else {
 6195                let tab_size = settings.tab_size.get();
 6196                let char_column = snapshot
 6197                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6198                    .flat_map(str::chars)
 6199                    .count()
 6200                    + row_delta as usize;
 6201                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6202                IndentSize::spaces(chars_to_next_tab_stop)
 6203            };
 6204            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6205            selection.end = selection.start;
 6206            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6207            row_delta += tab_size.len;
 6208        }
 6209
 6210        self.transact(cx, |this, cx| {
 6211            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6212            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6213            this.refresh_inline_completion(true, false, cx);
 6214        });
 6215    }
 6216
 6217    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6218        if self.read_only(cx) {
 6219            return;
 6220        }
 6221        let mut selections = self.selections.all::<Point>(cx);
 6222        let mut prev_edited_row = 0;
 6223        let mut row_delta = 0;
 6224        let mut edits = Vec::new();
 6225        let buffer = self.buffer.read(cx);
 6226        let snapshot = buffer.snapshot(cx);
 6227        for selection in &mut selections {
 6228            if selection.start.row != prev_edited_row {
 6229                row_delta = 0;
 6230            }
 6231            prev_edited_row = selection.end.row;
 6232
 6233            row_delta =
 6234                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6235        }
 6236
 6237        self.transact(cx, |this, cx| {
 6238            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6239            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6240        });
 6241    }
 6242
 6243    fn indent_selection(
 6244        buffer: &MultiBuffer,
 6245        snapshot: &MultiBufferSnapshot,
 6246        selection: &mut Selection<Point>,
 6247        edits: &mut Vec<(Range<Point>, String)>,
 6248        delta_for_start_row: u32,
 6249        cx: &AppContext,
 6250    ) -> u32 {
 6251        let settings = buffer.settings_at(selection.start, cx);
 6252        let tab_size = settings.tab_size.get();
 6253        let indent_kind = if settings.hard_tabs {
 6254            IndentKind::Tab
 6255        } else {
 6256            IndentKind::Space
 6257        };
 6258        let mut start_row = selection.start.row;
 6259        let mut end_row = selection.end.row + 1;
 6260
 6261        // If a selection ends at the beginning of a line, don't indent
 6262        // that last line.
 6263        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6264            end_row -= 1;
 6265        }
 6266
 6267        // Avoid re-indenting a row that has already been indented by a
 6268        // previous selection, but still update this selection's column
 6269        // to reflect that indentation.
 6270        if delta_for_start_row > 0 {
 6271            start_row += 1;
 6272            selection.start.column += delta_for_start_row;
 6273            if selection.end.row == selection.start.row {
 6274                selection.end.column += delta_for_start_row;
 6275            }
 6276        }
 6277
 6278        let mut delta_for_end_row = 0;
 6279        let has_multiple_rows = start_row + 1 != end_row;
 6280        for row in start_row..end_row {
 6281            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6282            let indent_delta = match (current_indent.kind, indent_kind) {
 6283                (IndentKind::Space, IndentKind::Space) => {
 6284                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6285                    IndentSize::spaces(columns_to_next_tab_stop)
 6286                }
 6287                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6288                (_, IndentKind::Tab) => IndentSize::tab(),
 6289            };
 6290
 6291            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6292                0
 6293            } else {
 6294                selection.start.column
 6295            };
 6296            let row_start = Point::new(row, start);
 6297            edits.push((
 6298                row_start..row_start,
 6299                indent_delta.chars().collect::<String>(),
 6300            ));
 6301
 6302            // Update this selection's endpoints to reflect the indentation.
 6303            if row == selection.start.row {
 6304                selection.start.column += indent_delta.len;
 6305            }
 6306            if row == selection.end.row {
 6307                selection.end.column += indent_delta.len;
 6308                delta_for_end_row = indent_delta.len;
 6309            }
 6310        }
 6311
 6312        if selection.start.row == selection.end.row {
 6313            delta_for_start_row + delta_for_end_row
 6314        } else {
 6315            delta_for_end_row
 6316        }
 6317    }
 6318
 6319    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6320        if self.read_only(cx) {
 6321            return;
 6322        }
 6323        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6324        let selections = self.selections.all::<Point>(cx);
 6325        let mut deletion_ranges = Vec::new();
 6326        let mut last_outdent = None;
 6327        {
 6328            let buffer = self.buffer.read(cx);
 6329            let snapshot = buffer.snapshot(cx);
 6330            for selection in &selections {
 6331                let settings = buffer.settings_at(selection.start, cx);
 6332                let tab_size = settings.tab_size.get();
 6333                let mut rows = selection.spanned_rows(false, &display_map);
 6334
 6335                // Avoid re-outdenting a row that has already been outdented by a
 6336                // previous selection.
 6337                if let Some(last_row) = last_outdent {
 6338                    if last_row == rows.start {
 6339                        rows.start = rows.start.next_row();
 6340                    }
 6341                }
 6342                let has_multiple_rows = rows.len() > 1;
 6343                for row in rows.iter_rows() {
 6344                    let indent_size = snapshot.indent_size_for_line(row);
 6345                    if indent_size.len > 0 {
 6346                        let deletion_len = match indent_size.kind {
 6347                            IndentKind::Space => {
 6348                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6349                                if columns_to_prev_tab_stop == 0 {
 6350                                    tab_size
 6351                                } else {
 6352                                    columns_to_prev_tab_stop
 6353                                }
 6354                            }
 6355                            IndentKind::Tab => 1,
 6356                        };
 6357                        let start = if has_multiple_rows
 6358                            || deletion_len > selection.start.column
 6359                            || indent_size.len < selection.start.column
 6360                        {
 6361                            0
 6362                        } else {
 6363                            selection.start.column - deletion_len
 6364                        };
 6365                        deletion_ranges.push(
 6366                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6367                        );
 6368                        last_outdent = Some(row);
 6369                    }
 6370                }
 6371            }
 6372        }
 6373
 6374        self.transact(cx, |this, cx| {
 6375            this.buffer.update(cx, |buffer, cx| {
 6376                let empty_str: Arc<str> = Arc::default();
 6377                buffer.edit(
 6378                    deletion_ranges
 6379                        .into_iter()
 6380                        .map(|range| (range, empty_str.clone())),
 6381                    None,
 6382                    cx,
 6383                );
 6384            });
 6385            let selections = this.selections.all::<usize>(cx);
 6386            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6387        });
 6388    }
 6389
 6390    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6391        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6392        let selections = self.selections.all::<Point>(cx);
 6393
 6394        let mut new_cursors = Vec::new();
 6395        let mut edit_ranges = Vec::new();
 6396        let mut selections = selections.iter().peekable();
 6397        while let Some(selection) = selections.next() {
 6398            let mut rows = selection.spanned_rows(false, &display_map);
 6399            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6400
 6401            // Accumulate contiguous regions of rows that we want to delete.
 6402            while let Some(next_selection) = selections.peek() {
 6403                let next_rows = next_selection.spanned_rows(false, &display_map);
 6404                if next_rows.start <= rows.end {
 6405                    rows.end = next_rows.end;
 6406                    selections.next().unwrap();
 6407                } else {
 6408                    break;
 6409                }
 6410            }
 6411
 6412            let buffer = &display_map.buffer_snapshot;
 6413            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6414            let edit_end;
 6415            let cursor_buffer_row;
 6416            if buffer.max_point().row >= rows.end.0 {
 6417                // If there's a line after the range, delete the \n from the end of the row range
 6418                // and position the cursor on the next line.
 6419                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6420                cursor_buffer_row = rows.end;
 6421            } else {
 6422                // If there isn't a line after the range, delete the \n from the line before the
 6423                // start of the row range and position the cursor there.
 6424                edit_start = edit_start.saturating_sub(1);
 6425                edit_end = buffer.len();
 6426                cursor_buffer_row = rows.start.previous_row();
 6427            }
 6428
 6429            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6430            *cursor.column_mut() =
 6431                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6432
 6433            new_cursors.push((
 6434                selection.id,
 6435                buffer.anchor_after(cursor.to_point(&display_map)),
 6436            ));
 6437            edit_ranges.push(edit_start..edit_end);
 6438        }
 6439
 6440        self.transact(cx, |this, cx| {
 6441            let buffer = this.buffer.update(cx, |buffer, cx| {
 6442                let empty_str: Arc<str> = Arc::default();
 6443                buffer.edit(
 6444                    edit_ranges
 6445                        .into_iter()
 6446                        .map(|range| (range, empty_str.clone())),
 6447                    None,
 6448                    cx,
 6449                );
 6450                buffer.snapshot(cx)
 6451            });
 6452            let new_selections = new_cursors
 6453                .into_iter()
 6454                .map(|(id, cursor)| {
 6455                    let cursor = cursor.to_point(&buffer);
 6456                    Selection {
 6457                        id,
 6458                        start: cursor,
 6459                        end: cursor,
 6460                        reversed: false,
 6461                        goal: SelectionGoal::None,
 6462                    }
 6463                })
 6464                .collect();
 6465
 6466            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6467                s.select(new_selections);
 6468            });
 6469        });
 6470    }
 6471
 6472    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6473        if self.read_only(cx) {
 6474            return;
 6475        }
 6476        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6477        for selection in self.selections.all::<Point>(cx) {
 6478            let start = MultiBufferRow(selection.start.row);
 6479            // Treat single line selections as if they include the next line. Otherwise this action
 6480            // would do nothing for single line selections individual cursors.
 6481            let end = if selection.start.row == selection.end.row {
 6482                MultiBufferRow(selection.start.row + 1)
 6483            } else {
 6484                MultiBufferRow(selection.end.row)
 6485            };
 6486
 6487            if let Some(last_row_range) = row_ranges.last_mut() {
 6488                if start <= last_row_range.end {
 6489                    last_row_range.end = end;
 6490                    continue;
 6491                }
 6492            }
 6493            row_ranges.push(start..end);
 6494        }
 6495
 6496        let snapshot = self.buffer.read(cx).snapshot(cx);
 6497        let mut cursor_positions = Vec::new();
 6498        for row_range in &row_ranges {
 6499            let anchor = snapshot.anchor_before(Point::new(
 6500                row_range.end.previous_row().0,
 6501                snapshot.line_len(row_range.end.previous_row()),
 6502            ));
 6503            cursor_positions.push(anchor..anchor);
 6504        }
 6505
 6506        self.transact(cx, |this, cx| {
 6507            for row_range in row_ranges.into_iter().rev() {
 6508                for row in row_range.iter_rows().rev() {
 6509                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6510                    let next_line_row = row.next_row();
 6511                    let indent = snapshot.indent_size_for_line(next_line_row);
 6512                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6513
 6514                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6515                        " "
 6516                    } else {
 6517                        ""
 6518                    };
 6519
 6520                    this.buffer.update(cx, |buffer, cx| {
 6521                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6522                    });
 6523                }
 6524            }
 6525
 6526            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6527                s.select_anchor_ranges(cursor_positions)
 6528            });
 6529        });
 6530    }
 6531
 6532    pub fn sort_lines_case_sensitive(
 6533        &mut self,
 6534        _: &SortLinesCaseSensitive,
 6535        cx: &mut ViewContext<Self>,
 6536    ) {
 6537        self.manipulate_lines(cx, |lines| lines.sort())
 6538    }
 6539
 6540    pub fn sort_lines_case_insensitive(
 6541        &mut self,
 6542        _: &SortLinesCaseInsensitive,
 6543        cx: &mut ViewContext<Self>,
 6544    ) {
 6545        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6546    }
 6547
 6548    pub fn unique_lines_case_insensitive(
 6549        &mut self,
 6550        _: &UniqueLinesCaseInsensitive,
 6551        cx: &mut ViewContext<Self>,
 6552    ) {
 6553        self.manipulate_lines(cx, |lines| {
 6554            let mut seen = HashSet::default();
 6555            lines.retain(|line| seen.insert(line.to_lowercase()));
 6556        })
 6557    }
 6558
 6559    pub fn unique_lines_case_sensitive(
 6560        &mut self,
 6561        _: &UniqueLinesCaseSensitive,
 6562        cx: &mut ViewContext<Self>,
 6563    ) {
 6564        self.manipulate_lines(cx, |lines| {
 6565            let mut seen = HashSet::default();
 6566            lines.retain(|line| seen.insert(*line));
 6567        })
 6568    }
 6569
 6570    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6571        let mut revert_changes = HashMap::default();
 6572        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6573        for hunk in hunks_for_rows(
 6574            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6575            &multi_buffer_snapshot,
 6576        ) {
 6577            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6578        }
 6579        if !revert_changes.is_empty() {
 6580            self.transact(cx, |editor, cx| {
 6581                editor.revert(revert_changes, cx);
 6582            });
 6583        }
 6584    }
 6585
 6586    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6587        let Some(project) = self.project.clone() else {
 6588            return;
 6589        };
 6590        self.reload(project, cx).detach_and_notify_err(cx);
 6591    }
 6592
 6593    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6594        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6595        if !revert_changes.is_empty() {
 6596            self.transact(cx, |editor, cx| {
 6597                editor.revert(revert_changes, cx);
 6598            });
 6599        }
 6600    }
 6601
 6602    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6603        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6604            let project_path = buffer.read(cx).project_path(cx)?;
 6605            let project = self.project.as_ref()?.read(cx);
 6606            let entry = project.entry_for_path(&project_path, cx)?;
 6607            let parent = match &entry.canonical_path {
 6608                Some(canonical_path) => canonical_path.to_path_buf(),
 6609                None => project.absolute_path(&project_path, cx)?,
 6610            }
 6611            .parent()?
 6612            .to_path_buf();
 6613            Some(parent)
 6614        }) {
 6615            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6616        }
 6617    }
 6618
 6619    fn gather_revert_changes(
 6620        &mut self,
 6621        selections: &[Selection<Anchor>],
 6622        cx: &mut ViewContext<'_, Editor>,
 6623    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6624        let mut revert_changes = HashMap::default();
 6625        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6626        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6627            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6628        }
 6629        revert_changes
 6630    }
 6631
 6632    pub fn prepare_revert_change(
 6633        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6634        multi_buffer: &Model<MultiBuffer>,
 6635        hunk: &MultiBufferDiffHunk,
 6636        cx: &AppContext,
 6637    ) -> Option<()> {
 6638        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6639        let buffer = buffer.read(cx);
 6640        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6641        let buffer_snapshot = buffer.snapshot();
 6642        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6643        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6644            probe
 6645                .0
 6646                .start
 6647                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6648                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6649        }) {
 6650            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6651            Some(())
 6652        } else {
 6653            None
 6654        }
 6655    }
 6656
 6657    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6658        self.manipulate_lines(cx, |lines| lines.reverse())
 6659    }
 6660
 6661    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6662        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6663    }
 6664
 6665    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6666    where
 6667        Fn: FnMut(&mut Vec<&str>),
 6668    {
 6669        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6670        let buffer = self.buffer.read(cx).snapshot(cx);
 6671
 6672        let mut edits = Vec::new();
 6673
 6674        let selections = self.selections.all::<Point>(cx);
 6675        let mut selections = selections.iter().peekable();
 6676        let mut contiguous_row_selections = Vec::new();
 6677        let mut new_selections = Vec::new();
 6678        let mut added_lines = 0;
 6679        let mut removed_lines = 0;
 6680
 6681        while let Some(selection) = selections.next() {
 6682            let (start_row, end_row) = consume_contiguous_rows(
 6683                &mut contiguous_row_selections,
 6684                selection,
 6685                &display_map,
 6686                &mut selections,
 6687            );
 6688
 6689            let start_point = Point::new(start_row.0, 0);
 6690            let end_point = Point::new(
 6691                end_row.previous_row().0,
 6692                buffer.line_len(end_row.previous_row()),
 6693            );
 6694            let text = buffer
 6695                .text_for_range(start_point..end_point)
 6696                .collect::<String>();
 6697
 6698            let mut lines = text.split('\n').collect_vec();
 6699
 6700            let lines_before = lines.len();
 6701            callback(&mut lines);
 6702            let lines_after = lines.len();
 6703
 6704            edits.push((start_point..end_point, lines.join("\n")));
 6705
 6706            // Selections must change based on added and removed line count
 6707            let start_row =
 6708                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6709            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6710            new_selections.push(Selection {
 6711                id: selection.id,
 6712                start: start_row,
 6713                end: end_row,
 6714                goal: SelectionGoal::None,
 6715                reversed: selection.reversed,
 6716            });
 6717
 6718            if lines_after > lines_before {
 6719                added_lines += lines_after - lines_before;
 6720            } else if lines_before > lines_after {
 6721                removed_lines += lines_before - lines_after;
 6722            }
 6723        }
 6724
 6725        self.transact(cx, |this, cx| {
 6726            let buffer = this.buffer.update(cx, |buffer, cx| {
 6727                buffer.edit(edits, None, cx);
 6728                buffer.snapshot(cx)
 6729            });
 6730
 6731            // Recalculate offsets on newly edited buffer
 6732            let new_selections = new_selections
 6733                .iter()
 6734                .map(|s| {
 6735                    let start_point = Point::new(s.start.0, 0);
 6736                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6737                    Selection {
 6738                        id: s.id,
 6739                        start: buffer.point_to_offset(start_point),
 6740                        end: buffer.point_to_offset(end_point),
 6741                        goal: s.goal,
 6742                        reversed: s.reversed,
 6743                    }
 6744                })
 6745                .collect();
 6746
 6747            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6748                s.select(new_selections);
 6749            });
 6750
 6751            this.request_autoscroll(Autoscroll::fit(), cx);
 6752        });
 6753    }
 6754
 6755    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6756        self.manipulate_text(cx, |text| text.to_uppercase())
 6757    }
 6758
 6759    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6760        self.manipulate_text(cx, |text| text.to_lowercase())
 6761    }
 6762
 6763    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6764        self.manipulate_text(cx, |text| {
 6765            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6766            // https://github.com/rutrum/convert-case/issues/16
 6767            text.split('\n')
 6768                .map(|line| line.to_case(Case::Title))
 6769                .join("\n")
 6770        })
 6771    }
 6772
 6773    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6774        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6775    }
 6776
 6777    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6778        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6779    }
 6780
 6781    pub fn convert_to_upper_camel_case(
 6782        &mut self,
 6783        _: &ConvertToUpperCamelCase,
 6784        cx: &mut ViewContext<Self>,
 6785    ) {
 6786        self.manipulate_text(cx, |text| {
 6787            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6788            // https://github.com/rutrum/convert-case/issues/16
 6789            text.split('\n')
 6790                .map(|line| line.to_case(Case::UpperCamel))
 6791                .join("\n")
 6792        })
 6793    }
 6794
 6795    pub fn convert_to_lower_camel_case(
 6796        &mut self,
 6797        _: &ConvertToLowerCamelCase,
 6798        cx: &mut ViewContext<Self>,
 6799    ) {
 6800        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6801    }
 6802
 6803    pub fn convert_to_opposite_case(
 6804        &mut self,
 6805        _: &ConvertToOppositeCase,
 6806        cx: &mut ViewContext<Self>,
 6807    ) {
 6808        self.manipulate_text(cx, |text| {
 6809            text.chars()
 6810                .fold(String::with_capacity(text.len()), |mut t, c| {
 6811                    if c.is_uppercase() {
 6812                        t.extend(c.to_lowercase());
 6813                    } else {
 6814                        t.extend(c.to_uppercase());
 6815                    }
 6816                    t
 6817                })
 6818        })
 6819    }
 6820
 6821    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6822    where
 6823        Fn: FnMut(&str) -> String,
 6824    {
 6825        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6826        let buffer = self.buffer.read(cx).snapshot(cx);
 6827
 6828        let mut new_selections = Vec::new();
 6829        let mut edits = Vec::new();
 6830        let mut selection_adjustment = 0i32;
 6831
 6832        for selection in self.selections.all::<usize>(cx) {
 6833            let selection_is_empty = selection.is_empty();
 6834
 6835            let (start, end) = if selection_is_empty {
 6836                let word_range = movement::surrounding_word(
 6837                    &display_map,
 6838                    selection.start.to_display_point(&display_map),
 6839                );
 6840                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6841                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6842                (start, end)
 6843            } else {
 6844                (selection.start, selection.end)
 6845            };
 6846
 6847            let text = buffer.text_for_range(start..end).collect::<String>();
 6848            let old_length = text.len() as i32;
 6849            let text = callback(&text);
 6850
 6851            new_selections.push(Selection {
 6852                start: (start as i32 - selection_adjustment) as usize,
 6853                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6854                goal: SelectionGoal::None,
 6855                ..selection
 6856            });
 6857
 6858            selection_adjustment += old_length - text.len() as i32;
 6859
 6860            edits.push((start..end, text));
 6861        }
 6862
 6863        self.transact(cx, |this, cx| {
 6864            this.buffer.update(cx, |buffer, cx| {
 6865                buffer.edit(edits, None, cx);
 6866            });
 6867
 6868            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6869                s.select(new_selections);
 6870            });
 6871
 6872            this.request_autoscroll(Autoscroll::fit(), cx);
 6873        });
 6874    }
 6875
 6876    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6877        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6878        let buffer = &display_map.buffer_snapshot;
 6879        let selections = self.selections.all::<Point>(cx);
 6880
 6881        let mut edits = Vec::new();
 6882        let mut selections_iter = selections.iter().peekable();
 6883        while let Some(selection) = selections_iter.next() {
 6884            // Avoid duplicating the same lines twice.
 6885            let mut rows = selection.spanned_rows(false, &display_map);
 6886
 6887            while let Some(next_selection) = selections_iter.peek() {
 6888                let next_rows = next_selection.spanned_rows(false, &display_map);
 6889                if next_rows.start < rows.end {
 6890                    rows.end = next_rows.end;
 6891                    selections_iter.next().unwrap();
 6892                } else {
 6893                    break;
 6894                }
 6895            }
 6896
 6897            // Copy the text from the selected row region and splice it either at the start
 6898            // or end of the region.
 6899            let start = Point::new(rows.start.0, 0);
 6900            let end = Point::new(
 6901                rows.end.previous_row().0,
 6902                buffer.line_len(rows.end.previous_row()),
 6903            );
 6904            let text = buffer
 6905                .text_for_range(start..end)
 6906                .chain(Some("\n"))
 6907                .collect::<String>();
 6908            let insert_location = if upwards {
 6909                Point::new(rows.end.0, 0)
 6910            } else {
 6911                start
 6912            };
 6913            edits.push((insert_location..insert_location, text));
 6914        }
 6915
 6916        self.transact(cx, |this, cx| {
 6917            this.buffer.update(cx, |buffer, cx| {
 6918                buffer.edit(edits, None, cx);
 6919            });
 6920
 6921            this.request_autoscroll(Autoscroll::fit(), cx);
 6922        });
 6923    }
 6924
 6925    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6926        self.duplicate_line(true, cx);
 6927    }
 6928
 6929    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6930        self.duplicate_line(false, cx);
 6931    }
 6932
 6933    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6934        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6935        let buffer = self.buffer.read(cx).snapshot(cx);
 6936
 6937        let mut edits = Vec::new();
 6938        let mut unfold_ranges = Vec::new();
 6939        let mut refold_creases = Vec::new();
 6940
 6941        let selections = self.selections.all::<Point>(cx);
 6942        let mut selections = selections.iter().peekable();
 6943        let mut contiguous_row_selections = Vec::new();
 6944        let mut new_selections = Vec::new();
 6945
 6946        while let Some(selection) = selections.next() {
 6947            // Find all the selections that span a contiguous row range
 6948            let (start_row, end_row) = consume_contiguous_rows(
 6949                &mut contiguous_row_selections,
 6950                selection,
 6951                &display_map,
 6952                &mut selections,
 6953            );
 6954
 6955            // Move the text spanned by the row range to be before the line preceding the row range
 6956            if start_row.0 > 0 {
 6957                let range_to_move = Point::new(
 6958                    start_row.previous_row().0,
 6959                    buffer.line_len(start_row.previous_row()),
 6960                )
 6961                    ..Point::new(
 6962                        end_row.previous_row().0,
 6963                        buffer.line_len(end_row.previous_row()),
 6964                    );
 6965                let insertion_point = display_map
 6966                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6967                    .0;
 6968
 6969                // Don't move lines across excerpts
 6970                if buffer
 6971                    .excerpt_boundaries_in_range((
 6972                        Bound::Excluded(insertion_point),
 6973                        Bound::Included(range_to_move.end),
 6974                    ))
 6975                    .next()
 6976                    .is_none()
 6977                {
 6978                    let text = buffer
 6979                        .text_for_range(range_to_move.clone())
 6980                        .flat_map(|s| s.chars())
 6981                        .skip(1)
 6982                        .chain(['\n'])
 6983                        .collect::<String>();
 6984
 6985                    edits.push((
 6986                        buffer.anchor_after(range_to_move.start)
 6987                            ..buffer.anchor_before(range_to_move.end),
 6988                        String::new(),
 6989                    ));
 6990                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6991                    edits.push((insertion_anchor..insertion_anchor, text));
 6992
 6993                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6994
 6995                    // Move selections up
 6996                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6997                        |mut selection| {
 6998                            selection.start.row -= row_delta;
 6999                            selection.end.row -= row_delta;
 7000                            selection
 7001                        },
 7002                    ));
 7003
 7004                    // Move folds up
 7005                    unfold_ranges.push(range_to_move.clone());
 7006                    for fold in display_map.folds_in_range(
 7007                        buffer.anchor_before(range_to_move.start)
 7008                            ..buffer.anchor_after(range_to_move.end),
 7009                    ) {
 7010                        let mut start = fold.range.start.to_point(&buffer);
 7011                        let mut end = fold.range.end.to_point(&buffer);
 7012                        start.row -= row_delta;
 7013                        end.row -= row_delta;
 7014                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7015                    }
 7016                }
 7017            }
 7018
 7019            // If we didn't move line(s), preserve the existing selections
 7020            new_selections.append(&mut contiguous_row_selections);
 7021        }
 7022
 7023        self.transact(cx, |this, cx| {
 7024            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7025            this.buffer.update(cx, |buffer, cx| {
 7026                for (range, text) in edits {
 7027                    buffer.edit([(range, text)], None, cx);
 7028                }
 7029            });
 7030            this.fold_creases(refold_creases, true, cx);
 7031            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7032                s.select(new_selections);
 7033            })
 7034        });
 7035    }
 7036
 7037    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 7038        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7039        let buffer = self.buffer.read(cx).snapshot(cx);
 7040
 7041        let mut edits = Vec::new();
 7042        let mut unfold_ranges = Vec::new();
 7043        let mut refold_creases = Vec::new();
 7044
 7045        let selections = self.selections.all::<Point>(cx);
 7046        let mut selections = selections.iter().peekable();
 7047        let mut contiguous_row_selections = Vec::new();
 7048        let mut new_selections = Vec::new();
 7049
 7050        while let Some(selection) = selections.next() {
 7051            // Find all the selections that span a contiguous row range
 7052            let (start_row, end_row) = consume_contiguous_rows(
 7053                &mut contiguous_row_selections,
 7054                selection,
 7055                &display_map,
 7056                &mut selections,
 7057            );
 7058
 7059            // Move the text spanned by the row range to be after the last line of the row range
 7060            if end_row.0 <= buffer.max_point().row {
 7061                let range_to_move =
 7062                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7063                let insertion_point = display_map
 7064                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7065                    .0;
 7066
 7067                // Don't move lines across excerpt boundaries
 7068                if buffer
 7069                    .excerpt_boundaries_in_range((
 7070                        Bound::Excluded(range_to_move.start),
 7071                        Bound::Included(insertion_point),
 7072                    ))
 7073                    .next()
 7074                    .is_none()
 7075                {
 7076                    let mut text = String::from("\n");
 7077                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7078                    text.pop(); // Drop trailing newline
 7079                    edits.push((
 7080                        buffer.anchor_after(range_to_move.start)
 7081                            ..buffer.anchor_before(range_to_move.end),
 7082                        String::new(),
 7083                    ));
 7084                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7085                    edits.push((insertion_anchor..insertion_anchor, text));
 7086
 7087                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7088
 7089                    // Move selections down
 7090                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7091                        |mut selection| {
 7092                            selection.start.row += row_delta;
 7093                            selection.end.row += row_delta;
 7094                            selection
 7095                        },
 7096                    ));
 7097
 7098                    // Move folds down
 7099                    unfold_ranges.push(range_to_move.clone());
 7100                    for fold in display_map.folds_in_range(
 7101                        buffer.anchor_before(range_to_move.start)
 7102                            ..buffer.anchor_after(range_to_move.end),
 7103                    ) {
 7104                        let mut start = fold.range.start.to_point(&buffer);
 7105                        let mut end = fold.range.end.to_point(&buffer);
 7106                        start.row += row_delta;
 7107                        end.row += row_delta;
 7108                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7109                    }
 7110                }
 7111            }
 7112
 7113            // If we didn't move line(s), preserve the existing selections
 7114            new_selections.append(&mut contiguous_row_selections);
 7115        }
 7116
 7117        self.transact(cx, |this, cx| {
 7118            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7119            this.buffer.update(cx, |buffer, cx| {
 7120                for (range, text) in edits {
 7121                    buffer.edit([(range, text)], None, cx);
 7122                }
 7123            });
 7124            this.fold_creases(refold_creases, true, cx);
 7125            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7126        });
 7127    }
 7128
 7129    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7130        let text_layout_details = &self.text_layout_details(cx);
 7131        self.transact(cx, |this, cx| {
 7132            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7133                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7134                let line_mode = s.line_mode;
 7135                s.move_with(|display_map, selection| {
 7136                    if !selection.is_empty() || line_mode {
 7137                        return;
 7138                    }
 7139
 7140                    let mut head = selection.head();
 7141                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7142                    if head.column() == display_map.line_len(head.row()) {
 7143                        transpose_offset = display_map
 7144                            .buffer_snapshot
 7145                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7146                    }
 7147
 7148                    if transpose_offset == 0 {
 7149                        return;
 7150                    }
 7151
 7152                    *head.column_mut() += 1;
 7153                    head = display_map.clip_point(head, Bias::Right);
 7154                    let goal = SelectionGoal::HorizontalPosition(
 7155                        display_map
 7156                            .x_for_display_point(head, text_layout_details)
 7157                            .into(),
 7158                    );
 7159                    selection.collapse_to(head, goal);
 7160
 7161                    let transpose_start = display_map
 7162                        .buffer_snapshot
 7163                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7164                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7165                        let transpose_end = display_map
 7166                            .buffer_snapshot
 7167                            .clip_offset(transpose_offset + 1, Bias::Right);
 7168                        if let Some(ch) =
 7169                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7170                        {
 7171                            edits.push((transpose_start..transpose_offset, String::new()));
 7172                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7173                        }
 7174                    }
 7175                });
 7176                edits
 7177            });
 7178            this.buffer
 7179                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7180            let selections = this.selections.all::<usize>(cx);
 7181            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7182                s.select(selections);
 7183            });
 7184        });
 7185    }
 7186
 7187    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7188        self.rewrap_impl(IsVimMode::No, cx)
 7189    }
 7190
 7191    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7192        let buffer = self.buffer.read(cx).snapshot(cx);
 7193        let selections = self.selections.all::<Point>(cx);
 7194        let mut selections = selections.iter().peekable();
 7195
 7196        let mut edits = Vec::new();
 7197        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7198
 7199        while let Some(selection) = selections.next() {
 7200            let mut start_row = selection.start.row;
 7201            let mut end_row = selection.end.row;
 7202
 7203            // Skip selections that overlap with a range that has already been rewrapped.
 7204            let selection_range = start_row..end_row;
 7205            if rewrapped_row_ranges
 7206                .iter()
 7207                .any(|range| range.overlaps(&selection_range))
 7208            {
 7209                continue;
 7210            }
 7211
 7212            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7213
 7214            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7215                match language_scope.language_name().0.as_ref() {
 7216                    "Markdown" | "Plain Text" => {
 7217                        should_rewrap = true;
 7218                    }
 7219                    _ => {}
 7220                }
 7221            }
 7222
 7223            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7224
 7225            // Since not all lines in the selection may be at the same indent
 7226            // level, choose the indent size that is the most common between all
 7227            // of the lines.
 7228            //
 7229            // If there is a tie, we use the deepest indent.
 7230            let (indent_size, indent_end) = {
 7231                let mut indent_size_occurrences = HashMap::default();
 7232                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7233
 7234                for row in start_row..=end_row {
 7235                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7236                    rows_by_indent_size.entry(indent).or_default().push(row);
 7237                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7238                }
 7239
 7240                let indent_size = indent_size_occurrences
 7241                    .into_iter()
 7242                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7243                    .map(|(indent, _)| indent)
 7244                    .unwrap_or_default();
 7245                let row = rows_by_indent_size[&indent_size][0];
 7246                let indent_end = Point::new(row, indent_size.len);
 7247
 7248                (indent_size, indent_end)
 7249            };
 7250
 7251            let mut line_prefix = indent_size.chars().collect::<String>();
 7252
 7253            if let Some(comment_prefix) =
 7254                buffer
 7255                    .language_scope_at(selection.head())
 7256                    .and_then(|language| {
 7257                        language
 7258                            .line_comment_prefixes()
 7259                            .iter()
 7260                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7261                            .cloned()
 7262                    })
 7263            {
 7264                line_prefix.push_str(&comment_prefix);
 7265                should_rewrap = true;
 7266            }
 7267
 7268            if !should_rewrap {
 7269                continue;
 7270            }
 7271
 7272            if selection.is_empty() {
 7273                'expand_upwards: while start_row > 0 {
 7274                    let prev_row = start_row - 1;
 7275                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7276                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7277                    {
 7278                        start_row = prev_row;
 7279                    } else {
 7280                        break 'expand_upwards;
 7281                    }
 7282                }
 7283
 7284                'expand_downwards: while end_row < buffer.max_point().row {
 7285                    let next_row = end_row + 1;
 7286                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7287                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7288                    {
 7289                        end_row = next_row;
 7290                    } else {
 7291                        break 'expand_downwards;
 7292                    }
 7293                }
 7294            }
 7295
 7296            let start = Point::new(start_row, 0);
 7297            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7298            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7299            let Some(lines_without_prefixes) = selection_text
 7300                .lines()
 7301                .map(|line| {
 7302                    line.strip_prefix(&line_prefix)
 7303                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7304                        .ok_or_else(|| {
 7305                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7306                        })
 7307                })
 7308                .collect::<Result<Vec<_>, _>>()
 7309                .log_err()
 7310            else {
 7311                continue;
 7312            };
 7313
 7314            let wrap_column = buffer
 7315                .settings_at(Point::new(start_row, 0), cx)
 7316                .preferred_line_length as usize;
 7317            let wrapped_text = wrap_with_prefix(
 7318                line_prefix,
 7319                lines_without_prefixes.join(" "),
 7320                wrap_column,
 7321                tab_size,
 7322            );
 7323
 7324            // TODO: should always use char-based diff while still supporting cursor behavior that
 7325            // matches vim.
 7326            let diff = match is_vim_mode {
 7327                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7328                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7329            };
 7330            let mut offset = start.to_offset(&buffer);
 7331            let mut moved_since_edit = true;
 7332
 7333            for change in diff.iter_all_changes() {
 7334                let value = change.value();
 7335                match change.tag() {
 7336                    ChangeTag::Equal => {
 7337                        offset += value.len();
 7338                        moved_since_edit = true;
 7339                    }
 7340                    ChangeTag::Delete => {
 7341                        let start = buffer.anchor_after(offset);
 7342                        let end = buffer.anchor_before(offset + value.len());
 7343
 7344                        if moved_since_edit {
 7345                            edits.push((start..end, String::new()));
 7346                        } else {
 7347                            edits.last_mut().unwrap().0.end = end;
 7348                        }
 7349
 7350                        offset += value.len();
 7351                        moved_since_edit = false;
 7352                    }
 7353                    ChangeTag::Insert => {
 7354                        if moved_since_edit {
 7355                            let anchor = buffer.anchor_after(offset);
 7356                            edits.push((anchor..anchor, value.to_string()));
 7357                        } else {
 7358                            edits.last_mut().unwrap().1.push_str(value);
 7359                        }
 7360
 7361                        moved_since_edit = false;
 7362                    }
 7363                }
 7364            }
 7365
 7366            rewrapped_row_ranges.push(start_row..=end_row);
 7367        }
 7368
 7369        self.buffer
 7370            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7371    }
 7372
 7373    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7374        let mut text = String::new();
 7375        let buffer = self.buffer.read(cx).snapshot(cx);
 7376        let mut selections = self.selections.all::<Point>(cx);
 7377        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7378        {
 7379            let max_point = buffer.max_point();
 7380            let mut is_first = true;
 7381            for selection in &mut selections {
 7382                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7383                if is_entire_line {
 7384                    selection.start = Point::new(selection.start.row, 0);
 7385                    if !selection.is_empty() && selection.end.column == 0 {
 7386                        selection.end = cmp::min(max_point, selection.end);
 7387                    } else {
 7388                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7389                    }
 7390                    selection.goal = SelectionGoal::None;
 7391                }
 7392                if is_first {
 7393                    is_first = false;
 7394                } else {
 7395                    text += "\n";
 7396                }
 7397                let mut len = 0;
 7398                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7399                    text.push_str(chunk);
 7400                    len += chunk.len();
 7401                }
 7402                clipboard_selections.push(ClipboardSelection {
 7403                    len,
 7404                    is_entire_line,
 7405                    first_line_indent: buffer
 7406                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7407                        .len,
 7408                });
 7409            }
 7410        }
 7411
 7412        self.transact(cx, |this, cx| {
 7413            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7414                s.select(selections);
 7415            });
 7416            this.insert("", cx);
 7417            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7418                text,
 7419                clipboard_selections,
 7420            ));
 7421        });
 7422    }
 7423
 7424    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7425        let selections = self.selections.all::<Point>(cx);
 7426        let buffer = self.buffer.read(cx).read(cx);
 7427        let mut text = String::new();
 7428
 7429        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7430        {
 7431            let max_point = buffer.max_point();
 7432            let mut is_first = true;
 7433            for selection in selections.iter() {
 7434                let mut start = selection.start;
 7435                let mut end = selection.end;
 7436                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7437                if is_entire_line {
 7438                    start = Point::new(start.row, 0);
 7439                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7440                }
 7441                if is_first {
 7442                    is_first = false;
 7443                } else {
 7444                    text += "\n";
 7445                }
 7446                let mut len = 0;
 7447                for chunk in buffer.text_for_range(start..end) {
 7448                    text.push_str(chunk);
 7449                    len += chunk.len();
 7450                }
 7451                clipboard_selections.push(ClipboardSelection {
 7452                    len,
 7453                    is_entire_line,
 7454                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7455                });
 7456            }
 7457        }
 7458
 7459        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7460            text,
 7461            clipboard_selections,
 7462        ));
 7463    }
 7464
 7465    pub fn do_paste(
 7466        &mut self,
 7467        text: &String,
 7468        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7469        handle_entire_lines: bool,
 7470        cx: &mut ViewContext<Self>,
 7471    ) {
 7472        if self.read_only(cx) {
 7473            return;
 7474        }
 7475
 7476        let clipboard_text = Cow::Borrowed(text);
 7477
 7478        self.transact(cx, |this, cx| {
 7479            if let Some(mut clipboard_selections) = clipboard_selections {
 7480                let old_selections = this.selections.all::<usize>(cx);
 7481                let all_selections_were_entire_line =
 7482                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7483                let first_selection_indent_column =
 7484                    clipboard_selections.first().map(|s| s.first_line_indent);
 7485                if clipboard_selections.len() != old_selections.len() {
 7486                    clipboard_selections.drain(..);
 7487                }
 7488                let cursor_offset = this.selections.last::<usize>(cx).head();
 7489                let mut auto_indent_on_paste = true;
 7490
 7491                this.buffer.update(cx, |buffer, cx| {
 7492                    let snapshot = buffer.read(cx);
 7493                    auto_indent_on_paste =
 7494                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7495
 7496                    let mut start_offset = 0;
 7497                    let mut edits = Vec::new();
 7498                    let mut original_indent_columns = Vec::new();
 7499                    for (ix, selection) in old_selections.iter().enumerate() {
 7500                        let to_insert;
 7501                        let entire_line;
 7502                        let original_indent_column;
 7503                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7504                            let end_offset = start_offset + clipboard_selection.len;
 7505                            to_insert = &clipboard_text[start_offset..end_offset];
 7506                            entire_line = clipboard_selection.is_entire_line;
 7507                            start_offset = end_offset + 1;
 7508                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7509                        } else {
 7510                            to_insert = clipboard_text.as_str();
 7511                            entire_line = all_selections_were_entire_line;
 7512                            original_indent_column = first_selection_indent_column
 7513                        }
 7514
 7515                        // If the corresponding selection was empty when this slice of the
 7516                        // clipboard text was written, then the entire line containing the
 7517                        // selection was copied. If this selection is also currently empty,
 7518                        // then paste the line before the current line of the buffer.
 7519                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7520                            let column = selection.start.to_point(&snapshot).column as usize;
 7521                            let line_start = selection.start - column;
 7522                            line_start..line_start
 7523                        } else {
 7524                            selection.range()
 7525                        };
 7526
 7527                        edits.push((range, to_insert));
 7528                        original_indent_columns.extend(original_indent_column);
 7529                    }
 7530                    drop(snapshot);
 7531
 7532                    buffer.edit(
 7533                        edits,
 7534                        if auto_indent_on_paste {
 7535                            Some(AutoindentMode::Block {
 7536                                original_indent_columns,
 7537                            })
 7538                        } else {
 7539                            None
 7540                        },
 7541                        cx,
 7542                    );
 7543                });
 7544
 7545                let selections = this.selections.all::<usize>(cx);
 7546                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7547            } else {
 7548                this.insert(&clipboard_text, cx);
 7549            }
 7550        });
 7551    }
 7552
 7553    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7554        if let Some(item) = cx.read_from_clipboard() {
 7555            let entries = item.entries();
 7556
 7557            match entries.first() {
 7558                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7559                // of all the pasted entries.
 7560                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7561                    .do_paste(
 7562                        clipboard_string.text(),
 7563                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7564                        true,
 7565                        cx,
 7566                    ),
 7567                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7568            }
 7569        }
 7570    }
 7571
 7572    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7573        if self.read_only(cx) {
 7574            return;
 7575        }
 7576
 7577        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7578            if let Some((selections, _)) =
 7579                self.selection_history.transaction(transaction_id).cloned()
 7580            {
 7581                self.change_selections(None, cx, |s| {
 7582                    s.select_anchors(selections.to_vec());
 7583                });
 7584            }
 7585            self.request_autoscroll(Autoscroll::fit(), cx);
 7586            self.unmark_text(cx);
 7587            self.refresh_inline_completion(true, false, cx);
 7588            cx.emit(EditorEvent::Edited { transaction_id });
 7589            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7590        }
 7591    }
 7592
 7593    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7594        if self.read_only(cx) {
 7595            return;
 7596        }
 7597
 7598        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7599            if let Some((_, Some(selections))) =
 7600                self.selection_history.transaction(transaction_id).cloned()
 7601            {
 7602                self.change_selections(None, cx, |s| {
 7603                    s.select_anchors(selections.to_vec());
 7604                });
 7605            }
 7606            self.request_autoscroll(Autoscroll::fit(), cx);
 7607            self.unmark_text(cx);
 7608            self.refresh_inline_completion(true, false, cx);
 7609            cx.emit(EditorEvent::Edited { transaction_id });
 7610        }
 7611    }
 7612
 7613    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7614        self.buffer
 7615            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7616    }
 7617
 7618    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7619        self.buffer
 7620            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7621    }
 7622
 7623    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7624        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7625            let line_mode = s.line_mode;
 7626            s.move_with(|map, selection| {
 7627                let cursor = if selection.is_empty() && !line_mode {
 7628                    movement::left(map, selection.start)
 7629                } else {
 7630                    selection.start
 7631                };
 7632                selection.collapse_to(cursor, SelectionGoal::None);
 7633            });
 7634        })
 7635    }
 7636
 7637    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7638        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7639            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7640        })
 7641    }
 7642
 7643    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7644        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7645            let line_mode = s.line_mode;
 7646            s.move_with(|map, selection| {
 7647                let cursor = if selection.is_empty() && !line_mode {
 7648                    movement::right(map, selection.end)
 7649                } else {
 7650                    selection.end
 7651                };
 7652                selection.collapse_to(cursor, SelectionGoal::None)
 7653            });
 7654        })
 7655    }
 7656
 7657    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7658        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7659            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7660        })
 7661    }
 7662
 7663    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7664        if self.take_rename(true, cx).is_some() {
 7665            return;
 7666        }
 7667
 7668        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7669            cx.propagate();
 7670            return;
 7671        }
 7672
 7673        let text_layout_details = &self.text_layout_details(cx);
 7674        let selection_count = self.selections.count();
 7675        let first_selection = self.selections.first_anchor();
 7676
 7677        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7678            let line_mode = s.line_mode;
 7679            s.move_with(|map, selection| {
 7680                if !selection.is_empty() && !line_mode {
 7681                    selection.goal = SelectionGoal::None;
 7682                }
 7683                let (cursor, goal) = movement::up(
 7684                    map,
 7685                    selection.start,
 7686                    selection.goal,
 7687                    false,
 7688                    text_layout_details,
 7689                );
 7690                selection.collapse_to(cursor, goal);
 7691            });
 7692        });
 7693
 7694        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7695        {
 7696            cx.propagate();
 7697        }
 7698    }
 7699
 7700    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7701        if self.take_rename(true, cx).is_some() {
 7702            return;
 7703        }
 7704
 7705        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7706            cx.propagate();
 7707            return;
 7708        }
 7709
 7710        let text_layout_details = &self.text_layout_details(cx);
 7711
 7712        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7713            let line_mode = s.line_mode;
 7714            s.move_with(|map, selection| {
 7715                if !selection.is_empty() && !line_mode {
 7716                    selection.goal = SelectionGoal::None;
 7717                }
 7718                let (cursor, goal) = movement::up_by_rows(
 7719                    map,
 7720                    selection.start,
 7721                    action.lines,
 7722                    selection.goal,
 7723                    false,
 7724                    text_layout_details,
 7725                );
 7726                selection.collapse_to(cursor, goal);
 7727            });
 7728        })
 7729    }
 7730
 7731    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7732        if self.take_rename(true, cx).is_some() {
 7733            return;
 7734        }
 7735
 7736        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7737            cx.propagate();
 7738            return;
 7739        }
 7740
 7741        let text_layout_details = &self.text_layout_details(cx);
 7742
 7743        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7744            let line_mode = s.line_mode;
 7745            s.move_with(|map, selection| {
 7746                if !selection.is_empty() && !line_mode {
 7747                    selection.goal = SelectionGoal::None;
 7748                }
 7749                let (cursor, goal) = movement::down_by_rows(
 7750                    map,
 7751                    selection.start,
 7752                    action.lines,
 7753                    selection.goal,
 7754                    false,
 7755                    text_layout_details,
 7756                );
 7757                selection.collapse_to(cursor, goal);
 7758            });
 7759        })
 7760    }
 7761
 7762    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7763        let text_layout_details = &self.text_layout_details(cx);
 7764        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7765            s.move_heads_with(|map, head, goal| {
 7766                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7767            })
 7768        })
 7769    }
 7770
 7771    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7772        let text_layout_details = &self.text_layout_details(cx);
 7773        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7774            s.move_heads_with(|map, head, goal| {
 7775                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7776            })
 7777        })
 7778    }
 7779
 7780    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7781        let Some(row_count) = self.visible_row_count() else {
 7782            return;
 7783        };
 7784
 7785        let text_layout_details = &self.text_layout_details(cx);
 7786
 7787        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7788            s.move_heads_with(|map, head, goal| {
 7789                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7790            })
 7791        })
 7792    }
 7793
 7794    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7795        if self.take_rename(true, cx).is_some() {
 7796            return;
 7797        }
 7798
 7799        if self
 7800            .context_menu
 7801            .write()
 7802            .as_mut()
 7803            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7804            .unwrap_or(false)
 7805        {
 7806            return;
 7807        }
 7808
 7809        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7810            cx.propagate();
 7811            return;
 7812        }
 7813
 7814        let Some(row_count) = self.visible_row_count() else {
 7815            return;
 7816        };
 7817
 7818        let autoscroll = if action.center_cursor {
 7819            Autoscroll::center()
 7820        } else {
 7821            Autoscroll::fit()
 7822        };
 7823
 7824        let text_layout_details = &self.text_layout_details(cx);
 7825
 7826        self.change_selections(Some(autoscroll), cx, |s| {
 7827            let line_mode = s.line_mode;
 7828            s.move_with(|map, selection| {
 7829                if !selection.is_empty() && !line_mode {
 7830                    selection.goal = SelectionGoal::None;
 7831                }
 7832                let (cursor, goal) = movement::up_by_rows(
 7833                    map,
 7834                    selection.end,
 7835                    row_count,
 7836                    selection.goal,
 7837                    false,
 7838                    text_layout_details,
 7839                );
 7840                selection.collapse_to(cursor, goal);
 7841            });
 7842        });
 7843    }
 7844
 7845    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7846        let text_layout_details = &self.text_layout_details(cx);
 7847        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7848            s.move_heads_with(|map, head, goal| {
 7849                movement::up(map, head, goal, false, text_layout_details)
 7850            })
 7851        })
 7852    }
 7853
 7854    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7855        self.take_rename(true, cx);
 7856
 7857        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7858            cx.propagate();
 7859            return;
 7860        }
 7861
 7862        let text_layout_details = &self.text_layout_details(cx);
 7863        let selection_count = self.selections.count();
 7864        let first_selection = self.selections.first_anchor();
 7865
 7866        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7867            let line_mode = s.line_mode;
 7868            s.move_with(|map, selection| {
 7869                if !selection.is_empty() && !line_mode {
 7870                    selection.goal = SelectionGoal::None;
 7871                }
 7872                let (cursor, goal) = movement::down(
 7873                    map,
 7874                    selection.end,
 7875                    selection.goal,
 7876                    false,
 7877                    text_layout_details,
 7878                );
 7879                selection.collapse_to(cursor, goal);
 7880            });
 7881        });
 7882
 7883        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7884        {
 7885            cx.propagate();
 7886        }
 7887    }
 7888
 7889    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7890        let Some(row_count) = self.visible_row_count() else {
 7891            return;
 7892        };
 7893
 7894        let text_layout_details = &self.text_layout_details(cx);
 7895
 7896        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7897            s.move_heads_with(|map, head, goal| {
 7898                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7899            })
 7900        })
 7901    }
 7902
 7903    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7904        if self.take_rename(true, cx).is_some() {
 7905            return;
 7906        }
 7907
 7908        if self
 7909            .context_menu
 7910            .write()
 7911            .as_mut()
 7912            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7913            .unwrap_or(false)
 7914        {
 7915            return;
 7916        }
 7917
 7918        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7919            cx.propagate();
 7920            return;
 7921        }
 7922
 7923        let Some(row_count) = self.visible_row_count() else {
 7924            return;
 7925        };
 7926
 7927        let autoscroll = if action.center_cursor {
 7928            Autoscroll::center()
 7929        } else {
 7930            Autoscroll::fit()
 7931        };
 7932
 7933        let text_layout_details = &self.text_layout_details(cx);
 7934        self.change_selections(Some(autoscroll), cx, |s| {
 7935            let line_mode = s.line_mode;
 7936            s.move_with(|map, selection| {
 7937                if !selection.is_empty() && !line_mode {
 7938                    selection.goal = SelectionGoal::None;
 7939                }
 7940                let (cursor, goal) = movement::down_by_rows(
 7941                    map,
 7942                    selection.end,
 7943                    row_count,
 7944                    selection.goal,
 7945                    false,
 7946                    text_layout_details,
 7947                );
 7948                selection.collapse_to(cursor, goal);
 7949            });
 7950        });
 7951    }
 7952
 7953    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7954        let text_layout_details = &self.text_layout_details(cx);
 7955        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7956            s.move_heads_with(|map, head, goal| {
 7957                movement::down(map, head, goal, false, text_layout_details)
 7958            })
 7959        });
 7960    }
 7961
 7962    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7963        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7964            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7965        }
 7966    }
 7967
 7968    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7969        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7970            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7971        }
 7972    }
 7973
 7974    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7975        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7976            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7977        }
 7978    }
 7979
 7980    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7981        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7982            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7983        }
 7984    }
 7985
 7986    pub fn move_to_previous_word_start(
 7987        &mut self,
 7988        _: &MoveToPreviousWordStart,
 7989        cx: &mut ViewContext<Self>,
 7990    ) {
 7991        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7992            s.move_cursors_with(|map, head, _| {
 7993                (
 7994                    movement::previous_word_start(map, head),
 7995                    SelectionGoal::None,
 7996                )
 7997            });
 7998        })
 7999    }
 8000
 8001    pub fn move_to_previous_subword_start(
 8002        &mut self,
 8003        _: &MoveToPreviousSubwordStart,
 8004        cx: &mut ViewContext<Self>,
 8005    ) {
 8006        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8007            s.move_cursors_with(|map, head, _| {
 8008                (
 8009                    movement::previous_subword_start(map, head),
 8010                    SelectionGoal::None,
 8011                )
 8012            });
 8013        })
 8014    }
 8015
 8016    pub fn select_to_previous_word_start(
 8017        &mut self,
 8018        _: &SelectToPreviousWordStart,
 8019        cx: &mut ViewContext<Self>,
 8020    ) {
 8021        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8022            s.move_heads_with(|map, head, _| {
 8023                (
 8024                    movement::previous_word_start(map, head),
 8025                    SelectionGoal::None,
 8026                )
 8027            });
 8028        })
 8029    }
 8030
 8031    pub fn select_to_previous_subword_start(
 8032        &mut self,
 8033        _: &SelectToPreviousSubwordStart,
 8034        cx: &mut ViewContext<Self>,
 8035    ) {
 8036        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8037            s.move_heads_with(|map, head, _| {
 8038                (
 8039                    movement::previous_subword_start(map, head),
 8040                    SelectionGoal::None,
 8041                )
 8042            });
 8043        })
 8044    }
 8045
 8046    pub fn delete_to_previous_word_start(
 8047        &mut self,
 8048        action: &DeleteToPreviousWordStart,
 8049        cx: &mut ViewContext<Self>,
 8050    ) {
 8051        self.transact(cx, |this, cx| {
 8052            this.select_autoclose_pair(cx);
 8053            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8054                let line_mode = s.line_mode;
 8055                s.move_with(|map, selection| {
 8056                    if selection.is_empty() && !line_mode {
 8057                        let cursor = if action.ignore_newlines {
 8058                            movement::previous_word_start(map, selection.head())
 8059                        } else {
 8060                            movement::previous_word_start_or_newline(map, selection.head())
 8061                        };
 8062                        selection.set_head(cursor, SelectionGoal::None);
 8063                    }
 8064                });
 8065            });
 8066            this.insert("", cx);
 8067        });
 8068    }
 8069
 8070    pub fn delete_to_previous_subword_start(
 8071        &mut self,
 8072        _: &DeleteToPreviousSubwordStart,
 8073        cx: &mut ViewContext<Self>,
 8074    ) {
 8075        self.transact(cx, |this, cx| {
 8076            this.select_autoclose_pair(cx);
 8077            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8078                let line_mode = s.line_mode;
 8079                s.move_with(|map, selection| {
 8080                    if selection.is_empty() && !line_mode {
 8081                        let cursor = movement::previous_subword_start(map, selection.head());
 8082                        selection.set_head(cursor, SelectionGoal::None);
 8083                    }
 8084                });
 8085            });
 8086            this.insert("", cx);
 8087        });
 8088    }
 8089
 8090    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8091        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8092            s.move_cursors_with(|map, head, _| {
 8093                (movement::next_word_end(map, head), SelectionGoal::None)
 8094            });
 8095        })
 8096    }
 8097
 8098    pub fn move_to_next_subword_end(
 8099        &mut self,
 8100        _: &MoveToNextSubwordEnd,
 8101        cx: &mut ViewContext<Self>,
 8102    ) {
 8103        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8104            s.move_cursors_with(|map, head, _| {
 8105                (movement::next_subword_end(map, head), SelectionGoal::None)
 8106            });
 8107        })
 8108    }
 8109
 8110    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8111        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8112            s.move_heads_with(|map, head, _| {
 8113                (movement::next_word_end(map, head), SelectionGoal::None)
 8114            });
 8115        })
 8116    }
 8117
 8118    pub fn select_to_next_subword_end(
 8119        &mut self,
 8120        _: &SelectToNextSubwordEnd,
 8121        cx: &mut ViewContext<Self>,
 8122    ) {
 8123        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8124            s.move_heads_with(|map, head, _| {
 8125                (movement::next_subword_end(map, head), SelectionGoal::None)
 8126            });
 8127        })
 8128    }
 8129
 8130    pub fn delete_to_next_word_end(
 8131        &mut self,
 8132        action: &DeleteToNextWordEnd,
 8133        cx: &mut ViewContext<Self>,
 8134    ) {
 8135        self.transact(cx, |this, cx| {
 8136            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8137                let line_mode = s.line_mode;
 8138                s.move_with(|map, selection| {
 8139                    if selection.is_empty() && !line_mode {
 8140                        let cursor = if action.ignore_newlines {
 8141                            movement::next_word_end(map, selection.head())
 8142                        } else {
 8143                            movement::next_word_end_or_newline(map, selection.head())
 8144                        };
 8145                        selection.set_head(cursor, SelectionGoal::None);
 8146                    }
 8147                });
 8148            });
 8149            this.insert("", cx);
 8150        });
 8151    }
 8152
 8153    pub fn delete_to_next_subword_end(
 8154        &mut self,
 8155        _: &DeleteToNextSubwordEnd,
 8156        cx: &mut ViewContext<Self>,
 8157    ) {
 8158        self.transact(cx, |this, cx| {
 8159            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8160                s.move_with(|map, selection| {
 8161                    if selection.is_empty() {
 8162                        let cursor = movement::next_subword_end(map, selection.head());
 8163                        selection.set_head(cursor, SelectionGoal::None);
 8164                    }
 8165                });
 8166            });
 8167            this.insert("", cx);
 8168        });
 8169    }
 8170
 8171    pub fn move_to_beginning_of_line(
 8172        &mut self,
 8173        action: &MoveToBeginningOfLine,
 8174        cx: &mut ViewContext<Self>,
 8175    ) {
 8176        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8177            s.move_cursors_with(|map, head, _| {
 8178                (
 8179                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8180                    SelectionGoal::None,
 8181                )
 8182            });
 8183        })
 8184    }
 8185
 8186    pub fn select_to_beginning_of_line(
 8187        &mut self,
 8188        action: &SelectToBeginningOfLine,
 8189        cx: &mut ViewContext<Self>,
 8190    ) {
 8191        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8192            s.move_heads_with(|map, head, _| {
 8193                (
 8194                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8195                    SelectionGoal::None,
 8196                )
 8197            });
 8198        });
 8199    }
 8200
 8201    pub fn delete_to_beginning_of_line(
 8202        &mut self,
 8203        _: &DeleteToBeginningOfLine,
 8204        cx: &mut ViewContext<Self>,
 8205    ) {
 8206        self.transact(cx, |this, cx| {
 8207            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8208                s.move_with(|_, selection| {
 8209                    selection.reversed = true;
 8210                });
 8211            });
 8212
 8213            this.select_to_beginning_of_line(
 8214                &SelectToBeginningOfLine {
 8215                    stop_at_soft_wraps: false,
 8216                },
 8217                cx,
 8218            );
 8219            this.backspace(&Backspace, cx);
 8220        });
 8221    }
 8222
 8223    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8224        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8225            s.move_cursors_with(|map, head, _| {
 8226                (
 8227                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8228                    SelectionGoal::None,
 8229                )
 8230            });
 8231        })
 8232    }
 8233
 8234    pub fn select_to_end_of_line(
 8235        &mut self,
 8236        action: &SelectToEndOfLine,
 8237        cx: &mut ViewContext<Self>,
 8238    ) {
 8239        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8240            s.move_heads_with(|map, head, _| {
 8241                (
 8242                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8243                    SelectionGoal::None,
 8244                )
 8245            });
 8246        })
 8247    }
 8248
 8249    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8250        self.transact(cx, |this, cx| {
 8251            this.select_to_end_of_line(
 8252                &SelectToEndOfLine {
 8253                    stop_at_soft_wraps: false,
 8254                },
 8255                cx,
 8256            );
 8257            this.delete(&Delete, cx);
 8258        });
 8259    }
 8260
 8261    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8262        self.transact(cx, |this, cx| {
 8263            this.select_to_end_of_line(
 8264                &SelectToEndOfLine {
 8265                    stop_at_soft_wraps: false,
 8266                },
 8267                cx,
 8268            );
 8269            this.cut(&Cut, cx);
 8270        });
 8271    }
 8272
 8273    pub fn move_to_start_of_paragraph(
 8274        &mut self,
 8275        _: &MoveToStartOfParagraph,
 8276        cx: &mut ViewContext<Self>,
 8277    ) {
 8278        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8279            cx.propagate();
 8280            return;
 8281        }
 8282
 8283        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8284            s.move_with(|map, selection| {
 8285                selection.collapse_to(
 8286                    movement::start_of_paragraph(map, selection.head(), 1),
 8287                    SelectionGoal::None,
 8288                )
 8289            });
 8290        })
 8291    }
 8292
 8293    pub fn move_to_end_of_paragraph(
 8294        &mut self,
 8295        _: &MoveToEndOfParagraph,
 8296        cx: &mut ViewContext<Self>,
 8297    ) {
 8298        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8299            cx.propagate();
 8300            return;
 8301        }
 8302
 8303        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8304            s.move_with(|map, selection| {
 8305                selection.collapse_to(
 8306                    movement::end_of_paragraph(map, selection.head(), 1),
 8307                    SelectionGoal::None,
 8308                )
 8309            });
 8310        })
 8311    }
 8312
 8313    pub fn select_to_start_of_paragraph(
 8314        &mut self,
 8315        _: &SelectToStartOfParagraph,
 8316        cx: &mut ViewContext<Self>,
 8317    ) {
 8318        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8319            cx.propagate();
 8320            return;
 8321        }
 8322
 8323        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8324            s.move_heads_with(|map, head, _| {
 8325                (
 8326                    movement::start_of_paragraph(map, head, 1),
 8327                    SelectionGoal::None,
 8328                )
 8329            });
 8330        })
 8331    }
 8332
 8333    pub fn select_to_end_of_paragraph(
 8334        &mut self,
 8335        _: &SelectToEndOfParagraph,
 8336        cx: &mut ViewContext<Self>,
 8337    ) {
 8338        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8339            cx.propagate();
 8340            return;
 8341        }
 8342
 8343        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8344            s.move_heads_with(|map, head, _| {
 8345                (
 8346                    movement::end_of_paragraph(map, head, 1),
 8347                    SelectionGoal::None,
 8348                )
 8349            });
 8350        })
 8351    }
 8352
 8353    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8354        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8355            cx.propagate();
 8356            return;
 8357        }
 8358
 8359        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8360            s.select_ranges(vec![0..0]);
 8361        });
 8362    }
 8363
 8364    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8365        let mut selection = self.selections.last::<Point>(cx);
 8366        selection.set_head(Point::zero(), SelectionGoal::None);
 8367
 8368        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8369            s.select(vec![selection]);
 8370        });
 8371    }
 8372
 8373    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8374        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8375            cx.propagate();
 8376            return;
 8377        }
 8378
 8379        let cursor = self.buffer.read(cx).read(cx).len();
 8380        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8381            s.select_ranges(vec![cursor..cursor])
 8382        });
 8383    }
 8384
 8385    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8386        self.nav_history = nav_history;
 8387    }
 8388
 8389    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8390        self.nav_history.as_ref()
 8391    }
 8392
 8393    fn push_to_nav_history(
 8394        &mut self,
 8395        cursor_anchor: Anchor,
 8396        new_position: Option<Point>,
 8397        cx: &mut ViewContext<Self>,
 8398    ) {
 8399        if let Some(nav_history) = self.nav_history.as_mut() {
 8400            let buffer = self.buffer.read(cx).read(cx);
 8401            let cursor_position = cursor_anchor.to_point(&buffer);
 8402            let scroll_state = self.scroll_manager.anchor();
 8403            let scroll_top_row = scroll_state.top_row(&buffer);
 8404            drop(buffer);
 8405
 8406            if let Some(new_position) = new_position {
 8407                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8408                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8409                    return;
 8410                }
 8411            }
 8412
 8413            nav_history.push(
 8414                Some(NavigationData {
 8415                    cursor_anchor,
 8416                    cursor_position,
 8417                    scroll_anchor: scroll_state,
 8418                    scroll_top_row,
 8419                }),
 8420                cx,
 8421            );
 8422        }
 8423    }
 8424
 8425    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8426        let buffer = self.buffer.read(cx).snapshot(cx);
 8427        let mut selection = self.selections.first::<usize>(cx);
 8428        selection.set_head(buffer.len(), SelectionGoal::None);
 8429        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8430            s.select(vec![selection]);
 8431        });
 8432    }
 8433
 8434    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8435        let end = self.buffer.read(cx).read(cx).len();
 8436        self.change_selections(None, cx, |s| {
 8437            s.select_ranges(vec![0..end]);
 8438        });
 8439    }
 8440
 8441    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8442        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8443        let mut selections = self.selections.all::<Point>(cx);
 8444        let max_point = display_map.buffer_snapshot.max_point();
 8445        for selection in &mut selections {
 8446            let rows = selection.spanned_rows(true, &display_map);
 8447            selection.start = Point::new(rows.start.0, 0);
 8448            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8449            selection.reversed = false;
 8450        }
 8451        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8452            s.select(selections);
 8453        });
 8454    }
 8455
 8456    pub fn split_selection_into_lines(
 8457        &mut self,
 8458        _: &SplitSelectionIntoLines,
 8459        cx: &mut ViewContext<Self>,
 8460    ) {
 8461        let mut to_unfold = Vec::new();
 8462        let mut new_selection_ranges = Vec::new();
 8463        {
 8464            let selections = self.selections.all::<Point>(cx);
 8465            let buffer = self.buffer.read(cx).read(cx);
 8466            for selection in selections {
 8467                for row in selection.start.row..selection.end.row {
 8468                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8469                    new_selection_ranges.push(cursor..cursor);
 8470                }
 8471                new_selection_ranges.push(selection.end..selection.end);
 8472                to_unfold.push(selection.start..selection.end);
 8473            }
 8474        }
 8475        self.unfold_ranges(&to_unfold, true, true, cx);
 8476        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8477            s.select_ranges(new_selection_ranges);
 8478        });
 8479    }
 8480
 8481    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8482        self.add_selection(true, cx);
 8483    }
 8484
 8485    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8486        self.add_selection(false, cx);
 8487    }
 8488
 8489    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8490        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8491        let mut selections = self.selections.all::<Point>(cx);
 8492        let text_layout_details = self.text_layout_details(cx);
 8493        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8494            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8495            let range = oldest_selection.display_range(&display_map).sorted();
 8496
 8497            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8498            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8499            let positions = start_x.min(end_x)..start_x.max(end_x);
 8500
 8501            selections.clear();
 8502            let mut stack = Vec::new();
 8503            for row in range.start.row().0..=range.end.row().0 {
 8504                if let Some(selection) = self.selections.build_columnar_selection(
 8505                    &display_map,
 8506                    DisplayRow(row),
 8507                    &positions,
 8508                    oldest_selection.reversed,
 8509                    &text_layout_details,
 8510                ) {
 8511                    stack.push(selection.id);
 8512                    selections.push(selection);
 8513                }
 8514            }
 8515
 8516            if above {
 8517                stack.reverse();
 8518            }
 8519
 8520            AddSelectionsState { above, stack }
 8521        });
 8522
 8523        let last_added_selection = *state.stack.last().unwrap();
 8524        let mut new_selections = Vec::new();
 8525        if above == state.above {
 8526            let end_row = if above {
 8527                DisplayRow(0)
 8528            } else {
 8529                display_map.max_point().row()
 8530            };
 8531
 8532            'outer: for selection in selections {
 8533                if selection.id == last_added_selection {
 8534                    let range = selection.display_range(&display_map).sorted();
 8535                    debug_assert_eq!(range.start.row(), range.end.row());
 8536                    let mut row = range.start.row();
 8537                    let positions =
 8538                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8539                            px(start)..px(end)
 8540                        } else {
 8541                            let start_x =
 8542                                display_map.x_for_display_point(range.start, &text_layout_details);
 8543                            let end_x =
 8544                                display_map.x_for_display_point(range.end, &text_layout_details);
 8545                            start_x.min(end_x)..start_x.max(end_x)
 8546                        };
 8547
 8548                    while row != end_row {
 8549                        if above {
 8550                            row.0 -= 1;
 8551                        } else {
 8552                            row.0 += 1;
 8553                        }
 8554
 8555                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8556                            &display_map,
 8557                            row,
 8558                            &positions,
 8559                            selection.reversed,
 8560                            &text_layout_details,
 8561                        ) {
 8562                            state.stack.push(new_selection.id);
 8563                            if above {
 8564                                new_selections.push(new_selection);
 8565                                new_selections.push(selection);
 8566                            } else {
 8567                                new_selections.push(selection);
 8568                                new_selections.push(new_selection);
 8569                            }
 8570
 8571                            continue 'outer;
 8572                        }
 8573                    }
 8574                }
 8575
 8576                new_selections.push(selection);
 8577            }
 8578        } else {
 8579            new_selections = selections;
 8580            new_selections.retain(|s| s.id != last_added_selection);
 8581            state.stack.pop();
 8582        }
 8583
 8584        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8585            s.select(new_selections);
 8586        });
 8587        if state.stack.len() > 1 {
 8588            self.add_selections_state = Some(state);
 8589        }
 8590    }
 8591
 8592    pub fn select_next_match_internal(
 8593        &mut self,
 8594        display_map: &DisplaySnapshot,
 8595        replace_newest: bool,
 8596        autoscroll: Option<Autoscroll>,
 8597        cx: &mut ViewContext<Self>,
 8598    ) -> Result<()> {
 8599        fn select_next_match_ranges(
 8600            this: &mut Editor,
 8601            range: Range<usize>,
 8602            replace_newest: bool,
 8603            auto_scroll: Option<Autoscroll>,
 8604            cx: &mut ViewContext<Editor>,
 8605        ) {
 8606            this.unfold_ranges(&[range.clone()], false, true, cx);
 8607            this.change_selections(auto_scroll, cx, |s| {
 8608                if replace_newest {
 8609                    s.delete(s.newest_anchor().id);
 8610                }
 8611                s.insert_range(range.clone());
 8612            });
 8613        }
 8614
 8615        let buffer = &display_map.buffer_snapshot;
 8616        let mut selections = self.selections.all::<usize>(cx);
 8617        if let Some(mut select_next_state) = self.select_next_state.take() {
 8618            let query = &select_next_state.query;
 8619            if !select_next_state.done {
 8620                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8621                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8622                let mut next_selected_range = None;
 8623
 8624                let bytes_after_last_selection =
 8625                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8626                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8627                let query_matches = query
 8628                    .stream_find_iter(bytes_after_last_selection)
 8629                    .map(|result| (last_selection.end, result))
 8630                    .chain(
 8631                        query
 8632                            .stream_find_iter(bytes_before_first_selection)
 8633                            .map(|result| (0, result)),
 8634                    );
 8635
 8636                for (start_offset, query_match) in query_matches {
 8637                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8638                    let offset_range =
 8639                        start_offset + query_match.start()..start_offset + query_match.end();
 8640                    let display_range = offset_range.start.to_display_point(display_map)
 8641                        ..offset_range.end.to_display_point(display_map);
 8642
 8643                    if !select_next_state.wordwise
 8644                        || (!movement::is_inside_word(display_map, display_range.start)
 8645                            && !movement::is_inside_word(display_map, display_range.end))
 8646                    {
 8647                        // TODO: This is n^2, because we might check all the selections
 8648                        if !selections
 8649                            .iter()
 8650                            .any(|selection| selection.range().overlaps(&offset_range))
 8651                        {
 8652                            next_selected_range = Some(offset_range);
 8653                            break;
 8654                        }
 8655                    }
 8656                }
 8657
 8658                if let Some(next_selected_range) = next_selected_range {
 8659                    select_next_match_ranges(
 8660                        self,
 8661                        next_selected_range,
 8662                        replace_newest,
 8663                        autoscroll,
 8664                        cx,
 8665                    );
 8666                } else {
 8667                    select_next_state.done = true;
 8668                }
 8669            }
 8670
 8671            self.select_next_state = Some(select_next_state);
 8672        } else {
 8673            let mut only_carets = true;
 8674            let mut same_text_selected = true;
 8675            let mut selected_text = None;
 8676
 8677            let mut selections_iter = selections.iter().peekable();
 8678            while let Some(selection) = selections_iter.next() {
 8679                if selection.start != selection.end {
 8680                    only_carets = false;
 8681                }
 8682
 8683                if same_text_selected {
 8684                    if selected_text.is_none() {
 8685                        selected_text =
 8686                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8687                    }
 8688
 8689                    if let Some(next_selection) = selections_iter.peek() {
 8690                        if next_selection.range().len() == selection.range().len() {
 8691                            let next_selected_text = buffer
 8692                                .text_for_range(next_selection.range())
 8693                                .collect::<String>();
 8694                            if Some(next_selected_text) != selected_text {
 8695                                same_text_selected = false;
 8696                                selected_text = None;
 8697                            }
 8698                        } else {
 8699                            same_text_selected = false;
 8700                            selected_text = None;
 8701                        }
 8702                    }
 8703                }
 8704            }
 8705
 8706            if only_carets {
 8707                for selection in &mut selections {
 8708                    let word_range = movement::surrounding_word(
 8709                        display_map,
 8710                        selection.start.to_display_point(display_map),
 8711                    );
 8712                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8713                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8714                    selection.goal = SelectionGoal::None;
 8715                    selection.reversed = false;
 8716                    select_next_match_ranges(
 8717                        self,
 8718                        selection.start..selection.end,
 8719                        replace_newest,
 8720                        autoscroll,
 8721                        cx,
 8722                    );
 8723                }
 8724
 8725                if selections.len() == 1 {
 8726                    let selection = selections
 8727                        .last()
 8728                        .expect("ensured that there's only one selection");
 8729                    let query = buffer
 8730                        .text_for_range(selection.start..selection.end)
 8731                        .collect::<String>();
 8732                    let is_empty = query.is_empty();
 8733                    let select_state = SelectNextState {
 8734                        query: AhoCorasick::new(&[query])?,
 8735                        wordwise: true,
 8736                        done: is_empty,
 8737                    };
 8738                    self.select_next_state = Some(select_state);
 8739                } else {
 8740                    self.select_next_state = None;
 8741                }
 8742            } else if let Some(selected_text) = selected_text {
 8743                self.select_next_state = Some(SelectNextState {
 8744                    query: AhoCorasick::new(&[selected_text])?,
 8745                    wordwise: false,
 8746                    done: false,
 8747                });
 8748                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8749            }
 8750        }
 8751        Ok(())
 8752    }
 8753
 8754    pub fn select_all_matches(
 8755        &mut self,
 8756        _action: &SelectAllMatches,
 8757        cx: &mut ViewContext<Self>,
 8758    ) -> Result<()> {
 8759        self.push_to_selection_history();
 8760        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8761
 8762        self.select_next_match_internal(&display_map, false, None, cx)?;
 8763        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8764            return Ok(());
 8765        };
 8766        if select_next_state.done {
 8767            return Ok(());
 8768        }
 8769
 8770        let mut new_selections = self.selections.all::<usize>(cx);
 8771
 8772        let buffer = &display_map.buffer_snapshot;
 8773        let query_matches = select_next_state
 8774            .query
 8775            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8776
 8777        for query_match in query_matches {
 8778            let query_match = query_match.unwrap(); // can only fail due to I/O
 8779            let offset_range = query_match.start()..query_match.end();
 8780            let display_range = offset_range.start.to_display_point(&display_map)
 8781                ..offset_range.end.to_display_point(&display_map);
 8782
 8783            if !select_next_state.wordwise
 8784                || (!movement::is_inside_word(&display_map, display_range.start)
 8785                    && !movement::is_inside_word(&display_map, display_range.end))
 8786            {
 8787                self.selections.change_with(cx, |selections| {
 8788                    new_selections.push(Selection {
 8789                        id: selections.new_selection_id(),
 8790                        start: offset_range.start,
 8791                        end: offset_range.end,
 8792                        reversed: false,
 8793                        goal: SelectionGoal::None,
 8794                    });
 8795                });
 8796            }
 8797        }
 8798
 8799        new_selections.sort_by_key(|selection| selection.start);
 8800        let mut ix = 0;
 8801        while ix + 1 < new_selections.len() {
 8802            let current_selection = &new_selections[ix];
 8803            let next_selection = &new_selections[ix + 1];
 8804            if current_selection.range().overlaps(&next_selection.range()) {
 8805                if current_selection.id < next_selection.id {
 8806                    new_selections.remove(ix + 1);
 8807                } else {
 8808                    new_selections.remove(ix);
 8809                }
 8810            } else {
 8811                ix += 1;
 8812            }
 8813        }
 8814
 8815        select_next_state.done = true;
 8816        self.unfold_ranges(
 8817            &new_selections
 8818                .iter()
 8819                .map(|selection| selection.range())
 8820                .collect::<Vec<_>>(),
 8821            false,
 8822            false,
 8823            cx,
 8824        );
 8825        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8826            selections.select(new_selections)
 8827        });
 8828
 8829        Ok(())
 8830    }
 8831
 8832    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8833        self.push_to_selection_history();
 8834        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8835        self.select_next_match_internal(
 8836            &display_map,
 8837            action.replace_newest,
 8838            Some(Autoscroll::newest()),
 8839            cx,
 8840        )?;
 8841        Ok(())
 8842    }
 8843
 8844    pub fn select_previous(
 8845        &mut self,
 8846        action: &SelectPrevious,
 8847        cx: &mut ViewContext<Self>,
 8848    ) -> Result<()> {
 8849        self.push_to_selection_history();
 8850        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8851        let buffer = &display_map.buffer_snapshot;
 8852        let mut selections = self.selections.all::<usize>(cx);
 8853        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8854            let query = &select_prev_state.query;
 8855            if !select_prev_state.done {
 8856                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8857                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8858                let mut next_selected_range = None;
 8859                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8860                let bytes_before_last_selection =
 8861                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8862                let bytes_after_first_selection =
 8863                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8864                let query_matches = query
 8865                    .stream_find_iter(bytes_before_last_selection)
 8866                    .map(|result| (last_selection.start, result))
 8867                    .chain(
 8868                        query
 8869                            .stream_find_iter(bytes_after_first_selection)
 8870                            .map(|result| (buffer.len(), result)),
 8871                    );
 8872                for (end_offset, query_match) in query_matches {
 8873                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8874                    let offset_range =
 8875                        end_offset - query_match.end()..end_offset - query_match.start();
 8876                    let display_range = offset_range.start.to_display_point(&display_map)
 8877                        ..offset_range.end.to_display_point(&display_map);
 8878
 8879                    if !select_prev_state.wordwise
 8880                        || (!movement::is_inside_word(&display_map, display_range.start)
 8881                            && !movement::is_inside_word(&display_map, display_range.end))
 8882                    {
 8883                        next_selected_range = Some(offset_range);
 8884                        break;
 8885                    }
 8886                }
 8887
 8888                if let Some(next_selected_range) = next_selected_range {
 8889                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8890                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8891                        if action.replace_newest {
 8892                            s.delete(s.newest_anchor().id);
 8893                        }
 8894                        s.insert_range(next_selected_range);
 8895                    });
 8896                } else {
 8897                    select_prev_state.done = true;
 8898                }
 8899            }
 8900
 8901            self.select_prev_state = Some(select_prev_state);
 8902        } else {
 8903            let mut only_carets = true;
 8904            let mut same_text_selected = true;
 8905            let mut selected_text = None;
 8906
 8907            let mut selections_iter = selections.iter().peekable();
 8908            while let Some(selection) = selections_iter.next() {
 8909                if selection.start != selection.end {
 8910                    only_carets = false;
 8911                }
 8912
 8913                if same_text_selected {
 8914                    if selected_text.is_none() {
 8915                        selected_text =
 8916                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8917                    }
 8918
 8919                    if let Some(next_selection) = selections_iter.peek() {
 8920                        if next_selection.range().len() == selection.range().len() {
 8921                            let next_selected_text = buffer
 8922                                .text_for_range(next_selection.range())
 8923                                .collect::<String>();
 8924                            if Some(next_selected_text) != selected_text {
 8925                                same_text_selected = false;
 8926                                selected_text = None;
 8927                            }
 8928                        } else {
 8929                            same_text_selected = false;
 8930                            selected_text = None;
 8931                        }
 8932                    }
 8933                }
 8934            }
 8935
 8936            if only_carets {
 8937                for selection in &mut selections {
 8938                    let word_range = movement::surrounding_word(
 8939                        &display_map,
 8940                        selection.start.to_display_point(&display_map),
 8941                    );
 8942                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8943                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8944                    selection.goal = SelectionGoal::None;
 8945                    selection.reversed = false;
 8946                }
 8947                if selections.len() == 1 {
 8948                    let selection = selections
 8949                        .last()
 8950                        .expect("ensured that there's only one selection");
 8951                    let query = buffer
 8952                        .text_for_range(selection.start..selection.end)
 8953                        .collect::<String>();
 8954                    let is_empty = query.is_empty();
 8955                    let select_state = SelectNextState {
 8956                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8957                        wordwise: true,
 8958                        done: is_empty,
 8959                    };
 8960                    self.select_prev_state = Some(select_state);
 8961                } else {
 8962                    self.select_prev_state = None;
 8963                }
 8964
 8965                self.unfold_ranges(
 8966                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8967                    false,
 8968                    true,
 8969                    cx,
 8970                );
 8971                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8972                    s.select(selections);
 8973                });
 8974            } else if let Some(selected_text) = selected_text {
 8975                self.select_prev_state = Some(SelectNextState {
 8976                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8977                    wordwise: false,
 8978                    done: false,
 8979                });
 8980                self.select_previous(action, cx)?;
 8981            }
 8982        }
 8983        Ok(())
 8984    }
 8985
 8986    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8987        if self.read_only(cx) {
 8988            return;
 8989        }
 8990        let text_layout_details = &self.text_layout_details(cx);
 8991        self.transact(cx, |this, cx| {
 8992            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8993            let mut edits = Vec::new();
 8994            let mut selection_edit_ranges = Vec::new();
 8995            let mut last_toggled_row = None;
 8996            let snapshot = this.buffer.read(cx).read(cx);
 8997            let empty_str: Arc<str> = Arc::default();
 8998            let mut suffixes_inserted = Vec::new();
 8999            let ignore_indent = action.ignore_indent;
 9000
 9001            fn comment_prefix_range(
 9002                snapshot: &MultiBufferSnapshot,
 9003                row: MultiBufferRow,
 9004                comment_prefix: &str,
 9005                comment_prefix_whitespace: &str,
 9006                ignore_indent: bool,
 9007            ) -> Range<Point> {
 9008                let indent_size = if ignore_indent {
 9009                    0
 9010                } else {
 9011                    snapshot.indent_size_for_line(row).len
 9012                };
 9013
 9014                let start = Point::new(row.0, indent_size);
 9015
 9016                let mut line_bytes = snapshot
 9017                    .bytes_in_range(start..snapshot.max_point())
 9018                    .flatten()
 9019                    .copied();
 9020
 9021                // If this line currently begins with the line comment prefix, then record
 9022                // the range containing the prefix.
 9023                if line_bytes
 9024                    .by_ref()
 9025                    .take(comment_prefix.len())
 9026                    .eq(comment_prefix.bytes())
 9027                {
 9028                    // Include any whitespace that matches the comment prefix.
 9029                    let matching_whitespace_len = line_bytes
 9030                        .zip(comment_prefix_whitespace.bytes())
 9031                        .take_while(|(a, b)| a == b)
 9032                        .count() as u32;
 9033                    let end = Point::new(
 9034                        start.row,
 9035                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9036                    );
 9037                    start..end
 9038                } else {
 9039                    start..start
 9040                }
 9041            }
 9042
 9043            fn comment_suffix_range(
 9044                snapshot: &MultiBufferSnapshot,
 9045                row: MultiBufferRow,
 9046                comment_suffix: &str,
 9047                comment_suffix_has_leading_space: bool,
 9048            ) -> Range<Point> {
 9049                let end = Point::new(row.0, snapshot.line_len(row));
 9050                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9051
 9052                let mut line_end_bytes = snapshot
 9053                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9054                    .flatten()
 9055                    .copied();
 9056
 9057                let leading_space_len = if suffix_start_column > 0
 9058                    && line_end_bytes.next() == Some(b' ')
 9059                    && comment_suffix_has_leading_space
 9060                {
 9061                    1
 9062                } else {
 9063                    0
 9064                };
 9065
 9066                // If this line currently begins with the line comment prefix, then record
 9067                // the range containing the prefix.
 9068                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9069                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9070                    start..end
 9071                } else {
 9072                    end..end
 9073                }
 9074            }
 9075
 9076            // TODO: Handle selections that cross excerpts
 9077            for selection in &mut selections {
 9078                let start_column = snapshot
 9079                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9080                    .len;
 9081                let language = if let Some(language) =
 9082                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9083                {
 9084                    language
 9085                } else {
 9086                    continue;
 9087                };
 9088
 9089                selection_edit_ranges.clear();
 9090
 9091                // If multiple selections contain a given row, avoid processing that
 9092                // row more than once.
 9093                let mut start_row = MultiBufferRow(selection.start.row);
 9094                if last_toggled_row == Some(start_row) {
 9095                    start_row = start_row.next_row();
 9096                }
 9097                let end_row =
 9098                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9099                        MultiBufferRow(selection.end.row - 1)
 9100                    } else {
 9101                        MultiBufferRow(selection.end.row)
 9102                    };
 9103                last_toggled_row = Some(end_row);
 9104
 9105                if start_row > end_row {
 9106                    continue;
 9107                }
 9108
 9109                // If the language has line comments, toggle those.
 9110                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9111
 9112                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9113                if ignore_indent {
 9114                    full_comment_prefixes = full_comment_prefixes
 9115                        .into_iter()
 9116                        .map(|s| Arc::from(s.trim_end()))
 9117                        .collect();
 9118                }
 9119
 9120                if !full_comment_prefixes.is_empty() {
 9121                    let first_prefix = full_comment_prefixes
 9122                        .first()
 9123                        .expect("prefixes is non-empty");
 9124                    let prefix_trimmed_lengths = full_comment_prefixes
 9125                        .iter()
 9126                        .map(|p| p.trim_end_matches(' ').len())
 9127                        .collect::<SmallVec<[usize; 4]>>();
 9128
 9129                    let mut all_selection_lines_are_comments = true;
 9130
 9131                    for row in start_row.0..=end_row.0 {
 9132                        let row = MultiBufferRow(row);
 9133                        if start_row < end_row && snapshot.is_line_blank(row) {
 9134                            continue;
 9135                        }
 9136
 9137                        let prefix_range = full_comment_prefixes
 9138                            .iter()
 9139                            .zip(prefix_trimmed_lengths.iter().copied())
 9140                            .map(|(prefix, trimmed_prefix_len)| {
 9141                                comment_prefix_range(
 9142                                    snapshot.deref(),
 9143                                    row,
 9144                                    &prefix[..trimmed_prefix_len],
 9145                                    &prefix[trimmed_prefix_len..],
 9146                                    ignore_indent,
 9147                                )
 9148                            })
 9149                            .max_by_key(|range| range.end.column - range.start.column)
 9150                            .expect("prefixes is non-empty");
 9151
 9152                        if prefix_range.is_empty() {
 9153                            all_selection_lines_are_comments = false;
 9154                        }
 9155
 9156                        selection_edit_ranges.push(prefix_range);
 9157                    }
 9158
 9159                    if all_selection_lines_are_comments {
 9160                        edits.extend(
 9161                            selection_edit_ranges
 9162                                .iter()
 9163                                .cloned()
 9164                                .map(|range| (range, empty_str.clone())),
 9165                        );
 9166                    } else {
 9167                        let min_column = selection_edit_ranges
 9168                            .iter()
 9169                            .map(|range| range.start.column)
 9170                            .min()
 9171                            .unwrap_or(0);
 9172                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9173                            let position = Point::new(range.start.row, min_column);
 9174                            (position..position, first_prefix.clone())
 9175                        }));
 9176                    }
 9177                } else if let Some((full_comment_prefix, comment_suffix)) =
 9178                    language.block_comment_delimiters()
 9179                {
 9180                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9181                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9182                    let prefix_range = comment_prefix_range(
 9183                        snapshot.deref(),
 9184                        start_row,
 9185                        comment_prefix,
 9186                        comment_prefix_whitespace,
 9187                        ignore_indent,
 9188                    );
 9189                    let suffix_range = comment_suffix_range(
 9190                        snapshot.deref(),
 9191                        end_row,
 9192                        comment_suffix.trim_start_matches(' '),
 9193                        comment_suffix.starts_with(' '),
 9194                    );
 9195
 9196                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9197                        edits.push((
 9198                            prefix_range.start..prefix_range.start,
 9199                            full_comment_prefix.clone(),
 9200                        ));
 9201                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9202                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9203                    } else {
 9204                        edits.push((prefix_range, empty_str.clone()));
 9205                        edits.push((suffix_range, empty_str.clone()));
 9206                    }
 9207                } else {
 9208                    continue;
 9209                }
 9210            }
 9211
 9212            drop(snapshot);
 9213            this.buffer.update(cx, |buffer, cx| {
 9214                buffer.edit(edits, None, cx);
 9215            });
 9216
 9217            // Adjust selections so that they end before any comment suffixes that
 9218            // were inserted.
 9219            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9220            let mut selections = this.selections.all::<Point>(cx);
 9221            let snapshot = this.buffer.read(cx).read(cx);
 9222            for selection in &mut selections {
 9223                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9224                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9225                        Ordering::Less => {
 9226                            suffixes_inserted.next();
 9227                            continue;
 9228                        }
 9229                        Ordering::Greater => break,
 9230                        Ordering::Equal => {
 9231                            if selection.end.column == snapshot.line_len(row) {
 9232                                if selection.is_empty() {
 9233                                    selection.start.column -= suffix_len as u32;
 9234                                }
 9235                                selection.end.column -= suffix_len as u32;
 9236                            }
 9237                            break;
 9238                        }
 9239                    }
 9240                }
 9241            }
 9242
 9243            drop(snapshot);
 9244            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9245
 9246            let selections = this.selections.all::<Point>(cx);
 9247            let selections_on_single_row = selections.windows(2).all(|selections| {
 9248                selections[0].start.row == selections[1].start.row
 9249                    && selections[0].end.row == selections[1].end.row
 9250                    && selections[0].start.row == selections[0].end.row
 9251            });
 9252            let selections_selecting = selections
 9253                .iter()
 9254                .any(|selection| selection.start != selection.end);
 9255            let advance_downwards = action.advance_downwards
 9256                && selections_on_single_row
 9257                && !selections_selecting
 9258                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9259
 9260            if advance_downwards {
 9261                let snapshot = this.buffer.read(cx).snapshot(cx);
 9262
 9263                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9264                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9265                        let mut point = display_point.to_point(display_snapshot);
 9266                        point.row += 1;
 9267                        point = snapshot.clip_point(point, Bias::Left);
 9268                        let display_point = point.to_display_point(display_snapshot);
 9269                        let goal = SelectionGoal::HorizontalPosition(
 9270                            display_snapshot
 9271                                .x_for_display_point(display_point, text_layout_details)
 9272                                .into(),
 9273                        );
 9274                        (display_point, goal)
 9275                    })
 9276                });
 9277            }
 9278        });
 9279    }
 9280
 9281    pub fn select_enclosing_symbol(
 9282        &mut self,
 9283        _: &SelectEnclosingSymbol,
 9284        cx: &mut ViewContext<Self>,
 9285    ) {
 9286        let buffer = self.buffer.read(cx).snapshot(cx);
 9287        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9288
 9289        fn update_selection(
 9290            selection: &Selection<usize>,
 9291            buffer_snap: &MultiBufferSnapshot,
 9292        ) -> Option<Selection<usize>> {
 9293            let cursor = selection.head();
 9294            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9295            for symbol in symbols.iter().rev() {
 9296                let start = symbol.range.start.to_offset(buffer_snap);
 9297                let end = symbol.range.end.to_offset(buffer_snap);
 9298                let new_range = start..end;
 9299                if start < selection.start || end > selection.end {
 9300                    return Some(Selection {
 9301                        id: selection.id,
 9302                        start: new_range.start,
 9303                        end: new_range.end,
 9304                        goal: SelectionGoal::None,
 9305                        reversed: selection.reversed,
 9306                    });
 9307                }
 9308            }
 9309            None
 9310        }
 9311
 9312        let mut selected_larger_symbol = false;
 9313        let new_selections = old_selections
 9314            .iter()
 9315            .map(|selection| match update_selection(selection, &buffer) {
 9316                Some(new_selection) => {
 9317                    if new_selection.range() != selection.range() {
 9318                        selected_larger_symbol = true;
 9319                    }
 9320                    new_selection
 9321                }
 9322                None => selection.clone(),
 9323            })
 9324            .collect::<Vec<_>>();
 9325
 9326        if selected_larger_symbol {
 9327            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9328                s.select(new_selections);
 9329            });
 9330        }
 9331    }
 9332
 9333    pub fn select_larger_syntax_node(
 9334        &mut self,
 9335        _: &SelectLargerSyntaxNode,
 9336        cx: &mut ViewContext<Self>,
 9337    ) {
 9338        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9339        let buffer = self.buffer.read(cx).snapshot(cx);
 9340        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9341
 9342        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9343        let mut selected_larger_node = false;
 9344        let new_selections = old_selections
 9345            .iter()
 9346            .map(|selection| {
 9347                let old_range = selection.start..selection.end;
 9348                let mut new_range = old_range.clone();
 9349                while let Some(containing_range) =
 9350                    buffer.range_for_syntax_ancestor(new_range.clone())
 9351                {
 9352                    new_range = containing_range;
 9353                    if !display_map.intersects_fold(new_range.start)
 9354                        && !display_map.intersects_fold(new_range.end)
 9355                    {
 9356                        break;
 9357                    }
 9358                }
 9359
 9360                selected_larger_node |= new_range != old_range;
 9361                Selection {
 9362                    id: selection.id,
 9363                    start: new_range.start,
 9364                    end: new_range.end,
 9365                    goal: SelectionGoal::None,
 9366                    reversed: selection.reversed,
 9367                }
 9368            })
 9369            .collect::<Vec<_>>();
 9370
 9371        if selected_larger_node {
 9372            stack.push(old_selections);
 9373            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9374                s.select(new_selections);
 9375            });
 9376        }
 9377        self.select_larger_syntax_node_stack = stack;
 9378    }
 9379
 9380    pub fn select_smaller_syntax_node(
 9381        &mut self,
 9382        _: &SelectSmallerSyntaxNode,
 9383        cx: &mut ViewContext<Self>,
 9384    ) {
 9385        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9386        if let Some(selections) = stack.pop() {
 9387            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9388                s.select(selections.to_vec());
 9389            });
 9390        }
 9391        self.select_larger_syntax_node_stack = stack;
 9392    }
 9393
 9394    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9395        if !EditorSettings::get_global(cx).gutter.runnables {
 9396            self.clear_tasks();
 9397            return Task::ready(());
 9398        }
 9399        let project = self.project.as_ref().map(Model::downgrade);
 9400        cx.spawn(|this, mut cx| async move {
 9401            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9402            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9403                return;
 9404            };
 9405            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9406                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9407            }) else {
 9408                return;
 9409            };
 9410
 9411            let hide_runnables = project
 9412                .update(&mut cx, |project, cx| {
 9413                    // Do not display any test indicators in non-dev server remote projects.
 9414                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9415                })
 9416                .unwrap_or(true);
 9417            if hide_runnables {
 9418                return;
 9419            }
 9420            let new_rows =
 9421                cx.background_executor()
 9422                    .spawn({
 9423                        let snapshot = display_snapshot.clone();
 9424                        async move {
 9425                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9426                        }
 9427                    })
 9428                    .await;
 9429            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9430
 9431            this.update(&mut cx, |this, _| {
 9432                this.clear_tasks();
 9433                for (key, value) in rows {
 9434                    this.insert_tasks(key, value);
 9435                }
 9436            })
 9437            .ok();
 9438        })
 9439    }
 9440    fn fetch_runnable_ranges(
 9441        snapshot: &DisplaySnapshot,
 9442        range: Range<Anchor>,
 9443    ) -> Vec<language::RunnableRange> {
 9444        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9445    }
 9446
 9447    fn runnable_rows(
 9448        project: Model<Project>,
 9449        snapshot: DisplaySnapshot,
 9450        runnable_ranges: Vec<RunnableRange>,
 9451        mut cx: AsyncWindowContext,
 9452    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9453        runnable_ranges
 9454            .into_iter()
 9455            .filter_map(|mut runnable| {
 9456                let tasks = cx
 9457                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9458                    .ok()?;
 9459                if tasks.is_empty() {
 9460                    return None;
 9461                }
 9462
 9463                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9464
 9465                let row = snapshot
 9466                    .buffer_snapshot
 9467                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9468                    .1
 9469                    .start
 9470                    .row;
 9471
 9472                let context_range =
 9473                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9474                Some((
 9475                    (runnable.buffer_id, row),
 9476                    RunnableTasks {
 9477                        templates: tasks,
 9478                        offset: MultiBufferOffset(runnable.run_range.start),
 9479                        context_range,
 9480                        column: point.column,
 9481                        extra_variables: runnable.extra_captures,
 9482                    },
 9483                ))
 9484            })
 9485            .collect()
 9486    }
 9487
 9488    fn templates_with_tags(
 9489        project: &Model<Project>,
 9490        runnable: &mut Runnable,
 9491        cx: &WindowContext<'_>,
 9492    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9493        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9494            let (worktree_id, file) = project
 9495                .buffer_for_id(runnable.buffer, cx)
 9496                .and_then(|buffer| buffer.read(cx).file())
 9497                .map(|file| (file.worktree_id(cx), file.clone()))
 9498                .unzip();
 9499
 9500            (
 9501                project.task_store().read(cx).task_inventory().cloned(),
 9502                worktree_id,
 9503                file,
 9504            )
 9505        });
 9506
 9507        let tags = mem::take(&mut runnable.tags);
 9508        let mut tags: Vec<_> = tags
 9509            .into_iter()
 9510            .flat_map(|tag| {
 9511                let tag = tag.0.clone();
 9512                inventory
 9513                    .as_ref()
 9514                    .into_iter()
 9515                    .flat_map(|inventory| {
 9516                        inventory.read(cx).list_tasks(
 9517                            file.clone(),
 9518                            Some(runnable.language.clone()),
 9519                            worktree_id,
 9520                            cx,
 9521                        )
 9522                    })
 9523                    .filter(move |(_, template)| {
 9524                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9525                    })
 9526            })
 9527            .sorted_by_key(|(kind, _)| kind.to_owned())
 9528            .collect();
 9529        if let Some((leading_tag_source, _)) = tags.first() {
 9530            // Strongest source wins; if we have worktree tag binding, prefer that to
 9531            // global and language bindings;
 9532            // if we have a global binding, prefer that to language binding.
 9533            let first_mismatch = tags
 9534                .iter()
 9535                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9536            if let Some(index) = first_mismatch {
 9537                tags.truncate(index);
 9538            }
 9539        }
 9540
 9541        tags
 9542    }
 9543
 9544    pub fn move_to_enclosing_bracket(
 9545        &mut self,
 9546        _: &MoveToEnclosingBracket,
 9547        cx: &mut ViewContext<Self>,
 9548    ) {
 9549        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9550            s.move_offsets_with(|snapshot, selection| {
 9551                let Some(enclosing_bracket_ranges) =
 9552                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9553                else {
 9554                    return;
 9555                };
 9556
 9557                let mut best_length = usize::MAX;
 9558                let mut best_inside = false;
 9559                let mut best_in_bracket_range = false;
 9560                let mut best_destination = None;
 9561                for (open, close) in enclosing_bracket_ranges {
 9562                    let close = close.to_inclusive();
 9563                    let length = close.end() - open.start;
 9564                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9565                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9566                        || close.contains(&selection.head());
 9567
 9568                    // If best is next to a bracket and current isn't, skip
 9569                    if !in_bracket_range && best_in_bracket_range {
 9570                        continue;
 9571                    }
 9572
 9573                    // Prefer smaller lengths unless best is inside and current isn't
 9574                    if length > best_length && (best_inside || !inside) {
 9575                        continue;
 9576                    }
 9577
 9578                    best_length = length;
 9579                    best_inside = inside;
 9580                    best_in_bracket_range = in_bracket_range;
 9581                    best_destination = Some(
 9582                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9583                            if inside {
 9584                                open.end
 9585                            } else {
 9586                                open.start
 9587                            }
 9588                        } else if inside {
 9589                            *close.start()
 9590                        } else {
 9591                            *close.end()
 9592                        },
 9593                    );
 9594                }
 9595
 9596                if let Some(destination) = best_destination {
 9597                    selection.collapse_to(destination, SelectionGoal::None);
 9598                }
 9599            })
 9600        });
 9601    }
 9602
 9603    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9604        self.end_selection(cx);
 9605        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9606        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9607            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9608            self.select_next_state = entry.select_next_state;
 9609            self.select_prev_state = entry.select_prev_state;
 9610            self.add_selections_state = entry.add_selections_state;
 9611            self.request_autoscroll(Autoscroll::newest(), cx);
 9612        }
 9613        self.selection_history.mode = SelectionHistoryMode::Normal;
 9614    }
 9615
 9616    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9617        self.end_selection(cx);
 9618        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9619        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9620            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9621            self.select_next_state = entry.select_next_state;
 9622            self.select_prev_state = entry.select_prev_state;
 9623            self.add_selections_state = entry.add_selections_state;
 9624            self.request_autoscroll(Autoscroll::newest(), cx);
 9625        }
 9626        self.selection_history.mode = SelectionHistoryMode::Normal;
 9627    }
 9628
 9629    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9630        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9631    }
 9632
 9633    pub fn expand_excerpts_down(
 9634        &mut self,
 9635        action: &ExpandExcerptsDown,
 9636        cx: &mut ViewContext<Self>,
 9637    ) {
 9638        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9639    }
 9640
 9641    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9642        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9643    }
 9644
 9645    pub fn expand_excerpts_for_direction(
 9646        &mut self,
 9647        lines: u32,
 9648        direction: ExpandExcerptDirection,
 9649        cx: &mut ViewContext<Self>,
 9650    ) {
 9651        let selections = self.selections.disjoint_anchors();
 9652
 9653        let lines = if lines == 0 {
 9654            EditorSettings::get_global(cx).expand_excerpt_lines
 9655        } else {
 9656            lines
 9657        };
 9658
 9659        self.buffer.update(cx, |buffer, cx| {
 9660            buffer.expand_excerpts(
 9661                selections
 9662                    .iter()
 9663                    .map(|selection| selection.head().excerpt_id)
 9664                    .dedup(),
 9665                lines,
 9666                direction,
 9667                cx,
 9668            )
 9669        })
 9670    }
 9671
 9672    pub fn expand_excerpt(
 9673        &mut self,
 9674        excerpt: ExcerptId,
 9675        direction: ExpandExcerptDirection,
 9676        cx: &mut ViewContext<Self>,
 9677    ) {
 9678        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9679        self.buffer.update(cx, |buffer, cx| {
 9680            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9681        })
 9682    }
 9683
 9684    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9685        self.go_to_diagnostic_impl(Direction::Next, cx)
 9686    }
 9687
 9688    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9689        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9690    }
 9691
 9692    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9693        let buffer = self.buffer.read(cx).snapshot(cx);
 9694        let selection = self.selections.newest::<usize>(cx);
 9695
 9696        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9697        if direction == Direction::Next {
 9698            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9699                let (group_id, jump_to) = popover.activation_info();
 9700                if self.activate_diagnostics(group_id, cx) {
 9701                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9702                        let mut new_selection = s.newest_anchor().clone();
 9703                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9704                        s.select_anchors(vec![new_selection.clone()]);
 9705                    });
 9706                }
 9707                return;
 9708            }
 9709        }
 9710
 9711        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9712            active_diagnostics
 9713                .primary_range
 9714                .to_offset(&buffer)
 9715                .to_inclusive()
 9716        });
 9717        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9718            if active_primary_range.contains(&selection.head()) {
 9719                *active_primary_range.start()
 9720            } else {
 9721                selection.head()
 9722            }
 9723        } else {
 9724            selection.head()
 9725        };
 9726        let snapshot = self.snapshot(cx);
 9727        loop {
 9728            let diagnostics = if direction == Direction::Prev {
 9729                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9730            } else {
 9731                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9732            }
 9733            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9734            let group = diagnostics
 9735                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9736                // be sorted in a stable way
 9737                // skip until we are at current active diagnostic, if it exists
 9738                .skip_while(|entry| {
 9739                    (match direction {
 9740                        Direction::Prev => entry.range.start >= search_start,
 9741                        Direction::Next => entry.range.start <= search_start,
 9742                    }) && self
 9743                        .active_diagnostics
 9744                        .as_ref()
 9745                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9746                })
 9747                .find_map(|entry| {
 9748                    if entry.diagnostic.is_primary
 9749                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9750                        && !entry.range.is_empty()
 9751                        // if we match with the active diagnostic, skip it
 9752                        && Some(entry.diagnostic.group_id)
 9753                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9754                    {
 9755                        Some((entry.range, entry.diagnostic.group_id))
 9756                    } else {
 9757                        None
 9758                    }
 9759                });
 9760
 9761            if let Some((primary_range, group_id)) = group {
 9762                if self.activate_diagnostics(group_id, cx) {
 9763                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9764                        s.select(vec![Selection {
 9765                            id: selection.id,
 9766                            start: primary_range.start,
 9767                            end: primary_range.start,
 9768                            reversed: false,
 9769                            goal: SelectionGoal::None,
 9770                        }]);
 9771                    });
 9772                }
 9773                break;
 9774            } else {
 9775                // Cycle around to the start of the buffer, potentially moving back to the start of
 9776                // the currently active diagnostic.
 9777                active_primary_range.take();
 9778                if direction == Direction::Prev {
 9779                    if search_start == buffer.len() {
 9780                        break;
 9781                    } else {
 9782                        search_start = buffer.len();
 9783                    }
 9784                } else if search_start == 0 {
 9785                    break;
 9786                } else {
 9787                    search_start = 0;
 9788                }
 9789            }
 9790        }
 9791    }
 9792
 9793    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9794        let snapshot = self
 9795            .display_map
 9796            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9797        let selection = self.selections.newest::<Point>(cx);
 9798        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9799    }
 9800
 9801    fn go_to_hunk_after_position(
 9802        &mut self,
 9803        snapshot: &DisplaySnapshot,
 9804        position: Point,
 9805        cx: &mut ViewContext<'_, Editor>,
 9806    ) -> Option<MultiBufferDiffHunk> {
 9807        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9808            snapshot,
 9809            position,
 9810            false,
 9811            snapshot
 9812                .buffer_snapshot
 9813                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9814            cx,
 9815        ) {
 9816            return Some(hunk);
 9817        }
 9818
 9819        let wrapped_point = Point::zero();
 9820        self.go_to_next_hunk_in_direction(
 9821            snapshot,
 9822            wrapped_point,
 9823            true,
 9824            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9825                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9826            ),
 9827            cx,
 9828        )
 9829    }
 9830
 9831    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9832        let snapshot = self
 9833            .display_map
 9834            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9835        let selection = self.selections.newest::<Point>(cx);
 9836
 9837        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9838    }
 9839
 9840    fn go_to_hunk_before_position(
 9841        &mut self,
 9842        snapshot: &DisplaySnapshot,
 9843        position: Point,
 9844        cx: &mut ViewContext<'_, Editor>,
 9845    ) -> Option<MultiBufferDiffHunk> {
 9846        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9847            snapshot,
 9848            position,
 9849            false,
 9850            snapshot
 9851                .buffer_snapshot
 9852                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9853            cx,
 9854        ) {
 9855            return Some(hunk);
 9856        }
 9857
 9858        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9859        self.go_to_next_hunk_in_direction(
 9860            snapshot,
 9861            wrapped_point,
 9862            true,
 9863            snapshot
 9864                .buffer_snapshot
 9865                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9866            cx,
 9867        )
 9868    }
 9869
 9870    fn go_to_next_hunk_in_direction(
 9871        &mut self,
 9872        snapshot: &DisplaySnapshot,
 9873        initial_point: Point,
 9874        is_wrapped: bool,
 9875        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9876        cx: &mut ViewContext<Editor>,
 9877    ) -> Option<MultiBufferDiffHunk> {
 9878        let display_point = initial_point.to_display_point(snapshot);
 9879        let mut hunks = hunks
 9880            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9881            .filter(|(display_hunk, _)| {
 9882                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9883            })
 9884            .dedup();
 9885
 9886        if let Some((display_hunk, hunk)) = hunks.next() {
 9887            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9888                let row = display_hunk.start_display_row();
 9889                let point = DisplayPoint::new(row, 0);
 9890                s.select_display_ranges([point..point]);
 9891            });
 9892
 9893            Some(hunk)
 9894        } else {
 9895            None
 9896        }
 9897    }
 9898
 9899    pub fn go_to_definition(
 9900        &mut self,
 9901        _: &GoToDefinition,
 9902        cx: &mut ViewContext<Self>,
 9903    ) -> Task<Result<Navigated>> {
 9904        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9905        cx.spawn(|editor, mut cx| async move {
 9906            if definition.await? == Navigated::Yes {
 9907                return Ok(Navigated::Yes);
 9908            }
 9909            match editor.update(&mut cx, |editor, cx| {
 9910                editor.find_all_references(&FindAllReferences, cx)
 9911            })? {
 9912                Some(references) => references.await,
 9913                None => Ok(Navigated::No),
 9914            }
 9915        })
 9916    }
 9917
 9918    pub fn go_to_declaration(
 9919        &mut self,
 9920        _: &GoToDeclaration,
 9921        cx: &mut ViewContext<Self>,
 9922    ) -> Task<Result<Navigated>> {
 9923        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9924    }
 9925
 9926    pub fn go_to_declaration_split(
 9927        &mut self,
 9928        _: &GoToDeclaration,
 9929        cx: &mut ViewContext<Self>,
 9930    ) -> Task<Result<Navigated>> {
 9931        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9932    }
 9933
 9934    pub fn go_to_implementation(
 9935        &mut self,
 9936        _: &GoToImplementation,
 9937        cx: &mut ViewContext<Self>,
 9938    ) -> Task<Result<Navigated>> {
 9939        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9940    }
 9941
 9942    pub fn go_to_implementation_split(
 9943        &mut self,
 9944        _: &GoToImplementationSplit,
 9945        cx: &mut ViewContext<Self>,
 9946    ) -> Task<Result<Navigated>> {
 9947        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9948    }
 9949
 9950    pub fn go_to_type_definition(
 9951        &mut self,
 9952        _: &GoToTypeDefinition,
 9953        cx: &mut ViewContext<Self>,
 9954    ) -> Task<Result<Navigated>> {
 9955        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9956    }
 9957
 9958    pub fn go_to_definition_split(
 9959        &mut self,
 9960        _: &GoToDefinitionSplit,
 9961        cx: &mut ViewContext<Self>,
 9962    ) -> Task<Result<Navigated>> {
 9963        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9964    }
 9965
 9966    pub fn go_to_type_definition_split(
 9967        &mut self,
 9968        _: &GoToTypeDefinitionSplit,
 9969        cx: &mut ViewContext<Self>,
 9970    ) -> Task<Result<Navigated>> {
 9971        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9972    }
 9973
 9974    fn go_to_definition_of_kind(
 9975        &mut self,
 9976        kind: GotoDefinitionKind,
 9977        split: bool,
 9978        cx: &mut ViewContext<Self>,
 9979    ) -> Task<Result<Navigated>> {
 9980        let Some(provider) = self.semantics_provider.clone() else {
 9981            return Task::ready(Ok(Navigated::No));
 9982        };
 9983        let head = self.selections.newest::<usize>(cx).head();
 9984        let buffer = self.buffer.read(cx);
 9985        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9986            text_anchor
 9987        } else {
 9988            return Task::ready(Ok(Navigated::No));
 9989        };
 9990
 9991        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9992            return Task::ready(Ok(Navigated::No));
 9993        };
 9994
 9995        cx.spawn(|editor, mut cx| async move {
 9996            let definitions = definitions.await?;
 9997            let navigated = editor
 9998                .update(&mut cx, |editor, cx| {
 9999                    editor.navigate_to_hover_links(
10000                        Some(kind),
10001                        definitions
10002                            .into_iter()
10003                            .filter(|location| {
10004                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10005                            })
10006                            .map(HoverLink::Text)
10007                            .collect::<Vec<_>>(),
10008                        split,
10009                        cx,
10010                    )
10011                })?
10012                .await?;
10013            anyhow::Ok(navigated)
10014        })
10015    }
10016
10017    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
10018        let position = self.selections.newest_anchor().head();
10019        let Some((buffer, buffer_position)) =
10020            self.buffer.read(cx).text_anchor_for_position(position, cx)
10021        else {
10022            return;
10023        };
10024
10025        cx.spawn(|editor, mut cx| async move {
10026            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10027                editor.update(&mut cx, |_, cx| {
10028                    cx.open_url(&url);
10029                })
10030            } else {
10031                Ok(())
10032            }
10033        })
10034        .detach();
10035    }
10036
10037    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10038        let Some(workspace) = self.workspace() else {
10039            return;
10040        };
10041
10042        let position = self.selections.newest_anchor().head();
10043
10044        let Some((buffer, buffer_position)) =
10045            self.buffer.read(cx).text_anchor_for_position(position, cx)
10046        else {
10047            return;
10048        };
10049
10050        let project = self.project.clone();
10051
10052        cx.spawn(|_, mut cx| async move {
10053            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10054
10055            if let Some((_, path)) = result {
10056                workspace
10057                    .update(&mut cx, |workspace, cx| {
10058                        workspace.open_resolved_path(path, cx)
10059                    })?
10060                    .await?;
10061            }
10062            anyhow::Ok(())
10063        })
10064        .detach();
10065    }
10066
10067    pub(crate) fn navigate_to_hover_links(
10068        &mut self,
10069        kind: Option<GotoDefinitionKind>,
10070        mut definitions: Vec<HoverLink>,
10071        split: bool,
10072        cx: &mut ViewContext<Editor>,
10073    ) -> Task<Result<Navigated>> {
10074        // If there is one definition, just open it directly
10075        if definitions.len() == 1 {
10076            let definition = definitions.pop().unwrap();
10077
10078            enum TargetTaskResult {
10079                Location(Option<Location>),
10080                AlreadyNavigated,
10081            }
10082
10083            let target_task = match definition {
10084                HoverLink::Text(link) => {
10085                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10086                }
10087                HoverLink::InlayHint(lsp_location, server_id) => {
10088                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10089                    cx.background_executor().spawn(async move {
10090                        let location = computation.await?;
10091                        Ok(TargetTaskResult::Location(location))
10092                    })
10093                }
10094                HoverLink::Url(url) => {
10095                    cx.open_url(&url);
10096                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10097                }
10098                HoverLink::File(path) => {
10099                    if let Some(workspace) = self.workspace() {
10100                        cx.spawn(|_, mut cx| async move {
10101                            workspace
10102                                .update(&mut cx, |workspace, cx| {
10103                                    workspace.open_resolved_path(path, cx)
10104                                })?
10105                                .await
10106                                .map(|_| TargetTaskResult::AlreadyNavigated)
10107                        })
10108                    } else {
10109                        Task::ready(Ok(TargetTaskResult::Location(None)))
10110                    }
10111                }
10112            };
10113            cx.spawn(|editor, mut cx| async move {
10114                let target = match target_task.await.context("target resolution task")? {
10115                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10116                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10117                    TargetTaskResult::Location(Some(target)) => target,
10118                };
10119
10120                editor.update(&mut cx, |editor, cx| {
10121                    let Some(workspace) = editor.workspace() else {
10122                        return Navigated::No;
10123                    };
10124                    let pane = workspace.read(cx).active_pane().clone();
10125
10126                    let range = target.range.to_offset(target.buffer.read(cx));
10127                    let range = editor.range_for_match(&range);
10128
10129                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10130                        let buffer = target.buffer.read(cx);
10131                        let range = check_multiline_range(buffer, range);
10132                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10133                            s.select_ranges([range]);
10134                        });
10135                    } else {
10136                        cx.window_context().defer(move |cx| {
10137                            let target_editor: View<Self> =
10138                                workspace.update(cx, |workspace, cx| {
10139                                    let pane = if split {
10140                                        workspace.adjacent_pane(cx)
10141                                    } else {
10142                                        workspace.active_pane().clone()
10143                                    };
10144
10145                                    workspace.open_project_item(
10146                                        pane,
10147                                        target.buffer.clone(),
10148                                        true,
10149                                        true,
10150                                        cx,
10151                                    )
10152                                });
10153                            target_editor.update(cx, |target_editor, cx| {
10154                                // When selecting a definition in a different buffer, disable the nav history
10155                                // to avoid creating a history entry at the previous cursor location.
10156                                pane.update(cx, |pane, _| pane.disable_history());
10157                                let buffer = target.buffer.read(cx);
10158                                let range = check_multiline_range(buffer, range);
10159                                target_editor.change_selections(
10160                                    Some(Autoscroll::focused()),
10161                                    cx,
10162                                    |s| {
10163                                        s.select_ranges([range]);
10164                                    },
10165                                );
10166                                pane.update(cx, |pane, _| pane.enable_history());
10167                            });
10168                        });
10169                    }
10170                    Navigated::Yes
10171                })
10172            })
10173        } else if !definitions.is_empty() {
10174            cx.spawn(|editor, mut cx| async move {
10175                let (title, location_tasks, workspace) = editor
10176                    .update(&mut cx, |editor, cx| {
10177                        let tab_kind = match kind {
10178                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10179                            _ => "Definitions",
10180                        };
10181                        let title = definitions
10182                            .iter()
10183                            .find_map(|definition| match definition {
10184                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10185                                    let buffer = origin.buffer.read(cx);
10186                                    format!(
10187                                        "{} for {}",
10188                                        tab_kind,
10189                                        buffer
10190                                            .text_for_range(origin.range.clone())
10191                                            .collect::<String>()
10192                                    )
10193                                }),
10194                                HoverLink::InlayHint(_, _) => None,
10195                                HoverLink::Url(_) => None,
10196                                HoverLink::File(_) => None,
10197                            })
10198                            .unwrap_or(tab_kind.to_string());
10199                        let location_tasks = definitions
10200                            .into_iter()
10201                            .map(|definition| match definition {
10202                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10203                                HoverLink::InlayHint(lsp_location, server_id) => {
10204                                    editor.compute_target_location(lsp_location, server_id, cx)
10205                                }
10206                                HoverLink::Url(_) => Task::ready(Ok(None)),
10207                                HoverLink::File(_) => Task::ready(Ok(None)),
10208                            })
10209                            .collect::<Vec<_>>();
10210                        (title, location_tasks, editor.workspace().clone())
10211                    })
10212                    .context("location tasks preparation")?;
10213
10214                let locations = future::join_all(location_tasks)
10215                    .await
10216                    .into_iter()
10217                    .filter_map(|location| location.transpose())
10218                    .collect::<Result<_>>()
10219                    .context("location tasks")?;
10220
10221                let Some(workspace) = workspace else {
10222                    return Ok(Navigated::No);
10223                };
10224                let opened = workspace
10225                    .update(&mut cx, |workspace, cx| {
10226                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10227                    })
10228                    .ok();
10229
10230                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10231            })
10232        } else {
10233            Task::ready(Ok(Navigated::No))
10234        }
10235    }
10236
10237    fn compute_target_location(
10238        &self,
10239        lsp_location: lsp::Location,
10240        server_id: LanguageServerId,
10241        cx: &mut ViewContext<Self>,
10242    ) -> Task<anyhow::Result<Option<Location>>> {
10243        let Some(project) = self.project.clone() else {
10244            return Task::Ready(Some(Ok(None)));
10245        };
10246
10247        cx.spawn(move |editor, mut cx| async move {
10248            let location_task = editor.update(&mut cx, |_, cx| {
10249                project.update(cx, |project, cx| {
10250                    let language_server_name = project
10251                        .language_server_statuses(cx)
10252                        .find(|(id, _)| server_id == *id)
10253                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10254                    language_server_name.map(|language_server_name| {
10255                        project.open_local_buffer_via_lsp(
10256                            lsp_location.uri.clone(),
10257                            server_id,
10258                            language_server_name,
10259                            cx,
10260                        )
10261                    })
10262                })
10263            })?;
10264            let location = match location_task {
10265                Some(task) => Some({
10266                    let target_buffer_handle = task.await.context("open local buffer")?;
10267                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10268                        let target_start = target_buffer
10269                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10270                        let target_end = target_buffer
10271                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10272                        target_buffer.anchor_after(target_start)
10273                            ..target_buffer.anchor_before(target_end)
10274                    })?;
10275                    Location {
10276                        buffer: target_buffer_handle,
10277                        range,
10278                    }
10279                }),
10280                None => None,
10281            };
10282            Ok(location)
10283        })
10284    }
10285
10286    pub fn find_all_references(
10287        &mut self,
10288        _: &FindAllReferences,
10289        cx: &mut ViewContext<Self>,
10290    ) -> Option<Task<Result<Navigated>>> {
10291        let selection = self.selections.newest::<usize>(cx);
10292        let multi_buffer = self.buffer.read(cx);
10293        let head = selection.head();
10294
10295        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10296        let head_anchor = multi_buffer_snapshot.anchor_at(
10297            head,
10298            if head < selection.tail() {
10299                Bias::Right
10300            } else {
10301                Bias::Left
10302            },
10303        );
10304
10305        match self
10306            .find_all_references_task_sources
10307            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10308        {
10309            Ok(_) => {
10310                log::info!(
10311                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10312                );
10313                return None;
10314            }
10315            Err(i) => {
10316                self.find_all_references_task_sources.insert(i, head_anchor);
10317            }
10318        }
10319
10320        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10321        let workspace = self.workspace()?;
10322        let project = workspace.read(cx).project().clone();
10323        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10324        Some(cx.spawn(|editor, mut cx| async move {
10325            let _cleanup = defer({
10326                let mut cx = cx.clone();
10327                move || {
10328                    let _ = editor.update(&mut cx, |editor, _| {
10329                        if let Ok(i) =
10330                            editor
10331                                .find_all_references_task_sources
10332                                .binary_search_by(|anchor| {
10333                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10334                                })
10335                        {
10336                            editor.find_all_references_task_sources.remove(i);
10337                        }
10338                    });
10339                }
10340            });
10341
10342            let locations = references.await?;
10343            if locations.is_empty() {
10344                return anyhow::Ok(Navigated::No);
10345            }
10346
10347            workspace.update(&mut cx, |workspace, cx| {
10348                let title = locations
10349                    .first()
10350                    .as_ref()
10351                    .map(|location| {
10352                        let buffer = location.buffer.read(cx);
10353                        format!(
10354                            "References to `{}`",
10355                            buffer
10356                                .text_for_range(location.range.clone())
10357                                .collect::<String>()
10358                        )
10359                    })
10360                    .unwrap();
10361                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10362                Navigated::Yes
10363            })
10364        }))
10365    }
10366
10367    /// Opens a multibuffer with the given project locations in it
10368    pub fn open_locations_in_multibuffer(
10369        workspace: &mut Workspace,
10370        mut locations: Vec<Location>,
10371        title: String,
10372        split: bool,
10373        cx: &mut ViewContext<Workspace>,
10374    ) {
10375        // If there are multiple definitions, open them in a multibuffer
10376        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10377        let mut locations = locations.into_iter().peekable();
10378        let mut ranges_to_highlight = Vec::new();
10379        let capability = workspace.project().read(cx).capability();
10380
10381        let excerpt_buffer = cx.new_model(|cx| {
10382            let mut multibuffer = MultiBuffer::new(capability);
10383            while let Some(location) = locations.next() {
10384                let buffer = location.buffer.read(cx);
10385                let mut ranges_for_buffer = Vec::new();
10386                let range = location.range.to_offset(buffer);
10387                ranges_for_buffer.push(range.clone());
10388
10389                while let Some(next_location) = locations.peek() {
10390                    if next_location.buffer == location.buffer {
10391                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10392                        locations.next();
10393                    } else {
10394                        break;
10395                    }
10396                }
10397
10398                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10399                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10400                    location.buffer.clone(),
10401                    ranges_for_buffer,
10402                    DEFAULT_MULTIBUFFER_CONTEXT,
10403                    cx,
10404                ))
10405            }
10406
10407            multibuffer.with_title(title)
10408        });
10409
10410        let editor = cx.new_view(|cx| {
10411            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10412        });
10413        editor.update(cx, |editor, cx| {
10414            if let Some(first_range) = ranges_to_highlight.first() {
10415                editor.change_selections(None, cx, |selections| {
10416                    selections.clear_disjoint();
10417                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10418                });
10419            }
10420            editor.highlight_background::<Self>(
10421                &ranges_to_highlight,
10422                |theme| theme.editor_highlighted_line_background,
10423                cx,
10424            );
10425        });
10426
10427        let item = Box::new(editor);
10428        let item_id = item.item_id();
10429
10430        if split {
10431            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10432        } else {
10433            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10434                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10435                    pane.close_current_preview_item(cx)
10436                } else {
10437                    None
10438                }
10439            });
10440            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10441        }
10442        workspace.active_pane().update(cx, |pane, cx| {
10443            pane.set_preview_item_id(Some(item_id), cx);
10444        });
10445    }
10446
10447    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10448        use language::ToOffset as _;
10449
10450        let provider = self.semantics_provider.clone()?;
10451        let selection = self.selections.newest_anchor().clone();
10452        let (cursor_buffer, cursor_buffer_position) = self
10453            .buffer
10454            .read(cx)
10455            .text_anchor_for_position(selection.head(), cx)?;
10456        let (tail_buffer, cursor_buffer_position_end) = self
10457            .buffer
10458            .read(cx)
10459            .text_anchor_for_position(selection.tail(), cx)?;
10460        if tail_buffer != cursor_buffer {
10461            return None;
10462        }
10463
10464        let snapshot = cursor_buffer.read(cx).snapshot();
10465        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10466        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10467        let prepare_rename = provider
10468            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10469            .unwrap_or_else(|| Task::ready(Ok(None)));
10470        drop(snapshot);
10471
10472        Some(cx.spawn(|this, mut cx| async move {
10473            let rename_range = if let Some(range) = prepare_rename.await? {
10474                Some(range)
10475            } else {
10476                this.update(&mut cx, |this, cx| {
10477                    let buffer = this.buffer.read(cx).snapshot(cx);
10478                    let mut buffer_highlights = this
10479                        .document_highlights_for_position(selection.head(), &buffer)
10480                        .filter(|highlight| {
10481                            highlight.start.excerpt_id == selection.head().excerpt_id
10482                                && highlight.end.excerpt_id == selection.head().excerpt_id
10483                        });
10484                    buffer_highlights
10485                        .next()
10486                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10487                })?
10488            };
10489            if let Some(rename_range) = rename_range {
10490                this.update(&mut cx, |this, cx| {
10491                    let snapshot = cursor_buffer.read(cx).snapshot();
10492                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10493                    let cursor_offset_in_rename_range =
10494                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10495                    let cursor_offset_in_rename_range_end =
10496                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10497
10498                    this.take_rename(false, cx);
10499                    let buffer = this.buffer.read(cx).read(cx);
10500                    let cursor_offset = selection.head().to_offset(&buffer);
10501                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10502                    let rename_end = rename_start + rename_buffer_range.len();
10503                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10504                    let mut old_highlight_id = None;
10505                    let old_name: Arc<str> = buffer
10506                        .chunks(rename_start..rename_end, true)
10507                        .map(|chunk| {
10508                            if old_highlight_id.is_none() {
10509                                old_highlight_id = chunk.syntax_highlight_id;
10510                            }
10511                            chunk.text
10512                        })
10513                        .collect::<String>()
10514                        .into();
10515
10516                    drop(buffer);
10517
10518                    // Position the selection in the rename editor so that it matches the current selection.
10519                    this.show_local_selections = false;
10520                    let rename_editor = cx.new_view(|cx| {
10521                        let mut editor = Editor::single_line(cx);
10522                        editor.buffer.update(cx, |buffer, cx| {
10523                            buffer.edit([(0..0, old_name.clone())], None, cx)
10524                        });
10525                        let rename_selection_range = match cursor_offset_in_rename_range
10526                            .cmp(&cursor_offset_in_rename_range_end)
10527                        {
10528                            Ordering::Equal => {
10529                                editor.select_all(&SelectAll, cx);
10530                                return editor;
10531                            }
10532                            Ordering::Less => {
10533                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10534                            }
10535                            Ordering::Greater => {
10536                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10537                            }
10538                        };
10539                        if rename_selection_range.end > old_name.len() {
10540                            editor.select_all(&SelectAll, cx);
10541                        } else {
10542                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10543                                s.select_ranges([rename_selection_range]);
10544                            });
10545                        }
10546                        editor
10547                    });
10548                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10549                        if e == &EditorEvent::Focused {
10550                            cx.emit(EditorEvent::FocusedIn)
10551                        }
10552                    })
10553                    .detach();
10554
10555                    let write_highlights =
10556                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10557                    let read_highlights =
10558                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10559                    let ranges = write_highlights
10560                        .iter()
10561                        .flat_map(|(_, ranges)| ranges.iter())
10562                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10563                        .cloned()
10564                        .collect();
10565
10566                    this.highlight_text::<Rename>(
10567                        ranges,
10568                        HighlightStyle {
10569                            fade_out: Some(0.6),
10570                            ..Default::default()
10571                        },
10572                        cx,
10573                    );
10574                    let rename_focus_handle = rename_editor.focus_handle(cx);
10575                    cx.focus(&rename_focus_handle);
10576                    let block_id = this.insert_blocks(
10577                        [BlockProperties {
10578                            style: BlockStyle::Flex,
10579                            placement: BlockPlacement::Below(range.start),
10580                            height: 1,
10581                            render: Arc::new({
10582                                let rename_editor = rename_editor.clone();
10583                                move |cx: &mut BlockContext| {
10584                                    let mut text_style = cx.editor_style.text.clone();
10585                                    if let Some(highlight_style) = old_highlight_id
10586                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10587                                    {
10588                                        text_style = text_style.highlight(highlight_style);
10589                                    }
10590                                    div()
10591                                        .block_mouse_down()
10592                                        .pl(cx.anchor_x)
10593                                        .child(EditorElement::new(
10594                                            &rename_editor,
10595                                            EditorStyle {
10596                                                background: cx.theme().system().transparent,
10597                                                local_player: cx.editor_style.local_player,
10598                                                text: text_style,
10599                                                scrollbar_width: cx.editor_style.scrollbar_width,
10600                                                syntax: cx.editor_style.syntax.clone(),
10601                                                status: cx.editor_style.status.clone(),
10602                                                inlay_hints_style: HighlightStyle {
10603                                                    font_weight: Some(FontWeight::BOLD),
10604                                                    ..make_inlay_hints_style(cx)
10605                                                },
10606                                                suggestions_style: HighlightStyle {
10607                                                    color: Some(cx.theme().status().predictive),
10608                                                    ..HighlightStyle::default()
10609                                                },
10610                                                ..EditorStyle::default()
10611                                            },
10612                                        ))
10613                                        .into_any_element()
10614                                }
10615                            }),
10616                            priority: 0,
10617                        }],
10618                        Some(Autoscroll::fit()),
10619                        cx,
10620                    )[0];
10621                    this.pending_rename = Some(RenameState {
10622                        range,
10623                        old_name,
10624                        editor: rename_editor,
10625                        block_id,
10626                    });
10627                })?;
10628            }
10629
10630            Ok(())
10631        }))
10632    }
10633
10634    pub fn confirm_rename(
10635        &mut self,
10636        _: &ConfirmRename,
10637        cx: &mut ViewContext<Self>,
10638    ) -> Option<Task<Result<()>>> {
10639        let rename = self.take_rename(false, cx)?;
10640        let workspace = self.workspace()?.downgrade();
10641        let (buffer, start) = self
10642            .buffer
10643            .read(cx)
10644            .text_anchor_for_position(rename.range.start, cx)?;
10645        let (end_buffer, _) = self
10646            .buffer
10647            .read(cx)
10648            .text_anchor_for_position(rename.range.end, cx)?;
10649        if buffer != end_buffer {
10650            return None;
10651        }
10652
10653        let old_name = rename.old_name;
10654        let new_name = rename.editor.read(cx).text(cx);
10655
10656        let rename = self.semantics_provider.as_ref()?.perform_rename(
10657            &buffer,
10658            start,
10659            new_name.clone(),
10660            cx,
10661        )?;
10662
10663        Some(cx.spawn(|editor, mut cx| async move {
10664            let project_transaction = rename.await?;
10665            Self::open_project_transaction(
10666                &editor,
10667                workspace,
10668                project_transaction,
10669                format!("Rename: {}{}", old_name, new_name),
10670                cx.clone(),
10671            )
10672            .await?;
10673
10674            editor.update(&mut cx, |editor, cx| {
10675                editor.refresh_document_highlights(cx);
10676            })?;
10677            Ok(())
10678        }))
10679    }
10680
10681    fn take_rename(
10682        &mut self,
10683        moving_cursor: bool,
10684        cx: &mut ViewContext<Self>,
10685    ) -> Option<RenameState> {
10686        let rename = self.pending_rename.take()?;
10687        if rename.editor.focus_handle(cx).is_focused(cx) {
10688            cx.focus(&self.focus_handle);
10689        }
10690
10691        self.remove_blocks(
10692            [rename.block_id].into_iter().collect(),
10693            Some(Autoscroll::fit()),
10694            cx,
10695        );
10696        self.clear_highlights::<Rename>(cx);
10697        self.show_local_selections = true;
10698
10699        if moving_cursor {
10700            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10701                editor.selections.newest::<usize>(cx).head()
10702            });
10703
10704            // Update the selection to match the position of the selection inside
10705            // the rename editor.
10706            let snapshot = self.buffer.read(cx).read(cx);
10707            let rename_range = rename.range.to_offset(&snapshot);
10708            let cursor_in_editor = snapshot
10709                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10710                .min(rename_range.end);
10711            drop(snapshot);
10712
10713            self.change_selections(None, cx, |s| {
10714                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10715            });
10716        } else {
10717            self.refresh_document_highlights(cx);
10718        }
10719
10720        Some(rename)
10721    }
10722
10723    pub fn pending_rename(&self) -> Option<&RenameState> {
10724        self.pending_rename.as_ref()
10725    }
10726
10727    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10728        let project = match &self.project {
10729            Some(project) => project.clone(),
10730            None => return None,
10731        };
10732
10733        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10734    }
10735
10736    fn format_selections(
10737        &mut self,
10738        _: &FormatSelections,
10739        cx: &mut ViewContext<Self>,
10740    ) -> Option<Task<Result<()>>> {
10741        let project = match &self.project {
10742            Some(project) => project.clone(),
10743            None => return None,
10744        };
10745
10746        let selections = self
10747            .selections
10748            .all_adjusted(cx)
10749            .into_iter()
10750            .filter(|s| !s.is_empty())
10751            .collect_vec();
10752
10753        Some(self.perform_format(
10754            project,
10755            FormatTrigger::Manual,
10756            FormatTarget::Ranges(selections),
10757            cx,
10758        ))
10759    }
10760
10761    fn perform_format(
10762        &mut self,
10763        project: Model<Project>,
10764        trigger: FormatTrigger,
10765        target: FormatTarget,
10766        cx: &mut ViewContext<Self>,
10767    ) -> Task<Result<()>> {
10768        let buffer = self.buffer().clone();
10769        let mut buffers = buffer.read(cx).all_buffers();
10770        if trigger == FormatTrigger::Save {
10771            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10772        }
10773
10774        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10775        let format = project.update(cx, |project, cx| {
10776            project.format(buffers, true, trigger, target, cx)
10777        });
10778
10779        cx.spawn(|_, mut cx| async move {
10780            let transaction = futures::select_biased! {
10781                () = timeout => {
10782                    log::warn!("timed out waiting for formatting");
10783                    None
10784                }
10785                transaction = format.log_err().fuse() => transaction,
10786            };
10787
10788            buffer
10789                .update(&mut cx, |buffer, cx| {
10790                    if let Some(transaction) = transaction {
10791                        if !buffer.is_singleton() {
10792                            buffer.push_transaction(&transaction.0, cx);
10793                        }
10794                    }
10795
10796                    cx.notify();
10797                })
10798                .ok();
10799
10800            Ok(())
10801        })
10802    }
10803
10804    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10805        if let Some(project) = self.project.clone() {
10806            self.buffer.update(cx, |multi_buffer, cx| {
10807                project.update(cx, |project, cx| {
10808                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10809                });
10810            })
10811        }
10812    }
10813
10814    fn cancel_language_server_work(
10815        &mut self,
10816        _: &actions::CancelLanguageServerWork,
10817        cx: &mut ViewContext<Self>,
10818    ) {
10819        if let Some(project) = self.project.clone() {
10820            self.buffer.update(cx, |multi_buffer, cx| {
10821                project.update(cx, |project, cx| {
10822                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10823                });
10824            })
10825        }
10826    }
10827
10828    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10829        cx.show_character_palette();
10830    }
10831
10832    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10833        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10834            let buffer = self.buffer.read(cx).snapshot(cx);
10835            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10836            let is_valid = buffer
10837                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10838                .any(|entry| {
10839                    entry.diagnostic.is_primary
10840                        && !entry.range.is_empty()
10841                        && entry.range.start == primary_range_start
10842                        && entry.diagnostic.message == active_diagnostics.primary_message
10843                });
10844
10845            if is_valid != active_diagnostics.is_valid {
10846                active_diagnostics.is_valid = is_valid;
10847                let mut new_styles = HashMap::default();
10848                for (block_id, diagnostic) in &active_diagnostics.blocks {
10849                    new_styles.insert(
10850                        *block_id,
10851                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10852                    );
10853                }
10854                self.display_map.update(cx, |display_map, _cx| {
10855                    display_map.replace_blocks(new_styles)
10856                });
10857            }
10858        }
10859    }
10860
10861    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10862        self.dismiss_diagnostics(cx);
10863        let snapshot = self.snapshot(cx);
10864        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10865            let buffer = self.buffer.read(cx).snapshot(cx);
10866
10867            let mut primary_range = None;
10868            let mut primary_message = None;
10869            let mut group_end = Point::zero();
10870            let diagnostic_group = buffer
10871                .diagnostic_group::<MultiBufferPoint>(group_id)
10872                .filter_map(|entry| {
10873                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10874                        && (entry.range.start.row == entry.range.end.row
10875                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10876                    {
10877                        return None;
10878                    }
10879                    if entry.range.end > group_end {
10880                        group_end = entry.range.end;
10881                    }
10882                    if entry.diagnostic.is_primary {
10883                        primary_range = Some(entry.range.clone());
10884                        primary_message = Some(entry.diagnostic.message.clone());
10885                    }
10886                    Some(entry)
10887                })
10888                .collect::<Vec<_>>();
10889            let primary_range = primary_range?;
10890            let primary_message = primary_message?;
10891            let primary_range =
10892                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10893
10894            let blocks = display_map
10895                .insert_blocks(
10896                    diagnostic_group.iter().map(|entry| {
10897                        let diagnostic = entry.diagnostic.clone();
10898                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10899                        BlockProperties {
10900                            style: BlockStyle::Fixed,
10901                            placement: BlockPlacement::Below(
10902                                buffer.anchor_after(entry.range.start),
10903                            ),
10904                            height: message_height,
10905                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10906                            priority: 0,
10907                        }
10908                    }),
10909                    cx,
10910                )
10911                .into_iter()
10912                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10913                .collect();
10914
10915            Some(ActiveDiagnosticGroup {
10916                primary_range,
10917                primary_message,
10918                group_id,
10919                blocks,
10920                is_valid: true,
10921            })
10922        });
10923        self.active_diagnostics.is_some()
10924    }
10925
10926    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10927        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10928            self.display_map.update(cx, |display_map, cx| {
10929                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10930            });
10931            cx.notify();
10932        }
10933    }
10934
10935    pub fn set_selections_from_remote(
10936        &mut self,
10937        selections: Vec<Selection<Anchor>>,
10938        pending_selection: Option<Selection<Anchor>>,
10939        cx: &mut ViewContext<Self>,
10940    ) {
10941        let old_cursor_position = self.selections.newest_anchor().head();
10942        self.selections.change_with(cx, |s| {
10943            s.select_anchors(selections);
10944            if let Some(pending_selection) = pending_selection {
10945                s.set_pending(pending_selection, SelectMode::Character);
10946            } else {
10947                s.clear_pending();
10948            }
10949        });
10950        self.selections_did_change(false, &old_cursor_position, true, cx);
10951    }
10952
10953    fn push_to_selection_history(&mut self) {
10954        self.selection_history.push(SelectionHistoryEntry {
10955            selections: self.selections.disjoint_anchors(),
10956            select_next_state: self.select_next_state.clone(),
10957            select_prev_state: self.select_prev_state.clone(),
10958            add_selections_state: self.add_selections_state.clone(),
10959        });
10960    }
10961
10962    pub fn transact(
10963        &mut self,
10964        cx: &mut ViewContext<Self>,
10965        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10966    ) -> Option<TransactionId> {
10967        self.start_transaction_at(Instant::now(), cx);
10968        update(self, cx);
10969        self.end_transaction_at(Instant::now(), cx)
10970    }
10971
10972    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10973        self.end_selection(cx);
10974        if let Some(tx_id) = self
10975            .buffer
10976            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10977        {
10978            self.selection_history
10979                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10980            cx.emit(EditorEvent::TransactionBegun {
10981                transaction_id: tx_id,
10982            })
10983        }
10984    }
10985
10986    fn end_transaction_at(
10987        &mut self,
10988        now: Instant,
10989        cx: &mut ViewContext<Self>,
10990    ) -> Option<TransactionId> {
10991        if let Some(transaction_id) = self
10992            .buffer
10993            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10994        {
10995            if let Some((_, end_selections)) =
10996                self.selection_history.transaction_mut(transaction_id)
10997            {
10998                *end_selections = Some(self.selections.disjoint_anchors());
10999            } else {
11000                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11001            }
11002
11003            cx.emit(EditorEvent::Edited { transaction_id });
11004            Some(transaction_id)
11005        } else {
11006            None
11007        }
11008    }
11009
11010    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
11011        let selection = self.selections.newest::<Point>(cx);
11012
11013        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11014        let range = if selection.is_empty() {
11015            let point = selection.head().to_display_point(&display_map);
11016            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11017            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11018                .to_point(&display_map);
11019            start..end
11020        } else {
11021            selection.range()
11022        };
11023        if display_map.folds_in_range(range).next().is_some() {
11024            self.unfold_lines(&Default::default(), cx)
11025        } else {
11026            self.fold(&Default::default(), cx)
11027        }
11028    }
11029
11030    pub fn toggle_fold_recursive(
11031        &mut self,
11032        _: &actions::ToggleFoldRecursive,
11033        cx: &mut ViewContext<Self>,
11034    ) {
11035        let selection = self.selections.newest::<Point>(cx);
11036
11037        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11038        let range = if selection.is_empty() {
11039            let point = selection.head().to_display_point(&display_map);
11040            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11041            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11042                .to_point(&display_map);
11043            start..end
11044        } else {
11045            selection.range()
11046        };
11047        if display_map.folds_in_range(range).next().is_some() {
11048            self.unfold_recursive(&Default::default(), cx)
11049        } else {
11050            self.fold_recursive(&Default::default(), cx)
11051        }
11052    }
11053
11054    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11055        let mut to_fold = Vec::new();
11056        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11057        let selections = self.selections.all_adjusted(cx);
11058
11059        for selection in selections {
11060            let range = selection.range().sorted();
11061            let buffer_start_row = range.start.row;
11062
11063            if range.start.row != range.end.row {
11064                let mut found = false;
11065                let mut row = range.start.row;
11066                while row <= range.end.row {
11067                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11068                        found = true;
11069                        row = crease.range().end.row + 1;
11070                        to_fold.push(crease);
11071                    } else {
11072                        row += 1
11073                    }
11074                }
11075                if found {
11076                    continue;
11077                }
11078            }
11079
11080            for row in (0..=range.start.row).rev() {
11081                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11082                    if crease.range().end.row >= buffer_start_row {
11083                        to_fold.push(crease);
11084                        if row <= range.start.row {
11085                            break;
11086                        }
11087                    }
11088                }
11089            }
11090        }
11091
11092        self.fold_creases(to_fold, true, cx);
11093    }
11094
11095    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11096        let fold_at_level = fold_at.level;
11097        let snapshot = self.buffer.read(cx).snapshot(cx);
11098        let mut to_fold = Vec::new();
11099        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11100
11101        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11102            while start_row < end_row {
11103                match self
11104                    .snapshot(cx)
11105                    .crease_for_buffer_row(MultiBufferRow(start_row))
11106                {
11107                    Some(crease) => {
11108                        let nested_start_row = crease.range().start.row + 1;
11109                        let nested_end_row = crease.range().end.row;
11110
11111                        if current_level < fold_at_level {
11112                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11113                        } else if current_level == fold_at_level {
11114                            to_fold.push(crease);
11115                        }
11116
11117                        start_row = nested_end_row + 1;
11118                    }
11119                    None => start_row += 1,
11120                }
11121            }
11122        }
11123
11124        self.fold_creases(to_fold, true, cx);
11125    }
11126
11127    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11128        let mut fold_ranges = Vec::new();
11129        let snapshot = self.buffer.read(cx).snapshot(cx);
11130
11131        for row in 0..snapshot.max_buffer_row().0 {
11132            if let Some(foldable_range) =
11133                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11134            {
11135                fold_ranges.push(foldable_range);
11136            }
11137        }
11138
11139        self.fold_creases(fold_ranges, true, cx);
11140    }
11141
11142    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11143        let mut to_fold = Vec::new();
11144        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11145        let selections = self.selections.all_adjusted(cx);
11146
11147        for selection in selections {
11148            let range = selection.range().sorted();
11149            let buffer_start_row = range.start.row;
11150
11151            if range.start.row != range.end.row {
11152                let mut found = false;
11153                for row in range.start.row..=range.end.row {
11154                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11155                        found = true;
11156                        to_fold.push(crease);
11157                    }
11158                }
11159                if found {
11160                    continue;
11161                }
11162            }
11163
11164            for row in (0..=range.start.row).rev() {
11165                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11166                    if crease.range().end.row >= buffer_start_row {
11167                        to_fold.push(crease);
11168                    } else {
11169                        break;
11170                    }
11171                }
11172            }
11173        }
11174
11175        self.fold_creases(to_fold, true, cx);
11176    }
11177
11178    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11179        let buffer_row = fold_at.buffer_row;
11180        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11181
11182        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11183            let autoscroll = self
11184                .selections
11185                .all::<Point>(cx)
11186                .iter()
11187                .any(|selection| crease.range().overlaps(&selection.range()));
11188
11189            self.fold_creases(vec![crease], autoscroll, cx);
11190        }
11191    }
11192
11193    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11194        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11195        let buffer = &display_map.buffer_snapshot;
11196        let selections = self.selections.all::<Point>(cx);
11197        let ranges = selections
11198            .iter()
11199            .map(|s| {
11200                let range = s.display_range(&display_map).sorted();
11201                let mut start = range.start.to_point(&display_map);
11202                let mut end = range.end.to_point(&display_map);
11203                start.column = 0;
11204                end.column = buffer.line_len(MultiBufferRow(end.row));
11205                start..end
11206            })
11207            .collect::<Vec<_>>();
11208
11209        self.unfold_ranges(&ranges, true, true, cx);
11210    }
11211
11212    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11213        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11214        let selections = self.selections.all::<Point>(cx);
11215        let ranges = selections
11216            .iter()
11217            .map(|s| {
11218                let mut range = s.display_range(&display_map).sorted();
11219                *range.start.column_mut() = 0;
11220                *range.end.column_mut() = display_map.line_len(range.end.row());
11221                let start = range.start.to_point(&display_map);
11222                let end = range.end.to_point(&display_map);
11223                start..end
11224            })
11225            .collect::<Vec<_>>();
11226
11227        self.unfold_ranges(&ranges, true, true, cx);
11228    }
11229
11230    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11231        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11232
11233        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11234            ..Point::new(
11235                unfold_at.buffer_row.0,
11236                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11237            );
11238
11239        let autoscroll = self
11240            .selections
11241            .all::<Point>(cx)
11242            .iter()
11243            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11244
11245        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11246    }
11247
11248    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11249        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11250        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11251    }
11252
11253    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11254        let selections = self.selections.all::<Point>(cx);
11255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11256        let line_mode = self.selections.line_mode;
11257        let ranges = selections
11258            .into_iter()
11259            .map(|s| {
11260                if line_mode {
11261                    let start = Point::new(s.start.row, 0);
11262                    let end = Point::new(
11263                        s.end.row,
11264                        display_map
11265                            .buffer_snapshot
11266                            .line_len(MultiBufferRow(s.end.row)),
11267                    );
11268                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11269                } else {
11270                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11271                }
11272            })
11273            .collect::<Vec<_>>();
11274        self.fold_creases(ranges, true, cx);
11275    }
11276
11277    pub fn fold_creases<T: ToOffset + Clone>(
11278        &mut self,
11279        creases: Vec<Crease<T>>,
11280        auto_scroll: bool,
11281        cx: &mut ViewContext<Self>,
11282    ) {
11283        if creases.is_empty() {
11284            return;
11285        }
11286
11287        let mut buffers_affected = HashMap::default();
11288        let multi_buffer = self.buffer().read(cx);
11289        for crease in &creases {
11290            if let Some((_, buffer, _)) =
11291                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11292            {
11293                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11294            };
11295        }
11296
11297        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11298
11299        if auto_scroll {
11300            self.request_autoscroll(Autoscroll::fit(), cx);
11301        }
11302
11303        for buffer in buffers_affected.into_values() {
11304            self.sync_expanded_diff_hunks(buffer, cx);
11305        }
11306
11307        cx.notify();
11308
11309        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11310            // Clear diagnostics block when folding a range that contains it.
11311            let snapshot = self.snapshot(cx);
11312            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11313                drop(snapshot);
11314                self.active_diagnostics = Some(active_diagnostics);
11315                self.dismiss_diagnostics(cx);
11316            } else {
11317                self.active_diagnostics = Some(active_diagnostics);
11318            }
11319        }
11320
11321        self.scrollbar_marker_state.dirty = true;
11322    }
11323
11324    /// Removes any folds whose ranges intersect any of the given ranges.
11325    pub fn unfold_ranges<T: ToOffset + Clone>(
11326        &mut self,
11327        ranges: &[Range<T>],
11328        inclusive: bool,
11329        auto_scroll: bool,
11330        cx: &mut ViewContext<Self>,
11331    ) {
11332        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11333            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11334        });
11335    }
11336
11337    /// Removes any folds with the given ranges.
11338    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11339        &mut self,
11340        ranges: &[Range<T>],
11341        type_id: TypeId,
11342        auto_scroll: bool,
11343        cx: &mut ViewContext<Self>,
11344    ) {
11345        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11346            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11347        });
11348    }
11349
11350    fn remove_folds_with<T: ToOffset + Clone>(
11351        &mut self,
11352        ranges: &[Range<T>],
11353        auto_scroll: bool,
11354        cx: &mut ViewContext<Self>,
11355        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11356    ) {
11357        if ranges.is_empty() {
11358            return;
11359        }
11360
11361        let mut buffers_affected = HashMap::default();
11362        let multi_buffer = self.buffer().read(cx);
11363        for range in ranges {
11364            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11365                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11366            };
11367        }
11368
11369        self.display_map.update(cx, update);
11370
11371        if auto_scroll {
11372            self.request_autoscroll(Autoscroll::fit(), cx);
11373        }
11374
11375        for buffer in buffers_affected.into_values() {
11376            self.sync_expanded_diff_hunks(buffer, cx);
11377        }
11378
11379        cx.notify();
11380        self.scrollbar_marker_state.dirty = true;
11381        self.active_indent_guides_state.dirty = true;
11382    }
11383
11384    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11385        self.display_map.read(cx).fold_placeholder.clone()
11386    }
11387
11388    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11389        if hovered != self.gutter_hovered {
11390            self.gutter_hovered = hovered;
11391            cx.notify();
11392        }
11393    }
11394
11395    pub fn insert_blocks(
11396        &mut self,
11397        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11398        autoscroll: Option<Autoscroll>,
11399        cx: &mut ViewContext<Self>,
11400    ) -> Vec<CustomBlockId> {
11401        let blocks = self
11402            .display_map
11403            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11404        if let Some(autoscroll) = autoscroll {
11405            self.request_autoscroll(autoscroll, cx);
11406        }
11407        cx.notify();
11408        blocks
11409    }
11410
11411    pub fn resize_blocks(
11412        &mut self,
11413        heights: HashMap<CustomBlockId, u32>,
11414        autoscroll: Option<Autoscroll>,
11415        cx: &mut ViewContext<Self>,
11416    ) {
11417        self.display_map
11418            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11419        if let Some(autoscroll) = autoscroll {
11420            self.request_autoscroll(autoscroll, cx);
11421        }
11422        cx.notify();
11423    }
11424
11425    pub fn replace_blocks(
11426        &mut self,
11427        renderers: HashMap<CustomBlockId, RenderBlock>,
11428        autoscroll: Option<Autoscroll>,
11429        cx: &mut ViewContext<Self>,
11430    ) {
11431        self.display_map
11432            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11433        if let Some(autoscroll) = autoscroll {
11434            self.request_autoscroll(autoscroll, cx);
11435        }
11436        cx.notify();
11437    }
11438
11439    pub fn remove_blocks(
11440        &mut self,
11441        block_ids: HashSet<CustomBlockId>,
11442        autoscroll: Option<Autoscroll>,
11443        cx: &mut ViewContext<Self>,
11444    ) {
11445        self.display_map.update(cx, |display_map, cx| {
11446            display_map.remove_blocks(block_ids, cx)
11447        });
11448        if let Some(autoscroll) = autoscroll {
11449            self.request_autoscroll(autoscroll, cx);
11450        }
11451        cx.notify();
11452    }
11453
11454    pub fn row_for_block(
11455        &self,
11456        block_id: CustomBlockId,
11457        cx: &mut ViewContext<Self>,
11458    ) -> Option<DisplayRow> {
11459        self.display_map
11460            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11461    }
11462
11463    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11464        self.focused_block = Some(focused_block);
11465    }
11466
11467    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11468        self.focused_block.take()
11469    }
11470
11471    pub fn insert_creases(
11472        &mut self,
11473        creases: impl IntoIterator<Item = Crease<Anchor>>,
11474        cx: &mut ViewContext<Self>,
11475    ) -> Vec<CreaseId> {
11476        self.display_map
11477            .update(cx, |map, cx| map.insert_creases(creases, cx))
11478    }
11479
11480    pub fn remove_creases(
11481        &mut self,
11482        ids: impl IntoIterator<Item = CreaseId>,
11483        cx: &mut ViewContext<Self>,
11484    ) {
11485        self.display_map
11486            .update(cx, |map, cx| map.remove_creases(ids, cx));
11487    }
11488
11489    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11490        self.display_map
11491            .update(cx, |map, cx| map.snapshot(cx))
11492            .longest_row()
11493    }
11494
11495    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11496        self.display_map
11497            .update(cx, |map, cx| map.snapshot(cx))
11498            .max_point()
11499    }
11500
11501    pub fn text(&self, cx: &AppContext) -> String {
11502        self.buffer.read(cx).read(cx).text()
11503    }
11504
11505    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11506        let text = self.text(cx);
11507        let text = text.trim();
11508
11509        if text.is_empty() {
11510            return None;
11511        }
11512
11513        Some(text.to_string())
11514    }
11515
11516    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11517        self.transact(cx, |this, cx| {
11518            this.buffer
11519                .read(cx)
11520                .as_singleton()
11521                .expect("you can only call set_text on editors for singleton buffers")
11522                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11523        });
11524    }
11525
11526    pub fn display_text(&self, cx: &mut AppContext) -> String {
11527        self.display_map
11528            .update(cx, |map, cx| map.snapshot(cx))
11529            .text()
11530    }
11531
11532    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11533        let mut wrap_guides = smallvec::smallvec![];
11534
11535        if self.show_wrap_guides == Some(false) {
11536            return wrap_guides;
11537        }
11538
11539        let settings = self.buffer.read(cx).settings_at(0, cx);
11540        if settings.show_wrap_guides {
11541            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11542                wrap_guides.push((soft_wrap as usize, true));
11543            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11544                wrap_guides.push((soft_wrap as usize, true));
11545            }
11546            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11547        }
11548
11549        wrap_guides
11550    }
11551
11552    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11553        let settings = self.buffer.read(cx).settings_at(0, cx);
11554        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11555        match mode {
11556            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11557                SoftWrap::None
11558            }
11559            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11560            language_settings::SoftWrap::PreferredLineLength => {
11561                SoftWrap::Column(settings.preferred_line_length)
11562            }
11563            language_settings::SoftWrap::Bounded => {
11564                SoftWrap::Bounded(settings.preferred_line_length)
11565            }
11566        }
11567    }
11568
11569    pub fn set_soft_wrap_mode(
11570        &mut self,
11571        mode: language_settings::SoftWrap,
11572        cx: &mut ViewContext<Self>,
11573    ) {
11574        self.soft_wrap_mode_override = Some(mode);
11575        cx.notify();
11576    }
11577
11578    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11579        self.text_style_refinement = Some(style);
11580    }
11581
11582    /// called by the Element so we know what style we were most recently rendered with.
11583    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11584        let rem_size = cx.rem_size();
11585        self.display_map.update(cx, |map, cx| {
11586            map.set_font(
11587                style.text.font(),
11588                style.text.font_size.to_pixels(rem_size),
11589                cx,
11590            )
11591        });
11592        self.style = Some(style);
11593    }
11594
11595    pub fn style(&self) -> Option<&EditorStyle> {
11596        self.style.as_ref()
11597    }
11598
11599    // Called by the element. This method is not designed to be called outside of the editor
11600    // element's layout code because it does not notify when rewrapping is computed synchronously.
11601    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11602        self.display_map
11603            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11604    }
11605
11606    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11607        if self.soft_wrap_mode_override.is_some() {
11608            self.soft_wrap_mode_override.take();
11609        } else {
11610            let soft_wrap = match self.soft_wrap_mode(cx) {
11611                SoftWrap::GitDiff => return,
11612                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11613                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11614                    language_settings::SoftWrap::None
11615                }
11616            };
11617            self.soft_wrap_mode_override = Some(soft_wrap);
11618        }
11619        cx.notify();
11620    }
11621
11622    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11623        let Some(workspace) = self.workspace() else {
11624            return;
11625        };
11626        let fs = workspace.read(cx).app_state().fs.clone();
11627        let current_show = TabBarSettings::get_global(cx).show;
11628        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11629            setting.show = Some(!current_show);
11630        });
11631    }
11632
11633    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11634        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11635            self.buffer
11636                .read(cx)
11637                .settings_at(0, cx)
11638                .indent_guides
11639                .enabled
11640        });
11641        self.show_indent_guides = Some(!currently_enabled);
11642        cx.notify();
11643    }
11644
11645    fn should_show_indent_guides(&self) -> Option<bool> {
11646        self.show_indent_guides
11647    }
11648
11649    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11650        let mut editor_settings = EditorSettings::get_global(cx).clone();
11651        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11652        EditorSettings::override_global(editor_settings, cx);
11653    }
11654
11655    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11656        self.use_relative_line_numbers
11657            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11658    }
11659
11660    pub fn toggle_relative_line_numbers(
11661        &mut self,
11662        _: &ToggleRelativeLineNumbers,
11663        cx: &mut ViewContext<Self>,
11664    ) {
11665        let is_relative = self.should_use_relative_line_numbers(cx);
11666        self.set_relative_line_number(Some(!is_relative), cx)
11667    }
11668
11669    pub fn set_relative_line_number(
11670        &mut self,
11671        is_relative: Option<bool>,
11672        cx: &mut ViewContext<Self>,
11673    ) {
11674        self.use_relative_line_numbers = is_relative;
11675        cx.notify();
11676    }
11677
11678    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11679        self.show_gutter = show_gutter;
11680        cx.notify();
11681    }
11682
11683    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11684        self.show_line_numbers = Some(show_line_numbers);
11685        cx.notify();
11686    }
11687
11688    pub fn set_show_git_diff_gutter(
11689        &mut self,
11690        show_git_diff_gutter: bool,
11691        cx: &mut ViewContext<Self>,
11692    ) {
11693        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11694        cx.notify();
11695    }
11696
11697    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11698        self.show_code_actions = Some(show_code_actions);
11699        cx.notify();
11700    }
11701
11702    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11703        self.show_runnables = Some(show_runnables);
11704        cx.notify();
11705    }
11706
11707    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11708        if self.display_map.read(cx).masked != masked {
11709            self.display_map.update(cx, |map, _| map.masked = masked);
11710        }
11711        cx.notify()
11712    }
11713
11714    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11715        self.show_wrap_guides = Some(show_wrap_guides);
11716        cx.notify();
11717    }
11718
11719    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11720        self.show_indent_guides = Some(show_indent_guides);
11721        cx.notify();
11722    }
11723
11724    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11725        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11726            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11727                if let Some(dir) = file.abs_path(cx).parent() {
11728                    return Some(dir.to_owned());
11729                }
11730            }
11731
11732            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11733                return Some(project_path.path.to_path_buf());
11734            }
11735        }
11736
11737        None
11738    }
11739
11740    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11741        self.active_excerpt(cx)?
11742            .1
11743            .read(cx)
11744            .file()
11745            .and_then(|f| f.as_local())
11746    }
11747
11748    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11749        if let Some(target) = self.target_file(cx) {
11750            cx.reveal_path(&target.abs_path(cx));
11751        }
11752    }
11753
11754    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11755        if let Some(file) = self.target_file(cx) {
11756            if let Some(path) = file.abs_path(cx).to_str() {
11757                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11758            }
11759        }
11760    }
11761
11762    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11763        if let Some(file) = self.target_file(cx) {
11764            if let Some(path) = file.path().to_str() {
11765                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11766            }
11767        }
11768    }
11769
11770    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11771        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11772
11773        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11774            self.start_git_blame(true, cx);
11775        }
11776
11777        cx.notify();
11778    }
11779
11780    pub fn toggle_git_blame_inline(
11781        &mut self,
11782        _: &ToggleGitBlameInline,
11783        cx: &mut ViewContext<Self>,
11784    ) {
11785        self.toggle_git_blame_inline_internal(true, cx);
11786        cx.notify();
11787    }
11788
11789    pub fn git_blame_inline_enabled(&self) -> bool {
11790        self.git_blame_inline_enabled
11791    }
11792
11793    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11794        self.show_selection_menu = self
11795            .show_selection_menu
11796            .map(|show_selections_menu| !show_selections_menu)
11797            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11798
11799        cx.notify();
11800    }
11801
11802    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11803        self.show_selection_menu
11804            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11805    }
11806
11807    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11808        if let Some(project) = self.project.as_ref() {
11809            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11810                return;
11811            };
11812
11813            if buffer.read(cx).file().is_none() {
11814                return;
11815            }
11816
11817            let focused = self.focus_handle(cx).contains_focused(cx);
11818
11819            let project = project.clone();
11820            let blame =
11821                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11822            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11823            self.blame = Some(blame);
11824        }
11825    }
11826
11827    fn toggle_git_blame_inline_internal(
11828        &mut self,
11829        user_triggered: bool,
11830        cx: &mut ViewContext<Self>,
11831    ) {
11832        if self.git_blame_inline_enabled {
11833            self.git_blame_inline_enabled = false;
11834            self.show_git_blame_inline = false;
11835            self.show_git_blame_inline_delay_task.take();
11836        } else {
11837            self.git_blame_inline_enabled = true;
11838            self.start_git_blame_inline(user_triggered, cx);
11839        }
11840
11841        cx.notify();
11842    }
11843
11844    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11845        self.start_git_blame(user_triggered, cx);
11846
11847        if ProjectSettings::get_global(cx)
11848            .git
11849            .inline_blame_delay()
11850            .is_some()
11851        {
11852            self.start_inline_blame_timer(cx);
11853        } else {
11854            self.show_git_blame_inline = true
11855        }
11856    }
11857
11858    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11859        self.blame.as_ref()
11860    }
11861
11862    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11863        self.show_git_blame_gutter && self.has_blame_entries(cx)
11864    }
11865
11866    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11867        self.show_git_blame_inline
11868            && self.focus_handle.is_focused(cx)
11869            && !self.newest_selection_head_on_empty_line(cx)
11870            && self.has_blame_entries(cx)
11871    }
11872
11873    pub fn render_active_line_trailer(
11874        &mut self,
11875        style: &EditorStyle,
11876        cx: &mut WindowContext,
11877    ) -> Option<AnyElement> {
11878        let selection = self.selections.newest::<Point>(cx);
11879        if !selection.is_empty() {
11880            return None;
11881        };
11882
11883        let snapshot = self.buffer.read(cx).snapshot(cx);
11884        let buffer_row = MultiBufferRow(selection.head().row);
11885
11886        if snapshot.line_len(buffer_row) != 0 || self.has_active_inline_completion(cx) {
11887            return None;
11888        }
11889
11890        let focus_handle = self.focus_handle.clone();
11891        self.active_line_trailer_provider
11892            .as_mut()?
11893            .render_active_line_trailer(style, &focus_handle, cx)
11894    }
11895
11896    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11897        self.blame()
11898            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11899    }
11900
11901    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11902        let cursor_anchor = self.selections.newest_anchor().head();
11903
11904        let snapshot = self.buffer.read(cx).snapshot(cx);
11905        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11906
11907        snapshot.line_len(buffer_row) == 0
11908    }
11909
11910    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11911        let buffer_and_selection = maybe!({
11912            let selection = self.selections.newest::<Point>(cx);
11913            let selection_range = selection.range();
11914
11915            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11916                (buffer, selection_range.start.row..selection_range.end.row)
11917            } else {
11918                let buffer_ranges = self
11919                    .buffer()
11920                    .read(cx)
11921                    .range_to_buffer_ranges(selection_range, cx);
11922
11923                let (buffer, range, _) = if selection.reversed {
11924                    buffer_ranges.first()
11925                } else {
11926                    buffer_ranges.last()
11927                }?;
11928
11929                let snapshot = buffer.read(cx).snapshot();
11930                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11931                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11932                (buffer.clone(), selection)
11933            };
11934
11935            Some((buffer, selection))
11936        });
11937
11938        let Some((buffer, selection)) = buffer_and_selection else {
11939            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11940        };
11941
11942        let Some(project) = self.project.as_ref() else {
11943            return Task::ready(Err(anyhow!("editor does not have project")));
11944        };
11945
11946        project.update(cx, |project, cx| {
11947            project.get_permalink_to_line(&buffer, selection, cx)
11948        })
11949    }
11950
11951    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11952        let permalink_task = self.get_permalink_to_line(cx);
11953        let workspace = self.workspace();
11954
11955        cx.spawn(|_, mut cx| async move {
11956            match permalink_task.await {
11957                Ok(permalink) => {
11958                    cx.update(|cx| {
11959                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11960                    })
11961                    .ok();
11962                }
11963                Err(err) => {
11964                    let message = format!("Failed to copy permalink: {err}");
11965
11966                    Err::<(), anyhow::Error>(err).log_err();
11967
11968                    if let Some(workspace) = workspace {
11969                        workspace
11970                            .update(&mut cx, |workspace, cx| {
11971                                struct CopyPermalinkToLine;
11972
11973                                workspace.show_toast(
11974                                    Toast::new(
11975                                        NotificationId::unique::<CopyPermalinkToLine>(),
11976                                        message,
11977                                    ),
11978                                    cx,
11979                                )
11980                            })
11981                            .ok();
11982                    }
11983                }
11984            }
11985        })
11986        .detach();
11987    }
11988
11989    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11990        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11991        if let Some(file) = self.target_file(cx) {
11992            if let Some(path) = file.path().to_str() {
11993                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11994            }
11995        }
11996    }
11997
11998    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11999        let permalink_task = self.get_permalink_to_line(cx);
12000        let workspace = self.workspace();
12001
12002        cx.spawn(|_, mut cx| async move {
12003            match permalink_task.await {
12004                Ok(permalink) => {
12005                    cx.update(|cx| {
12006                        cx.open_url(permalink.as_ref());
12007                    })
12008                    .ok();
12009                }
12010                Err(err) => {
12011                    let message = format!("Failed to open permalink: {err}");
12012
12013                    Err::<(), anyhow::Error>(err).log_err();
12014
12015                    if let Some(workspace) = workspace {
12016                        workspace
12017                            .update(&mut cx, |workspace, cx| {
12018                                struct OpenPermalinkToLine;
12019
12020                                workspace.show_toast(
12021                                    Toast::new(
12022                                        NotificationId::unique::<OpenPermalinkToLine>(),
12023                                        message,
12024                                    ),
12025                                    cx,
12026                                )
12027                            })
12028                            .ok();
12029                    }
12030                }
12031            }
12032        })
12033        .detach();
12034    }
12035
12036    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12037    /// last highlight added will be used.
12038    ///
12039    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12040    pub fn highlight_rows<T: 'static>(
12041        &mut self,
12042        range: Range<Anchor>,
12043        color: Hsla,
12044        should_autoscroll: bool,
12045        cx: &mut ViewContext<Self>,
12046    ) {
12047        let snapshot = self.buffer().read(cx).snapshot(cx);
12048        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12049        let ix = row_highlights.binary_search_by(|highlight| {
12050            Ordering::Equal
12051                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12052                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12053        });
12054
12055        if let Err(mut ix) = ix {
12056            let index = post_inc(&mut self.highlight_order);
12057
12058            // If this range intersects with the preceding highlight, then merge it with
12059            // the preceding highlight. Otherwise insert a new highlight.
12060            let mut merged = false;
12061            if ix > 0 {
12062                let prev_highlight = &mut row_highlights[ix - 1];
12063                if prev_highlight
12064                    .range
12065                    .end
12066                    .cmp(&range.start, &snapshot)
12067                    .is_ge()
12068                {
12069                    ix -= 1;
12070                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12071                        prev_highlight.range.end = range.end;
12072                    }
12073                    merged = true;
12074                    prev_highlight.index = index;
12075                    prev_highlight.color = color;
12076                    prev_highlight.should_autoscroll = should_autoscroll;
12077                }
12078            }
12079
12080            if !merged {
12081                row_highlights.insert(
12082                    ix,
12083                    RowHighlight {
12084                        range: range.clone(),
12085                        index,
12086                        color,
12087                        should_autoscroll,
12088                    },
12089                );
12090            }
12091
12092            // If any of the following highlights intersect with this one, merge them.
12093            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12094                let highlight = &row_highlights[ix];
12095                if next_highlight
12096                    .range
12097                    .start
12098                    .cmp(&highlight.range.end, &snapshot)
12099                    .is_le()
12100                {
12101                    if next_highlight
12102                        .range
12103                        .end
12104                        .cmp(&highlight.range.end, &snapshot)
12105                        .is_gt()
12106                    {
12107                        row_highlights[ix].range.end = next_highlight.range.end;
12108                    }
12109                    row_highlights.remove(ix + 1);
12110                } else {
12111                    break;
12112                }
12113            }
12114        }
12115    }
12116
12117    /// Remove any highlighted row ranges of the given type that intersect the
12118    /// given ranges.
12119    pub fn remove_highlighted_rows<T: 'static>(
12120        &mut self,
12121        ranges_to_remove: Vec<Range<Anchor>>,
12122        cx: &mut ViewContext<Self>,
12123    ) {
12124        let snapshot = self.buffer().read(cx).snapshot(cx);
12125        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12126        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12127        row_highlights.retain(|highlight| {
12128            while let Some(range_to_remove) = ranges_to_remove.peek() {
12129                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12130                    Ordering::Less | Ordering::Equal => {
12131                        ranges_to_remove.next();
12132                    }
12133                    Ordering::Greater => {
12134                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12135                            Ordering::Less | Ordering::Equal => {
12136                                return false;
12137                            }
12138                            Ordering::Greater => break,
12139                        }
12140                    }
12141                }
12142            }
12143
12144            true
12145        })
12146    }
12147
12148    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12149    pub fn clear_row_highlights<T: 'static>(&mut self) {
12150        self.highlighted_rows.remove(&TypeId::of::<T>());
12151    }
12152
12153    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12154    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12155        self.highlighted_rows
12156            .get(&TypeId::of::<T>())
12157            .map_or(&[] as &[_], |vec| vec.as_slice())
12158            .iter()
12159            .map(|highlight| (highlight.range.clone(), highlight.color))
12160    }
12161
12162    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12163    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12164    /// Allows to ignore certain kinds of highlights.
12165    pub fn highlighted_display_rows(
12166        &mut self,
12167        cx: &mut WindowContext,
12168    ) -> BTreeMap<DisplayRow, Hsla> {
12169        let snapshot = self.snapshot(cx);
12170        let mut used_highlight_orders = HashMap::default();
12171        self.highlighted_rows
12172            .iter()
12173            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12174            .fold(
12175                BTreeMap::<DisplayRow, Hsla>::new(),
12176                |mut unique_rows, highlight| {
12177                    let start = highlight.range.start.to_display_point(&snapshot);
12178                    let end = highlight.range.end.to_display_point(&snapshot);
12179                    let start_row = start.row().0;
12180                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12181                        && end.column() == 0
12182                    {
12183                        end.row().0.saturating_sub(1)
12184                    } else {
12185                        end.row().0
12186                    };
12187                    for row in start_row..=end_row {
12188                        let used_index =
12189                            used_highlight_orders.entry(row).or_insert(highlight.index);
12190                        if highlight.index >= *used_index {
12191                            *used_index = highlight.index;
12192                            unique_rows.insert(DisplayRow(row), highlight.color);
12193                        }
12194                    }
12195                    unique_rows
12196                },
12197            )
12198    }
12199
12200    pub fn highlighted_display_row_for_autoscroll(
12201        &self,
12202        snapshot: &DisplaySnapshot,
12203    ) -> Option<DisplayRow> {
12204        self.highlighted_rows
12205            .values()
12206            .flat_map(|highlighted_rows| highlighted_rows.iter())
12207            .filter_map(|highlight| {
12208                if highlight.should_autoscroll {
12209                    Some(highlight.range.start.to_display_point(snapshot).row())
12210                } else {
12211                    None
12212                }
12213            })
12214            .min()
12215    }
12216
12217    pub fn set_search_within_ranges(
12218        &mut self,
12219        ranges: &[Range<Anchor>],
12220        cx: &mut ViewContext<Self>,
12221    ) {
12222        self.highlight_background::<SearchWithinRange>(
12223            ranges,
12224            |colors| colors.editor_document_highlight_read_background,
12225            cx,
12226        )
12227    }
12228
12229    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12230        self.breadcrumb_header = Some(new_header);
12231    }
12232
12233    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12234        self.clear_background_highlights::<SearchWithinRange>(cx);
12235    }
12236
12237    pub fn highlight_background<T: 'static>(
12238        &mut self,
12239        ranges: &[Range<Anchor>],
12240        color_fetcher: fn(&ThemeColors) -> Hsla,
12241        cx: &mut ViewContext<Self>,
12242    ) {
12243        self.background_highlights
12244            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12245        self.scrollbar_marker_state.dirty = true;
12246        cx.notify();
12247    }
12248
12249    pub fn clear_background_highlights<T: 'static>(
12250        &mut self,
12251        cx: &mut ViewContext<Self>,
12252    ) -> Option<BackgroundHighlight> {
12253        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12254        if !text_highlights.1.is_empty() {
12255            self.scrollbar_marker_state.dirty = true;
12256            cx.notify();
12257        }
12258        Some(text_highlights)
12259    }
12260
12261    pub fn highlight_gutter<T: 'static>(
12262        &mut self,
12263        ranges: &[Range<Anchor>],
12264        color_fetcher: fn(&AppContext) -> Hsla,
12265        cx: &mut ViewContext<Self>,
12266    ) {
12267        self.gutter_highlights
12268            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12269        cx.notify();
12270    }
12271
12272    pub fn clear_gutter_highlights<T: 'static>(
12273        &mut self,
12274        cx: &mut ViewContext<Self>,
12275    ) -> Option<GutterHighlight> {
12276        cx.notify();
12277        self.gutter_highlights.remove(&TypeId::of::<T>())
12278    }
12279
12280    #[cfg(feature = "test-support")]
12281    pub fn all_text_background_highlights(
12282        &mut self,
12283        cx: &mut ViewContext<Self>,
12284    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12285        let snapshot = self.snapshot(cx);
12286        let buffer = &snapshot.buffer_snapshot;
12287        let start = buffer.anchor_before(0);
12288        let end = buffer.anchor_after(buffer.len());
12289        let theme = cx.theme().colors();
12290        self.background_highlights_in_range(start..end, &snapshot, theme)
12291    }
12292
12293    #[cfg(feature = "test-support")]
12294    pub fn search_background_highlights(
12295        &mut self,
12296        cx: &mut ViewContext<Self>,
12297    ) -> Vec<Range<Point>> {
12298        let snapshot = self.buffer().read(cx).snapshot(cx);
12299
12300        let highlights = self
12301            .background_highlights
12302            .get(&TypeId::of::<items::BufferSearchHighlights>());
12303
12304        if let Some((_color, ranges)) = highlights {
12305            ranges
12306                .iter()
12307                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12308                .collect_vec()
12309        } else {
12310            vec![]
12311        }
12312    }
12313
12314    fn document_highlights_for_position<'a>(
12315        &'a self,
12316        position: Anchor,
12317        buffer: &'a MultiBufferSnapshot,
12318    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12319        let read_highlights = self
12320            .background_highlights
12321            .get(&TypeId::of::<DocumentHighlightRead>())
12322            .map(|h| &h.1);
12323        let write_highlights = self
12324            .background_highlights
12325            .get(&TypeId::of::<DocumentHighlightWrite>())
12326            .map(|h| &h.1);
12327        let left_position = position.bias_left(buffer);
12328        let right_position = position.bias_right(buffer);
12329        read_highlights
12330            .into_iter()
12331            .chain(write_highlights)
12332            .flat_map(move |ranges| {
12333                let start_ix = match ranges.binary_search_by(|probe| {
12334                    let cmp = probe.end.cmp(&left_position, buffer);
12335                    if cmp.is_ge() {
12336                        Ordering::Greater
12337                    } else {
12338                        Ordering::Less
12339                    }
12340                }) {
12341                    Ok(i) | Err(i) => i,
12342                };
12343
12344                ranges[start_ix..]
12345                    .iter()
12346                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12347            })
12348    }
12349
12350    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12351        self.background_highlights
12352            .get(&TypeId::of::<T>())
12353            .map_or(false, |(_, highlights)| !highlights.is_empty())
12354    }
12355
12356    pub fn background_highlights_in_range(
12357        &self,
12358        search_range: Range<Anchor>,
12359        display_snapshot: &DisplaySnapshot,
12360        theme: &ThemeColors,
12361    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12362        let mut results = Vec::new();
12363        for (color_fetcher, ranges) in self.background_highlights.values() {
12364            let color = color_fetcher(theme);
12365            let start_ix = match ranges.binary_search_by(|probe| {
12366                let cmp = probe
12367                    .end
12368                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12369                if cmp.is_gt() {
12370                    Ordering::Greater
12371                } else {
12372                    Ordering::Less
12373                }
12374            }) {
12375                Ok(i) | Err(i) => i,
12376            };
12377            for range in &ranges[start_ix..] {
12378                if range
12379                    .start
12380                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12381                    .is_ge()
12382                {
12383                    break;
12384                }
12385
12386                let start = range.start.to_display_point(display_snapshot);
12387                let end = range.end.to_display_point(display_snapshot);
12388                results.push((start..end, color))
12389            }
12390        }
12391        results
12392    }
12393
12394    pub fn background_highlight_row_ranges<T: 'static>(
12395        &self,
12396        search_range: Range<Anchor>,
12397        display_snapshot: &DisplaySnapshot,
12398        count: usize,
12399    ) -> Vec<RangeInclusive<DisplayPoint>> {
12400        let mut results = Vec::new();
12401        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12402            return vec![];
12403        };
12404
12405        let start_ix = match ranges.binary_search_by(|probe| {
12406            let cmp = probe
12407                .end
12408                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12409            if cmp.is_gt() {
12410                Ordering::Greater
12411            } else {
12412                Ordering::Less
12413            }
12414        }) {
12415            Ok(i) | Err(i) => i,
12416        };
12417        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12418            if let (Some(start_display), Some(end_display)) = (start, end) {
12419                results.push(
12420                    start_display.to_display_point(display_snapshot)
12421                        ..=end_display.to_display_point(display_snapshot),
12422                );
12423            }
12424        };
12425        let mut start_row: Option<Point> = None;
12426        let mut end_row: Option<Point> = None;
12427        if ranges.len() > count {
12428            return Vec::new();
12429        }
12430        for range in &ranges[start_ix..] {
12431            if range
12432                .start
12433                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12434                .is_ge()
12435            {
12436                break;
12437            }
12438            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12439            if let Some(current_row) = &end_row {
12440                if end.row == current_row.row {
12441                    continue;
12442                }
12443            }
12444            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12445            if start_row.is_none() {
12446                assert_eq!(end_row, None);
12447                start_row = Some(start);
12448                end_row = Some(end);
12449                continue;
12450            }
12451            if let Some(current_end) = end_row.as_mut() {
12452                if start.row > current_end.row + 1 {
12453                    push_region(start_row, end_row);
12454                    start_row = Some(start);
12455                    end_row = Some(end);
12456                } else {
12457                    // Merge two hunks.
12458                    *current_end = end;
12459                }
12460            } else {
12461                unreachable!();
12462            }
12463        }
12464        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12465        push_region(start_row, end_row);
12466        results
12467    }
12468
12469    pub fn gutter_highlights_in_range(
12470        &self,
12471        search_range: Range<Anchor>,
12472        display_snapshot: &DisplaySnapshot,
12473        cx: &AppContext,
12474    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12475        let mut results = Vec::new();
12476        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12477            let color = color_fetcher(cx);
12478            let start_ix = match ranges.binary_search_by(|probe| {
12479                let cmp = probe
12480                    .end
12481                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12482                if cmp.is_gt() {
12483                    Ordering::Greater
12484                } else {
12485                    Ordering::Less
12486                }
12487            }) {
12488                Ok(i) | Err(i) => i,
12489            };
12490            for range in &ranges[start_ix..] {
12491                if range
12492                    .start
12493                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12494                    .is_ge()
12495                {
12496                    break;
12497                }
12498
12499                let start = range.start.to_display_point(display_snapshot);
12500                let end = range.end.to_display_point(display_snapshot);
12501                results.push((start..end, color))
12502            }
12503        }
12504        results
12505    }
12506
12507    /// Get the text ranges corresponding to the redaction query
12508    pub fn redacted_ranges(
12509        &self,
12510        search_range: Range<Anchor>,
12511        display_snapshot: &DisplaySnapshot,
12512        cx: &WindowContext,
12513    ) -> Vec<Range<DisplayPoint>> {
12514        display_snapshot
12515            .buffer_snapshot
12516            .redacted_ranges(search_range, |file| {
12517                if let Some(file) = file {
12518                    file.is_private()
12519                        && EditorSettings::get(
12520                            Some(SettingsLocation {
12521                                worktree_id: file.worktree_id(cx),
12522                                path: file.path().as_ref(),
12523                            }),
12524                            cx,
12525                        )
12526                        .redact_private_values
12527                } else {
12528                    false
12529                }
12530            })
12531            .map(|range| {
12532                range.start.to_display_point(display_snapshot)
12533                    ..range.end.to_display_point(display_snapshot)
12534            })
12535            .collect()
12536    }
12537
12538    pub fn highlight_text<T: 'static>(
12539        &mut self,
12540        ranges: Vec<Range<Anchor>>,
12541        style: HighlightStyle,
12542        cx: &mut ViewContext<Self>,
12543    ) {
12544        self.display_map.update(cx, |map, _| {
12545            map.highlight_text(TypeId::of::<T>(), ranges, style)
12546        });
12547        cx.notify();
12548    }
12549
12550    pub(crate) fn highlight_inlays<T: 'static>(
12551        &mut self,
12552        highlights: Vec<InlayHighlight>,
12553        style: HighlightStyle,
12554        cx: &mut ViewContext<Self>,
12555    ) {
12556        self.display_map.update(cx, |map, _| {
12557            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12558        });
12559        cx.notify();
12560    }
12561
12562    pub fn text_highlights<'a, T: 'static>(
12563        &'a self,
12564        cx: &'a AppContext,
12565    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12566        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12567    }
12568
12569    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12570        let cleared = self
12571            .display_map
12572            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12573        if cleared {
12574            cx.notify();
12575        }
12576    }
12577
12578    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12579        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12580            && self.focus_handle.is_focused(cx)
12581    }
12582
12583    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12584        self.show_cursor_when_unfocused = is_enabled;
12585        cx.notify();
12586    }
12587
12588    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12589        cx.notify();
12590    }
12591
12592    fn on_buffer_event(
12593        &mut self,
12594        multibuffer: Model<MultiBuffer>,
12595        event: &multi_buffer::Event,
12596        cx: &mut ViewContext<Self>,
12597    ) {
12598        match event {
12599            multi_buffer::Event::Edited {
12600                singleton_buffer_edited,
12601            } => {
12602                self.scrollbar_marker_state.dirty = true;
12603                self.active_indent_guides_state.dirty = true;
12604                self.refresh_active_diagnostics(cx);
12605                self.refresh_code_actions(cx);
12606                if self.has_active_inline_completion(cx) {
12607                    self.update_visible_inline_completion(cx);
12608                }
12609                cx.emit(EditorEvent::BufferEdited);
12610                cx.emit(SearchEvent::MatchesInvalidated);
12611                if *singleton_buffer_edited {
12612                    if let Some(project) = &self.project {
12613                        let project = project.read(cx);
12614                        #[allow(clippy::mutable_key_type)]
12615                        let languages_affected = multibuffer
12616                            .read(cx)
12617                            .all_buffers()
12618                            .into_iter()
12619                            .filter_map(|buffer| {
12620                                let buffer = buffer.read(cx);
12621                                let language = buffer.language()?;
12622                                if project.is_local()
12623                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12624                                {
12625                                    None
12626                                } else {
12627                                    Some(language)
12628                                }
12629                            })
12630                            .cloned()
12631                            .collect::<HashSet<_>>();
12632                        if !languages_affected.is_empty() {
12633                            self.refresh_inlay_hints(
12634                                InlayHintRefreshReason::BufferEdited(languages_affected),
12635                                cx,
12636                            );
12637                        }
12638                    }
12639                }
12640
12641                let Some(project) = &self.project else { return };
12642                let (telemetry, is_via_ssh) = {
12643                    let project = project.read(cx);
12644                    let telemetry = project.client().telemetry().clone();
12645                    let is_via_ssh = project.is_via_ssh();
12646                    (telemetry, is_via_ssh)
12647                };
12648                refresh_linked_ranges(self, cx);
12649                telemetry.log_edit_event("editor", is_via_ssh);
12650            }
12651            multi_buffer::Event::ExcerptsAdded {
12652                buffer,
12653                predecessor,
12654                excerpts,
12655            } => {
12656                self.tasks_update_task = Some(self.refresh_runnables(cx));
12657                cx.emit(EditorEvent::ExcerptsAdded {
12658                    buffer: buffer.clone(),
12659                    predecessor: *predecessor,
12660                    excerpts: excerpts.clone(),
12661                });
12662                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12663            }
12664            multi_buffer::Event::ExcerptsRemoved { ids } => {
12665                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12666                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12667            }
12668            multi_buffer::Event::ExcerptsEdited { ids } => {
12669                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12670            }
12671            multi_buffer::Event::ExcerptsExpanded { ids } => {
12672                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12673            }
12674            multi_buffer::Event::Reparsed(buffer_id) => {
12675                self.tasks_update_task = Some(self.refresh_runnables(cx));
12676
12677                cx.emit(EditorEvent::Reparsed(*buffer_id));
12678            }
12679            multi_buffer::Event::LanguageChanged(buffer_id) => {
12680                linked_editing_ranges::refresh_linked_ranges(self, cx);
12681                cx.emit(EditorEvent::Reparsed(*buffer_id));
12682                cx.notify();
12683            }
12684            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12685            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12686            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12687                cx.emit(EditorEvent::TitleChanged)
12688            }
12689            multi_buffer::Event::DiffBaseChanged => {
12690                self.scrollbar_marker_state.dirty = true;
12691                cx.emit(EditorEvent::DiffBaseChanged);
12692                cx.notify();
12693            }
12694            multi_buffer::Event::DiffUpdated { buffer } => {
12695                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12696                cx.notify();
12697            }
12698            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12699            multi_buffer::Event::DiagnosticsUpdated => {
12700                self.refresh_active_diagnostics(cx);
12701                self.scrollbar_marker_state.dirty = true;
12702                cx.notify();
12703            }
12704            _ => {}
12705        };
12706    }
12707
12708    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12709        cx.notify();
12710    }
12711
12712    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12713        self.tasks_update_task = Some(self.refresh_runnables(cx));
12714        self.refresh_inline_completion(true, false, cx);
12715        self.refresh_inlay_hints(
12716            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12717                self.selections.newest_anchor().head(),
12718                &self.buffer.read(cx).snapshot(cx),
12719                cx,
12720            )),
12721            cx,
12722        );
12723
12724        let old_cursor_shape = self.cursor_shape;
12725
12726        {
12727            let editor_settings = EditorSettings::get_global(cx);
12728            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12729            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12730            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12731        }
12732
12733        if old_cursor_shape != self.cursor_shape {
12734            cx.emit(EditorEvent::CursorShapeChanged);
12735        }
12736
12737        let project_settings = ProjectSettings::get_global(cx);
12738        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12739
12740        if self.mode == EditorMode::Full {
12741            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12742            if self.git_blame_inline_enabled != inline_blame_enabled {
12743                self.toggle_git_blame_inline_internal(false, cx);
12744            }
12745        }
12746
12747        cx.notify();
12748    }
12749
12750    pub fn set_searchable(&mut self, searchable: bool) {
12751        self.searchable = searchable;
12752    }
12753
12754    pub fn searchable(&self) -> bool {
12755        self.searchable
12756    }
12757
12758    fn open_proposed_changes_editor(
12759        &mut self,
12760        _: &OpenProposedChangesEditor,
12761        cx: &mut ViewContext<Self>,
12762    ) {
12763        let Some(workspace) = self.workspace() else {
12764            cx.propagate();
12765            return;
12766        };
12767
12768        let selections = self.selections.all::<usize>(cx);
12769        let buffer = self.buffer.read(cx);
12770        let mut new_selections_by_buffer = HashMap::default();
12771        for selection in selections {
12772            for (buffer, range, _) in
12773                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12774            {
12775                let mut range = range.to_point(buffer.read(cx));
12776                range.start.column = 0;
12777                range.end.column = buffer.read(cx).line_len(range.end.row);
12778                new_selections_by_buffer
12779                    .entry(buffer)
12780                    .or_insert(Vec::new())
12781                    .push(range)
12782            }
12783        }
12784
12785        let proposed_changes_buffers = new_selections_by_buffer
12786            .into_iter()
12787            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12788            .collect::<Vec<_>>();
12789        let proposed_changes_editor = cx.new_view(|cx| {
12790            ProposedChangesEditor::new(
12791                "Proposed changes",
12792                proposed_changes_buffers,
12793                self.project.clone(),
12794                cx,
12795            )
12796        });
12797
12798        cx.window_context().defer(move |cx| {
12799            workspace.update(cx, |workspace, cx| {
12800                workspace.active_pane().update(cx, |pane, cx| {
12801                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12802                });
12803            });
12804        });
12805    }
12806
12807    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12808        self.open_excerpts_common(None, true, cx)
12809    }
12810
12811    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12812        self.open_excerpts_common(None, false, cx)
12813    }
12814
12815    fn open_excerpts_common(
12816        &mut self,
12817        jump_data: Option<JumpData>,
12818        split: bool,
12819        cx: &mut ViewContext<Self>,
12820    ) {
12821        let Some(workspace) = self.workspace() else {
12822            cx.propagate();
12823            return;
12824        };
12825
12826        if self.buffer.read(cx).is_singleton() {
12827            cx.propagate();
12828            return;
12829        }
12830
12831        let mut new_selections_by_buffer = HashMap::default();
12832        match &jump_data {
12833            Some(jump_data) => {
12834                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12835                if let Some(buffer) = multi_buffer_snapshot
12836                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12837                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12838                {
12839                    let buffer_snapshot = buffer.read(cx).snapshot();
12840                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12841                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12842                    } else {
12843                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12844                    };
12845                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12846                    new_selections_by_buffer.insert(
12847                        buffer,
12848                        (
12849                            vec![jump_to_offset..jump_to_offset],
12850                            Some(jump_data.line_offset_from_top),
12851                        ),
12852                    );
12853                }
12854            }
12855            None => {
12856                let selections = self.selections.all::<usize>(cx);
12857                let buffer = self.buffer.read(cx);
12858                for selection in selections {
12859                    for (mut buffer_handle, mut range, _) in
12860                        buffer.range_to_buffer_ranges(selection.range(), cx)
12861                    {
12862                        // When editing branch buffers, jump to the corresponding location
12863                        // in their base buffer.
12864                        let buffer = buffer_handle.read(cx);
12865                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12866                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12867                            buffer_handle = base_buffer;
12868                        }
12869
12870                        if selection.reversed {
12871                            mem::swap(&mut range.start, &mut range.end);
12872                        }
12873                        new_selections_by_buffer
12874                            .entry(buffer_handle)
12875                            .or_insert((Vec::new(), None))
12876                            .0
12877                            .push(range)
12878                    }
12879                }
12880            }
12881        }
12882
12883        if new_selections_by_buffer.is_empty() {
12884            return;
12885        }
12886
12887        // We defer the pane interaction because we ourselves are a workspace item
12888        // and activating a new item causes the pane to call a method on us reentrantly,
12889        // which panics if we're on the stack.
12890        cx.window_context().defer(move |cx| {
12891            workspace.update(cx, |workspace, cx| {
12892                let pane = if split {
12893                    workspace.adjacent_pane(cx)
12894                } else {
12895                    workspace.active_pane().clone()
12896                };
12897
12898                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12899                    let editor =
12900                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12901                    editor.update(cx, |editor, cx| {
12902                        let autoscroll = match scroll_offset {
12903                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12904                            None => Autoscroll::newest(),
12905                        };
12906                        let nav_history = editor.nav_history.take();
12907                        editor.change_selections(Some(autoscroll), cx, |s| {
12908                            s.select_ranges(ranges);
12909                        });
12910                        editor.nav_history = nav_history;
12911                    });
12912                }
12913            })
12914        });
12915    }
12916
12917    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12918        let snapshot = self.buffer.read(cx).read(cx);
12919        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12920        Some(
12921            ranges
12922                .iter()
12923                .map(move |range| {
12924                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12925                })
12926                .collect(),
12927        )
12928    }
12929
12930    fn selection_replacement_ranges(
12931        &self,
12932        range: Range<OffsetUtf16>,
12933        cx: &mut AppContext,
12934    ) -> Vec<Range<OffsetUtf16>> {
12935        let selections = self.selections.all::<OffsetUtf16>(cx);
12936        let newest_selection = selections
12937            .iter()
12938            .max_by_key(|selection| selection.id)
12939            .unwrap();
12940        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12941        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12942        let snapshot = self.buffer.read(cx).read(cx);
12943        selections
12944            .into_iter()
12945            .map(|mut selection| {
12946                selection.start.0 =
12947                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12948                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12949                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12950                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12951            })
12952            .collect()
12953    }
12954
12955    fn report_editor_event(
12956        &self,
12957        operation: &'static str,
12958        file_extension: Option<String>,
12959        cx: &AppContext,
12960    ) {
12961        if cfg!(any(test, feature = "test-support")) {
12962            return;
12963        }
12964
12965        let Some(project) = &self.project else { return };
12966
12967        // If None, we are in a file without an extension
12968        let file = self
12969            .buffer
12970            .read(cx)
12971            .as_singleton()
12972            .and_then(|b| b.read(cx).file());
12973        let file_extension = file_extension.or(file
12974            .as_ref()
12975            .and_then(|file| Path::new(file.file_name(cx)).extension())
12976            .and_then(|e| e.to_str())
12977            .map(|a| a.to_string()));
12978
12979        let vim_mode = cx
12980            .global::<SettingsStore>()
12981            .raw_user_settings()
12982            .get("vim_mode")
12983            == Some(&serde_json::Value::Bool(true));
12984
12985        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12986            == language::language_settings::InlineCompletionProvider::Copilot;
12987        let copilot_enabled_for_language = self
12988            .buffer
12989            .read(cx)
12990            .settings_at(0, cx)
12991            .show_inline_completions;
12992
12993        let project = project.read(cx);
12994        let telemetry = project.client().telemetry().clone();
12995        telemetry.report_editor_event(
12996            file_extension,
12997            vim_mode,
12998            operation,
12999            copilot_enabled,
13000            copilot_enabled_for_language,
13001            project.is_via_ssh(),
13002        )
13003    }
13004
13005    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13006    /// with each line being an array of {text, highlight} objects.
13007    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13008        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13009            return;
13010        };
13011
13012        #[derive(Serialize)]
13013        struct Chunk<'a> {
13014            text: String,
13015            highlight: Option<&'a str>,
13016        }
13017
13018        let snapshot = buffer.read(cx).snapshot();
13019        let range = self
13020            .selected_text_range(false, cx)
13021            .and_then(|selection| {
13022                if selection.range.is_empty() {
13023                    None
13024                } else {
13025                    Some(selection.range)
13026                }
13027            })
13028            .unwrap_or_else(|| 0..snapshot.len());
13029
13030        let chunks = snapshot.chunks(range, true);
13031        let mut lines = Vec::new();
13032        let mut line: VecDeque<Chunk> = VecDeque::new();
13033
13034        let Some(style) = self.style.as_ref() else {
13035            return;
13036        };
13037
13038        for chunk in chunks {
13039            let highlight = chunk
13040                .syntax_highlight_id
13041                .and_then(|id| id.name(&style.syntax));
13042            let mut chunk_lines = chunk.text.split('\n').peekable();
13043            while let Some(text) = chunk_lines.next() {
13044                let mut merged_with_last_token = false;
13045                if let Some(last_token) = line.back_mut() {
13046                    if last_token.highlight == highlight {
13047                        last_token.text.push_str(text);
13048                        merged_with_last_token = true;
13049                    }
13050                }
13051
13052                if !merged_with_last_token {
13053                    line.push_back(Chunk {
13054                        text: text.into(),
13055                        highlight,
13056                    });
13057                }
13058
13059                if chunk_lines.peek().is_some() {
13060                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13061                        line.pop_front();
13062                    }
13063                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13064                        line.pop_back();
13065                    }
13066
13067                    lines.push(mem::take(&mut line));
13068                }
13069            }
13070        }
13071
13072        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13073            return;
13074        };
13075        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13076    }
13077
13078    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13079        &self.inlay_hint_cache
13080    }
13081
13082    pub fn replay_insert_event(
13083        &mut self,
13084        text: &str,
13085        relative_utf16_range: Option<Range<isize>>,
13086        cx: &mut ViewContext<Self>,
13087    ) {
13088        if !self.input_enabled {
13089            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13090            return;
13091        }
13092        if let Some(relative_utf16_range) = relative_utf16_range {
13093            let selections = self.selections.all::<OffsetUtf16>(cx);
13094            self.change_selections(None, cx, |s| {
13095                let new_ranges = selections.into_iter().map(|range| {
13096                    let start = OffsetUtf16(
13097                        range
13098                            .head()
13099                            .0
13100                            .saturating_add_signed(relative_utf16_range.start),
13101                    );
13102                    let end = OffsetUtf16(
13103                        range
13104                            .head()
13105                            .0
13106                            .saturating_add_signed(relative_utf16_range.end),
13107                    );
13108                    start..end
13109                });
13110                s.select_ranges(new_ranges);
13111            });
13112        }
13113
13114        self.handle_input(text, cx);
13115    }
13116
13117    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13118        let Some(provider) = self.semantics_provider.as_ref() else {
13119            return false;
13120        };
13121
13122        let mut supports = false;
13123        self.buffer().read(cx).for_each_buffer(|buffer| {
13124            supports |= provider.supports_inlay_hints(buffer, cx);
13125        });
13126        supports
13127    }
13128
13129    pub fn focus(&self, cx: &mut WindowContext) {
13130        cx.focus(&self.focus_handle)
13131    }
13132
13133    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13134        self.focus_handle.is_focused(cx)
13135    }
13136
13137    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13138        cx.emit(EditorEvent::Focused);
13139
13140        if let Some(descendant) = self
13141            .last_focused_descendant
13142            .take()
13143            .and_then(|descendant| descendant.upgrade())
13144        {
13145            cx.focus(&descendant);
13146        } else {
13147            if let Some(blame) = self.blame.as_ref() {
13148                blame.update(cx, GitBlame::focus)
13149            }
13150
13151            self.blink_manager.update(cx, BlinkManager::enable);
13152            self.show_cursor_names(cx);
13153            self.buffer.update(cx, |buffer, cx| {
13154                buffer.finalize_last_transaction(cx);
13155                if self.leader_peer_id.is_none() {
13156                    buffer.set_active_selections(
13157                        &self.selections.disjoint_anchors(),
13158                        self.selections.line_mode,
13159                        self.cursor_shape,
13160                        cx,
13161                    );
13162                }
13163            });
13164        }
13165    }
13166
13167    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13168        cx.emit(EditorEvent::FocusedIn)
13169    }
13170
13171    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13172        if event.blurred != self.focus_handle {
13173            self.last_focused_descendant = Some(event.blurred);
13174        }
13175    }
13176
13177    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13178        self.blink_manager.update(cx, BlinkManager::disable);
13179        self.buffer
13180            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13181
13182        if let Some(blame) = self.blame.as_ref() {
13183            blame.update(cx, GitBlame::blur)
13184        }
13185        if !self.hover_state.focused(cx) {
13186            hide_hover(self, cx);
13187        }
13188
13189        self.hide_context_menu(cx);
13190        cx.emit(EditorEvent::Blurred);
13191        cx.notify();
13192    }
13193
13194    pub fn register_action<A: Action>(
13195        &mut self,
13196        listener: impl Fn(&A, &mut WindowContext) + 'static,
13197    ) -> Subscription {
13198        let id = self.next_editor_action_id.post_inc();
13199        let listener = Arc::new(listener);
13200        self.editor_actions.borrow_mut().insert(
13201            id,
13202            Box::new(move |cx| {
13203                let cx = cx.window_context();
13204                let listener = listener.clone();
13205                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13206                    let action = action.downcast_ref().unwrap();
13207                    if phase == DispatchPhase::Bubble {
13208                        listener(action, cx)
13209                    }
13210                })
13211            }),
13212        );
13213
13214        let editor_actions = self.editor_actions.clone();
13215        Subscription::new(move || {
13216            editor_actions.borrow_mut().remove(&id);
13217        })
13218    }
13219
13220    pub fn file_header_size(&self) -> u32 {
13221        FILE_HEADER_HEIGHT
13222    }
13223
13224    pub fn revert(
13225        &mut self,
13226        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13227        cx: &mut ViewContext<Self>,
13228    ) {
13229        self.buffer().update(cx, |multi_buffer, cx| {
13230            for (buffer_id, changes) in revert_changes {
13231                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13232                    buffer.update(cx, |buffer, cx| {
13233                        buffer.edit(
13234                            changes.into_iter().map(|(range, text)| {
13235                                (range, text.to_string().map(Arc::<str>::from))
13236                            }),
13237                            None,
13238                            cx,
13239                        );
13240                    });
13241                }
13242            }
13243        });
13244        self.change_selections(None, cx, |selections| selections.refresh());
13245    }
13246
13247    pub fn to_pixel_point(
13248        &mut self,
13249        source: multi_buffer::Anchor,
13250        editor_snapshot: &EditorSnapshot,
13251        cx: &mut ViewContext<Self>,
13252    ) -> Option<gpui::Point<Pixels>> {
13253        let source_point = source.to_display_point(editor_snapshot);
13254        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13255    }
13256
13257    pub fn display_to_pixel_point(
13258        &mut self,
13259        source: DisplayPoint,
13260        editor_snapshot: &EditorSnapshot,
13261        cx: &mut ViewContext<Self>,
13262    ) -> Option<gpui::Point<Pixels>> {
13263        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13264        let text_layout_details = self.text_layout_details(cx);
13265        let scroll_top = text_layout_details
13266            .scroll_anchor
13267            .scroll_position(editor_snapshot)
13268            .y;
13269
13270        if source.row().as_f32() < scroll_top.floor() {
13271            return None;
13272        }
13273        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13274        let source_y = line_height * (source.row().as_f32() - scroll_top);
13275        Some(gpui::Point::new(source_x, source_y))
13276    }
13277
13278    pub fn has_active_completions_menu(&self) -> bool {
13279        self.context_menu.read().as_ref().map_or(false, |menu| {
13280            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13281        })
13282    }
13283
13284    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13285        self.addons
13286            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13287    }
13288
13289    pub fn unregister_addon<T: Addon>(&mut self) {
13290        self.addons.remove(&std::any::TypeId::of::<T>());
13291    }
13292
13293    pub fn addon<T: Addon>(&self) -> Option<&T> {
13294        let type_id = std::any::TypeId::of::<T>();
13295        self.addons
13296            .get(&type_id)
13297            .and_then(|item| item.to_any().downcast_ref::<T>())
13298    }
13299}
13300
13301fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13302    let tab_size = tab_size.get() as usize;
13303    let mut width = offset;
13304
13305    for ch in text.chars() {
13306        width += if ch == '\t' {
13307            tab_size - (width % tab_size)
13308        } else {
13309            1
13310        };
13311    }
13312
13313    width - offset
13314}
13315
13316#[cfg(test)]
13317mod tests {
13318    use super::*;
13319
13320    #[test]
13321    fn test_string_size_with_expanded_tabs() {
13322        let nz = |val| NonZeroU32::new(val).unwrap();
13323        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13324        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13325        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13326        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13327        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13328        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13329        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13330        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13331    }
13332}
13333
13334/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13335struct WordBreakingTokenizer<'a> {
13336    input: &'a str,
13337}
13338
13339impl<'a> WordBreakingTokenizer<'a> {
13340    fn new(input: &'a str) -> Self {
13341        Self { input }
13342    }
13343}
13344
13345fn is_char_ideographic(ch: char) -> bool {
13346    use unicode_script::Script::*;
13347    use unicode_script::UnicodeScript;
13348    matches!(ch.script(), Han | Tangut | Yi)
13349}
13350
13351fn is_grapheme_ideographic(text: &str) -> bool {
13352    text.chars().any(is_char_ideographic)
13353}
13354
13355fn is_grapheme_whitespace(text: &str) -> bool {
13356    text.chars().any(|x| x.is_whitespace())
13357}
13358
13359fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13360    text.chars().next().map_or(false, |ch| {
13361        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13362    })
13363}
13364
13365#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13366struct WordBreakToken<'a> {
13367    token: &'a str,
13368    grapheme_len: usize,
13369    is_whitespace: bool,
13370}
13371
13372impl<'a> Iterator for WordBreakingTokenizer<'a> {
13373    /// Yields a span, the count of graphemes in the token, and whether it was
13374    /// whitespace. Note that it also breaks at word boundaries.
13375    type Item = WordBreakToken<'a>;
13376
13377    fn next(&mut self) -> Option<Self::Item> {
13378        use unicode_segmentation::UnicodeSegmentation;
13379        if self.input.is_empty() {
13380            return None;
13381        }
13382
13383        let mut iter = self.input.graphemes(true).peekable();
13384        let mut offset = 0;
13385        let mut graphemes = 0;
13386        if let Some(first_grapheme) = iter.next() {
13387            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13388            offset += first_grapheme.len();
13389            graphemes += 1;
13390            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13391                if let Some(grapheme) = iter.peek().copied() {
13392                    if should_stay_with_preceding_ideograph(grapheme) {
13393                        offset += grapheme.len();
13394                        graphemes += 1;
13395                    }
13396                }
13397            } else {
13398                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13399                let mut next_word_bound = words.peek().copied();
13400                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13401                    next_word_bound = words.next();
13402                }
13403                while let Some(grapheme) = iter.peek().copied() {
13404                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13405                        break;
13406                    };
13407                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13408                        break;
13409                    };
13410                    offset += grapheme.len();
13411                    graphemes += 1;
13412                    iter.next();
13413                }
13414            }
13415            let token = &self.input[..offset];
13416            self.input = &self.input[offset..];
13417            if is_whitespace {
13418                Some(WordBreakToken {
13419                    token: " ",
13420                    grapheme_len: 1,
13421                    is_whitespace: true,
13422                })
13423            } else {
13424                Some(WordBreakToken {
13425                    token,
13426                    grapheme_len: graphemes,
13427                    is_whitespace: false,
13428                })
13429            }
13430        } else {
13431            None
13432        }
13433    }
13434}
13435
13436#[test]
13437fn test_word_breaking_tokenizer() {
13438    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13439        ("", &[]),
13440        ("  ", &[(" ", 1, true)]),
13441        ("Ʒ", &[("Ʒ", 1, false)]),
13442        ("Ǽ", &[("Ǽ", 1, false)]),
13443        ("", &[("", 1, false)]),
13444        ("⋑⋑", &[("⋑⋑", 2, false)]),
13445        (
13446            "原理,进而",
13447            &[
13448                ("", 1, false),
13449                ("理,", 2, false),
13450                ("", 1, false),
13451                ("", 1, false),
13452            ],
13453        ),
13454        (
13455            "hello world",
13456            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13457        ),
13458        (
13459            "hello, world",
13460            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13461        ),
13462        (
13463            "  hello world",
13464            &[
13465                (" ", 1, true),
13466                ("hello", 5, false),
13467                (" ", 1, true),
13468                ("world", 5, false),
13469            ],
13470        ),
13471        (
13472            "这是什么 \n 钢笔",
13473            &[
13474                ("", 1, false),
13475                ("", 1, false),
13476                ("", 1, false),
13477                ("", 1, false),
13478                (" ", 1, true),
13479                ("", 1, false),
13480                ("", 1, false),
13481            ],
13482        ),
13483        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13484    ];
13485
13486    for (input, result) in tests {
13487        assert_eq!(
13488            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13489            result
13490                .iter()
13491                .copied()
13492                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13493                    token,
13494                    grapheme_len,
13495                    is_whitespace,
13496                })
13497                .collect::<Vec<_>>()
13498        );
13499    }
13500}
13501
13502fn wrap_with_prefix(
13503    line_prefix: String,
13504    unwrapped_text: String,
13505    wrap_column: usize,
13506    tab_size: NonZeroU32,
13507) -> String {
13508    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13509    let mut wrapped_text = String::new();
13510    let mut current_line = line_prefix.clone();
13511
13512    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13513    let mut current_line_len = line_prefix_len;
13514    for WordBreakToken {
13515        token,
13516        grapheme_len,
13517        is_whitespace,
13518    } in tokenizer
13519    {
13520        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13521            wrapped_text.push_str(current_line.trim_end());
13522            wrapped_text.push('\n');
13523            current_line.truncate(line_prefix.len());
13524            current_line_len = line_prefix_len;
13525            if !is_whitespace {
13526                current_line.push_str(token);
13527                current_line_len += grapheme_len;
13528            }
13529        } else if !is_whitespace {
13530            current_line.push_str(token);
13531            current_line_len += grapheme_len;
13532        } else if current_line_len != line_prefix_len {
13533            current_line.push(' ');
13534            current_line_len += 1;
13535        }
13536    }
13537
13538    if !current_line.is_empty() {
13539        wrapped_text.push_str(&current_line);
13540    }
13541    wrapped_text
13542}
13543
13544#[test]
13545fn test_wrap_with_prefix() {
13546    assert_eq!(
13547        wrap_with_prefix(
13548            "# ".to_string(),
13549            "abcdefg".to_string(),
13550            4,
13551            NonZeroU32::new(4).unwrap()
13552        ),
13553        "# abcdefg"
13554    );
13555    assert_eq!(
13556        wrap_with_prefix(
13557            "".to_string(),
13558            "\thello world".to_string(),
13559            8,
13560            NonZeroU32::new(4).unwrap()
13561        ),
13562        "hello\nworld"
13563    );
13564    assert_eq!(
13565        wrap_with_prefix(
13566            "// ".to_string(),
13567            "xx \nyy zz aa bb cc".to_string(),
13568            12,
13569            NonZeroU32::new(4).unwrap()
13570        ),
13571        "// xx yy zz\n// aa bb cc"
13572    );
13573    assert_eq!(
13574        wrap_with_prefix(
13575            String::new(),
13576            "这是什么 \n 钢笔".to_string(),
13577            3,
13578            NonZeroU32::new(4).unwrap()
13579        ),
13580        "这是什\n么 钢\n"
13581    );
13582}
13583
13584fn hunks_for_selections(
13585    multi_buffer_snapshot: &MultiBufferSnapshot,
13586    selections: &[Selection<Anchor>],
13587) -> Vec<MultiBufferDiffHunk> {
13588    let buffer_rows_for_selections = selections.iter().map(|selection| {
13589        let head = selection.head();
13590        let tail = selection.tail();
13591        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13592        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13593        if start > end {
13594            end..start
13595        } else {
13596            start..end
13597        }
13598    });
13599
13600    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13601}
13602
13603pub fn hunks_for_rows(
13604    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13605    multi_buffer_snapshot: &MultiBufferSnapshot,
13606) -> Vec<MultiBufferDiffHunk> {
13607    let mut hunks = Vec::new();
13608    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13609        HashMap::default();
13610    for selected_multi_buffer_rows in rows {
13611        let query_rows =
13612            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13613        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13614            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13615            // when the caret is just above or just below the deleted hunk.
13616            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13617            let related_to_selection = if allow_adjacent {
13618                hunk.row_range.overlaps(&query_rows)
13619                    || hunk.row_range.start == query_rows.end
13620                    || hunk.row_range.end == query_rows.start
13621            } else {
13622                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13623                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13624                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13625                    || selected_multi_buffer_rows.end == hunk.row_range.start
13626            };
13627            if related_to_selection {
13628                if !processed_buffer_rows
13629                    .entry(hunk.buffer_id)
13630                    .or_default()
13631                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13632                {
13633                    continue;
13634                }
13635                hunks.push(hunk);
13636            }
13637        }
13638    }
13639
13640    hunks
13641}
13642
13643pub trait CollaborationHub {
13644    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13645    fn user_participant_indices<'a>(
13646        &self,
13647        cx: &'a AppContext,
13648    ) -> &'a HashMap<u64, ParticipantIndex>;
13649    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13650}
13651
13652impl CollaborationHub for Model<Project> {
13653    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13654        self.read(cx).collaborators()
13655    }
13656
13657    fn user_participant_indices<'a>(
13658        &self,
13659        cx: &'a AppContext,
13660    ) -> &'a HashMap<u64, ParticipantIndex> {
13661        self.read(cx).user_store().read(cx).participant_indices()
13662    }
13663
13664    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13665        let this = self.read(cx);
13666        let user_ids = this.collaborators().values().map(|c| c.user_id);
13667        this.user_store().read_with(cx, |user_store, cx| {
13668            user_store.participant_names(user_ids, cx)
13669        })
13670    }
13671}
13672
13673pub trait SemanticsProvider {
13674    fn hover(
13675        &self,
13676        buffer: &Model<Buffer>,
13677        position: text::Anchor,
13678        cx: &mut AppContext,
13679    ) -> Option<Task<Vec<project::Hover>>>;
13680
13681    fn inlay_hints(
13682        &self,
13683        buffer_handle: Model<Buffer>,
13684        range: Range<text::Anchor>,
13685        cx: &mut AppContext,
13686    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13687
13688    fn resolve_inlay_hint(
13689        &self,
13690        hint: InlayHint,
13691        buffer_handle: Model<Buffer>,
13692        server_id: LanguageServerId,
13693        cx: &mut AppContext,
13694    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13695
13696    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13697
13698    fn document_highlights(
13699        &self,
13700        buffer: &Model<Buffer>,
13701        position: text::Anchor,
13702        cx: &mut AppContext,
13703    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13704
13705    fn definitions(
13706        &self,
13707        buffer: &Model<Buffer>,
13708        position: text::Anchor,
13709        kind: GotoDefinitionKind,
13710        cx: &mut AppContext,
13711    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13712
13713    fn range_for_rename(
13714        &self,
13715        buffer: &Model<Buffer>,
13716        position: text::Anchor,
13717        cx: &mut AppContext,
13718    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13719
13720    fn perform_rename(
13721        &self,
13722        buffer: &Model<Buffer>,
13723        position: text::Anchor,
13724        new_name: String,
13725        cx: &mut AppContext,
13726    ) -> Option<Task<Result<ProjectTransaction>>>;
13727}
13728
13729pub trait CompletionProvider {
13730    fn completions(
13731        &self,
13732        buffer: &Model<Buffer>,
13733        buffer_position: text::Anchor,
13734        trigger: CompletionContext,
13735        cx: &mut ViewContext<Editor>,
13736    ) -> Task<Result<Vec<Completion>>>;
13737
13738    fn resolve_completions(
13739        &self,
13740        buffer: Model<Buffer>,
13741        completion_indices: Vec<usize>,
13742        completions: Arc<RwLock<Box<[Completion]>>>,
13743        cx: &mut ViewContext<Editor>,
13744    ) -> Task<Result<bool>>;
13745
13746    fn apply_additional_edits_for_completion(
13747        &self,
13748        buffer: Model<Buffer>,
13749        completion: Completion,
13750        push_to_history: bool,
13751        cx: &mut ViewContext<Editor>,
13752    ) -> Task<Result<Option<language::Transaction>>>;
13753
13754    fn is_completion_trigger(
13755        &self,
13756        buffer: &Model<Buffer>,
13757        position: language::Anchor,
13758        text: &str,
13759        trigger_in_words: bool,
13760        cx: &mut ViewContext<Editor>,
13761    ) -> bool;
13762
13763    fn sort_completions(&self) -> bool {
13764        true
13765    }
13766}
13767
13768pub trait CodeActionProvider {
13769    fn code_actions(
13770        &self,
13771        buffer: &Model<Buffer>,
13772        range: Range<text::Anchor>,
13773        cx: &mut WindowContext,
13774    ) -> Task<Result<Vec<CodeAction>>>;
13775
13776    fn apply_code_action(
13777        &self,
13778        buffer_handle: Model<Buffer>,
13779        action: CodeAction,
13780        excerpt_id: ExcerptId,
13781        push_to_history: bool,
13782        cx: &mut WindowContext,
13783    ) -> Task<Result<ProjectTransaction>>;
13784}
13785
13786impl CodeActionProvider for Model<Project> {
13787    fn code_actions(
13788        &self,
13789        buffer: &Model<Buffer>,
13790        range: Range<text::Anchor>,
13791        cx: &mut WindowContext,
13792    ) -> Task<Result<Vec<CodeAction>>> {
13793        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13794    }
13795
13796    fn apply_code_action(
13797        &self,
13798        buffer_handle: Model<Buffer>,
13799        action: CodeAction,
13800        _excerpt_id: ExcerptId,
13801        push_to_history: bool,
13802        cx: &mut WindowContext,
13803    ) -> Task<Result<ProjectTransaction>> {
13804        self.update(cx, |project, cx| {
13805            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13806        })
13807    }
13808}
13809
13810fn snippet_completions(
13811    project: &Project,
13812    buffer: &Model<Buffer>,
13813    buffer_position: text::Anchor,
13814    cx: &mut AppContext,
13815) -> Vec<Completion> {
13816    let language = buffer.read(cx).language_at(buffer_position);
13817    let language_name = language.as_ref().map(|language| language.lsp_id());
13818    let snippet_store = project.snippets().read(cx);
13819    let snippets = snippet_store.snippets_for(language_name, cx);
13820
13821    if snippets.is_empty() {
13822        return vec![];
13823    }
13824    let snapshot = buffer.read(cx).text_snapshot();
13825    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13826
13827    let scope = language.map(|language| language.default_scope());
13828    let classifier = CharClassifier::new(scope).for_completion(true);
13829    let mut last_word = chars
13830        .take_while(|c| classifier.is_word(*c))
13831        .collect::<String>();
13832    last_word = last_word.chars().rev().collect();
13833    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13834    let to_lsp = |point: &text::Anchor| {
13835        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13836        point_to_lsp(end)
13837    };
13838    let lsp_end = to_lsp(&buffer_position);
13839    snippets
13840        .into_iter()
13841        .filter_map(|snippet| {
13842            let matching_prefix = snippet
13843                .prefix
13844                .iter()
13845                .find(|prefix| prefix.starts_with(&last_word))?;
13846            let start = as_offset - last_word.len();
13847            let start = snapshot.anchor_before(start);
13848            let range = start..buffer_position;
13849            let lsp_start = to_lsp(&start);
13850            let lsp_range = lsp::Range {
13851                start: lsp_start,
13852                end: lsp_end,
13853            };
13854            Some(Completion {
13855                old_range: range,
13856                new_text: snippet.body.clone(),
13857                label: CodeLabel {
13858                    text: matching_prefix.clone(),
13859                    runs: vec![],
13860                    filter_range: 0..matching_prefix.len(),
13861                },
13862                server_id: LanguageServerId(usize::MAX),
13863                documentation: snippet.description.clone().map(Documentation::SingleLine),
13864                lsp_completion: lsp::CompletionItem {
13865                    label: snippet.prefix.first().unwrap().clone(),
13866                    kind: Some(CompletionItemKind::SNIPPET),
13867                    label_details: snippet.description.as_ref().map(|description| {
13868                        lsp::CompletionItemLabelDetails {
13869                            detail: Some(description.clone()),
13870                            description: None,
13871                        }
13872                    }),
13873                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13874                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13875                        lsp::InsertReplaceEdit {
13876                            new_text: snippet.body.clone(),
13877                            insert: lsp_range,
13878                            replace: lsp_range,
13879                        },
13880                    )),
13881                    filter_text: Some(snippet.body.clone()),
13882                    sort_text: Some(char::MAX.to_string()),
13883                    ..Default::default()
13884                },
13885                confirm: None,
13886            })
13887        })
13888        .collect()
13889}
13890
13891impl CompletionProvider for Model<Project> {
13892    fn completions(
13893        &self,
13894        buffer: &Model<Buffer>,
13895        buffer_position: text::Anchor,
13896        options: CompletionContext,
13897        cx: &mut ViewContext<Editor>,
13898    ) -> Task<Result<Vec<Completion>>> {
13899        self.update(cx, |project, cx| {
13900            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13901            let project_completions = project.completions(buffer, buffer_position, options, cx);
13902            cx.background_executor().spawn(async move {
13903                let mut completions = project_completions.await?;
13904                //let snippets = snippets.into_iter().;
13905                completions.extend(snippets);
13906                Ok(completions)
13907            })
13908        })
13909    }
13910
13911    fn resolve_completions(
13912        &self,
13913        buffer: Model<Buffer>,
13914        completion_indices: Vec<usize>,
13915        completions: Arc<RwLock<Box<[Completion]>>>,
13916        cx: &mut ViewContext<Editor>,
13917    ) -> Task<Result<bool>> {
13918        self.update(cx, |project, cx| {
13919            project.resolve_completions(buffer, completion_indices, completions, cx)
13920        })
13921    }
13922
13923    fn apply_additional_edits_for_completion(
13924        &self,
13925        buffer: Model<Buffer>,
13926        completion: Completion,
13927        push_to_history: bool,
13928        cx: &mut ViewContext<Editor>,
13929    ) -> Task<Result<Option<language::Transaction>>> {
13930        self.update(cx, |project, cx| {
13931            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13932        })
13933    }
13934
13935    fn is_completion_trigger(
13936        &self,
13937        buffer: &Model<Buffer>,
13938        position: language::Anchor,
13939        text: &str,
13940        trigger_in_words: bool,
13941        cx: &mut ViewContext<Editor>,
13942    ) -> bool {
13943        if !EditorSettings::get_global(cx).show_completions_on_input {
13944            return false;
13945        }
13946
13947        let mut chars = text.chars();
13948        let char = if let Some(char) = chars.next() {
13949            char
13950        } else {
13951            return false;
13952        };
13953        if chars.next().is_some() {
13954            return false;
13955        }
13956
13957        let buffer = buffer.read(cx);
13958        let classifier = buffer
13959            .snapshot()
13960            .char_classifier_at(position)
13961            .for_completion(true);
13962        if trigger_in_words && classifier.is_word(char) {
13963            return true;
13964        }
13965
13966        buffer.completion_triggers().contains(text)
13967    }
13968}
13969
13970impl SemanticsProvider for Model<Project> {
13971    fn hover(
13972        &self,
13973        buffer: &Model<Buffer>,
13974        position: text::Anchor,
13975        cx: &mut AppContext,
13976    ) -> Option<Task<Vec<project::Hover>>> {
13977        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13978    }
13979
13980    fn document_highlights(
13981        &self,
13982        buffer: &Model<Buffer>,
13983        position: text::Anchor,
13984        cx: &mut AppContext,
13985    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13986        Some(self.update(cx, |project, cx| {
13987            project.document_highlights(buffer, position, cx)
13988        }))
13989    }
13990
13991    fn definitions(
13992        &self,
13993        buffer: &Model<Buffer>,
13994        position: text::Anchor,
13995        kind: GotoDefinitionKind,
13996        cx: &mut AppContext,
13997    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13998        Some(self.update(cx, |project, cx| match kind {
13999            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14000            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14001            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14002            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14003        }))
14004    }
14005
14006    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14007        // TODO: make this work for remote projects
14008        self.read(cx)
14009            .language_servers_for_buffer(buffer.read(cx), cx)
14010            .any(
14011                |(_, server)| match server.capabilities().inlay_hint_provider {
14012                    Some(lsp::OneOf::Left(enabled)) => enabled,
14013                    Some(lsp::OneOf::Right(_)) => true,
14014                    None => false,
14015                },
14016            )
14017    }
14018
14019    fn inlay_hints(
14020        &self,
14021        buffer_handle: Model<Buffer>,
14022        range: Range<text::Anchor>,
14023        cx: &mut AppContext,
14024    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14025        Some(self.update(cx, |project, cx| {
14026            project.inlay_hints(buffer_handle, range, cx)
14027        }))
14028    }
14029
14030    fn resolve_inlay_hint(
14031        &self,
14032        hint: InlayHint,
14033        buffer_handle: Model<Buffer>,
14034        server_id: LanguageServerId,
14035        cx: &mut AppContext,
14036    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14037        Some(self.update(cx, |project, cx| {
14038            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14039        }))
14040    }
14041
14042    fn range_for_rename(
14043        &self,
14044        buffer: &Model<Buffer>,
14045        position: text::Anchor,
14046        cx: &mut AppContext,
14047    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14048        Some(self.update(cx, |project, cx| {
14049            project.prepare_rename(buffer.clone(), position, cx)
14050        }))
14051    }
14052
14053    fn perform_rename(
14054        &self,
14055        buffer: &Model<Buffer>,
14056        position: text::Anchor,
14057        new_name: String,
14058        cx: &mut AppContext,
14059    ) -> Option<Task<Result<ProjectTransaction>>> {
14060        Some(self.update(cx, |project, cx| {
14061            project.perform_rename(buffer.clone(), position, new_name, cx)
14062        }))
14063    }
14064}
14065
14066fn inlay_hint_settings(
14067    location: Anchor,
14068    snapshot: &MultiBufferSnapshot,
14069    cx: &mut ViewContext<'_, Editor>,
14070) -> InlayHintSettings {
14071    let file = snapshot.file_at(location);
14072    let language = snapshot.language_at(location).map(|l| l.name());
14073    language_settings(language, file, cx).inlay_hints
14074}
14075
14076fn consume_contiguous_rows(
14077    contiguous_row_selections: &mut Vec<Selection<Point>>,
14078    selection: &Selection<Point>,
14079    display_map: &DisplaySnapshot,
14080    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14081) -> (MultiBufferRow, MultiBufferRow) {
14082    contiguous_row_selections.push(selection.clone());
14083    let start_row = MultiBufferRow(selection.start.row);
14084    let mut end_row = ending_row(selection, display_map);
14085
14086    while let Some(next_selection) = selections.peek() {
14087        if next_selection.start.row <= end_row.0 {
14088            end_row = ending_row(next_selection, display_map);
14089            contiguous_row_selections.push(selections.next().unwrap().clone());
14090        } else {
14091            break;
14092        }
14093    }
14094    (start_row, end_row)
14095}
14096
14097fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14098    if next_selection.end.column > 0 || next_selection.is_empty() {
14099        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14100    } else {
14101        MultiBufferRow(next_selection.end.row)
14102    }
14103}
14104
14105impl EditorSnapshot {
14106    pub fn remote_selections_in_range<'a>(
14107        &'a self,
14108        range: &'a Range<Anchor>,
14109        collaboration_hub: &dyn CollaborationHub,
14110        cx: &'a AppContext,
14111    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14112        let participant_names = collaboration_hub.user_names(cx);
14113        let participant_indices = collaboration_hub.user_participant_indices(cx);
14114        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14115        let collaborators_by_replica_id = collaborators_by_peer_id
14116            .iter()
14117            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14118            .collect::<HashMap<_, _>>();
14119        self.buffer_snapshot
14120            .selections_in_range(range, false)
14121            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14122                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14123                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14124                let user_name = participant_names.get(&collaborator.user_id).cloned();
14125                Some(RemoteSelection {
14126                    replica_id,
14127                    selection,
14128                    cursor_shape,
14129                    line_mode,
14130                    participant_index,
14131                    peer_id: collaborator.peer_id,
14132                    user_name,
14133                })
14134            })
14135    }
14136
14137    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14138        self.display_snapshot.buffer_snapshot.language_at(position)
14139    }
14140
14141    pub fn is_focused(&self) -> bool {
14142        self.is_focused
14143    }
14144
14145    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14146        self.placeholder_text.as_ref()
14147    }
14148
14149    pub fn scroll_position(&self) -> gpui::Point<f32> {
14150        self.scroll_anchor.scroll_position(&self.display_snapshot)
14151    }
14152
14153    fn gutter_dimensions(
14154        &self,
14155        font_id: FontId,
14156        font_size: Pixels,
14157        em_width: Pixels,
14158        em_advance: Pixels,
14159        max_line_number_width: Pixels,
14160        cx: &AppContext,
14161    ) -> GutterDimensions {
14162        if !self.show_gutter {
14163            return GutterDimensions::default();
14164        }
14165        let descent = cx.text_system().descent(font_id, font_size);
14166
14167        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14168            matches!(
14169                ProjectSettings::get_global(cx).git.git_gutter,
14170                Some(GitGutterSetting::TrackedFiles)
14171            )
14172        });
14173        let gutter_settings = EditorSettings::get_global(cx).gutter;
14174        let show_line_numbers = self
14175            .show_line_numbers
14176            .unwrap_or(gutter_settings.line_numbers);
14177        let line_gutter_width = if show_line_numbers {
14178            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14179            let min_width_for_number_on_gutter = em_advance * 4.0;
14180            max_line_number_width.max(min_width_for_number_on_gutter)
14181        } else {
14182            0.0.into()
14183        };
14184
14185        let show_code_actions = self
14186            .show_code_actions
14187            .unwrap_or(gutter_settings.code_actions);
14188
14189        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14190
14191        let git_blame_entries_width =
14192            self.git_blame_gutter_max_author_length
14193                .map(|max_author_length| {
14194                    // Length of the author name, but also space for the commit hash,
14195                    // the spacing and the timestamp.
14196                    let max_char_count = max_author_length
14197                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14198                        + 7 // length of commit sha
14199                        + 14 // length of max relative timestamp ("60 minutes ago")
14200                        + 4; // gaps and margins
14201
14202                    em_advance * max_char_count
14203                });
14204
14205        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14206        left_padding += if show_code_actions || show_runnables {
14207            em_width * 3.0
14208        } else if show_git_gutter && show_line_numbers {
14209            em_width * 2.0
14210        } else if show_git_gutter || show_line_numbers {
14211            em_width
14212        } else {
14213            px(0.)
14214        };
14215
14216        let right_padding = if gutter_settings.folds && show_line_numbers {
14217            em_width * 4.0
14218        } else if gutter_settings.folds {
14219            em_width * 3.0
14220        } else if show_line_numbers {
14221            em_width
14222        } else {
14223            px(0.)
14224        };
14225
14226        GutterDimensions {
14227            left_padding,
14228            right_padding,
14229            width: line_gutter_width + left_padding + right_padding,
14230            margin: -descent,
14231            git_blame_entries_width,
14232        }
14233    }
14234
14235    pub fn render_crease_toggle(
14236        &self,
14237        buffer_row: MultiBufferRow,
14238        row_contains_cursor: bool,
14239        editor: View<Editor>,
14240        cx: &mut WindowContext,
14241    ) -> Option<AnyElement> {
14242        let folded = self.is_line_folded(buffer_row);
14243        let mut is_foldable = false;
14244
14245        if let Some(crease) = self
14246            .crease_snapshot
14247            .query_row(buffer_row, &self.buffer_snapshot)
14248        {
14249            is_foldable = true;
14250            match crease {
14251                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14252                    if let Some(render_toggle) = render_toggle {
14253                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14254                            if folded {
14255                                editor.update(cx, |editor, cx| {
14256                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14257                                });
14258                            } else {
14259                                editor.update(cx, |editor, cx| {
14260                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14261                                });
14262                            }
14263                        });
14264                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14265                    }
14266                }
14267            }
14268        }
14269
14270        is_foldable |= self.starts_indent(buffer_row);
14271
14272        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14273            Some(
14274                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14275                    .selected(folded)
14276                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14277                        if folded {
14278                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14279                        } else {
14280                            this.fold_at(&FoldAt { buffer_row }, cx);
14281                        }
14282                    }))
14283                    .into_any_element(),
14284            )
14285        } else {
14286            None
14287        }
14288    }
14289
14290    pub fn render_crease_trailer(
14291        &self,
14292        buffer_row: MultiBufferRow,
14293        cx: &mut WindowContext,
14294    ) -> Option<AnyElement> {
14295        let folded = self.is_line_folded(buffer_row);
14296        if let Crease::Inline { render_trailer, .. } = self
14297            .crease_snapshot
14298            .query_row(buffer_row, &self.buffer_snapshot)?
14299        {
14300            let render_trailer = render_trailer.as_ref()?;
14301            Some(render_trailer(buffer_row, folded, cx))
14302        } else {
14303            None
14304        }
14305    }
14306}
14307
14308impl Deref for EditorSnapshot {
14309    type Target = DisplaySnapshot;
14310
14311    fn deref(&self) -> &Self::Target {
14312        &self.display_snapshot
14313    }
14314}
14315
14316#[derive(Clone, Debug, PartialEq, Eq)]
14317pub enum EditorEvent {
14318    InputIgnored {
14319        text: Arc<str>,
14320    },
14321    InputHandled {
14322        utf16_range_to_replace: Option<Range<isize>>,
14323        text: Arc<str>,
14324    },
14325    ExcerptsAdded {
14326        buffer: Model<Buffer>,
14327        predecessor: ExcerptId,
14328        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14329    },
14330    ExcerptsRemoved {
14331        ids: Vec<ExcerptId>,
14332    },
14333    ExcerptsEdited {
14334        ids: Vec<ExcerptId>,
14335    },
14336    ExcerptsExpanded {
14337        ids: Vec<ExcerptId>,
14338    },
14339    BufferEdited,
14340    Edited {
14341        transaction_id: clock::Lamport,
14342    },
14343    Reparsed(BufferId),
14344    Focused,
14345    FocusedIn,
14346    Blurred,
14347    DirtyChanged,
14348    Saved,
14349    TitleChanged,
14350    DiffBaseChanged,
14351    SelectionsChanged {
14352        local: bool,
14353    },
14354    ScrollPositionChanged {
14355        local: bool,
14356        autoscroll: bool,
14357    },
14358    Closed,
14359    TransactionUndone {
14360        transaction_id: clock::Lamport,
14361    },
14362    TransactionBegun {
14363        transaction_id: clock::Lamport,
14364    },
14365    Reloaded,
14366    CursorShapeChanged,
14367}
14368
14369impl EventEmitter<EditorEvent> for Editor {}
14370
14371impl FocusableView for Editor {
14372    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14373        self.focus_handle.clone()
14374    }
14375}
14376
14377impl Render for Editor {
14378    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14379        let settings = ThemeSettings::get_global(cx);
14380
14381        let mut text_style = match self.mode {
14382            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14383                color: cx.theme().colors().editor_foreground,
14384                font_family: settings.ui_font.family.clone(),
14385                font_features: settings.ui_font.features.clone(),
14386                font_fallbacks: settings.ui_font.fallbacks.clone(),
14387                font_size: rems(0.875).into(),
14388                font_weight: settings.ui_font.weight,
14389                line_height: relative(settings.buffer_line_height.value()),
14390                ..Default::default()
14391            },
14392            EditorMode::Full => TextStyle {
14393                color: cx.theme().colors().editor_foreground,
14394                font_family: settings.buffer_font.family.clone(),
14395                font_features: settings.buffer_font.features.clone(),
14396                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14397                font_size: settings.buffer_font_size(cx).into(),
14398                font_weight: settings.buffer_font.weight,
14399                line_height: relative(settings.buffer_line_height.value()),
14400                ..Default::default()
14401            },
14402        };
14403        if let Some(text_style_refinement) = &self.text_style_refinement {
14404            text_style.refine(text_style_refinement)
14405        }
14406
14407        let background = match self.mode {
14408            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14409            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14410            EditorMode::Full => cx.theme().colors().editor_background,
14411        };
14412
14413        EditorElement::new(
14414            cx.view(),
14415            EditorStyle {
14416                background,
14417                local_player: cx.theme().players().local(),
14418                text: text_style,
14419                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14420                syntax: cx.theme().syntax().clone(),
14421                status: cx.theme().status().clone(),
14422                inlay_hints_style: make_inlay_hints_style(cx),
14423                suggestions_style: HighlightStyle {
14424                    color: Some(cx.theme().status().predictive),
14425                    ..HighlightStyle::default()
14426                },
14427                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14428            },
14429        )
14430    }
14431}
14432
14433impl ViewInputHandler for Editor {
14434    fn text_for_range(
14435        &mut self,
14436        range_utf16: Range<usize>,
14437        cx: &mut ViewContext<Self>,
14438    ) -> Option<String> {
14439        Some(
14440            self.buffer
14441                .read(cx)
14442                .read(cx)
14443                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14444                .collect(),
14445        )
14446    }
14447
14448    fn selected_text_range(
14449        &mut self,
14450        ignore_disabled_input: bool,
14451        cx: &mut ViewContext<Self>,
14452    ) -> Option<UTF16Selection> {
14453        // Prevent the IME menu from appearing when holding down an alphabetic key
14454        // while input is disabled.
14455        if !ignore_disabled_input && !self.input_enabled {
14456            return None;
14457        }
14458
14459        let selection = self.selections.newest::<OffsetUtf16>(cx);
14460        let range = selection.range();
14461
14462        Some(UTF16Selection {
14463            range: range.start.0..range.end.0,
14464            reversed: selection.reversed,
14465        })
14466    }
14467
14468    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14469        let snapshot = self.buffer.read(cx).read(cx);
14470        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14471        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14472    }
14473
14474    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14475        self.clear_highlights::<InputComposition>(cx);
14476        self.ime_transaction.take();
14477    }
14478
14479    fn replace_text_in_range(
14480        &mut self,
14481        range_utf16: Option<Range<usize>>,
14482        text: &str,
14483        cx: &mut ViewContext<Self>,
14484    ) {
14485        if !self.input_enabled {
14486            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14487            return;
14488        }
14489
14490        self.transact(cx, |this, cx| {
14491            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14492                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14493                Some(this.selection_replacement_ranges(range_utf16, cx))
14494            } else {
14495                this.marked_text_ranges(cx)
14496            };
14497
14498            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14499                let newest_selection_id = this.selections.newest_anchor().id;
14500                this.selections
14501                    .all::<OffsetUtf16>(cx)
14502                    .iter()
14503                    .zip(ranges_to_replace.iter())
14504                    .find_map(|(selection, range)| {
14505                        if selection.id == newest_selection_id {
14506                            Some(
14507                                (range.start.0 as isize - selection.head().0 as isize)
14508                                    ..(range.end.0 as isize - selection.head().0 as isize),
14509                            )
14510                        } else {
14511                            None
14512                        }
14513                    })
14514            });
14515
14516            cx.emit(EditorEvent::InputHandled {
14517                utf16_range_to_replace: range_to_replace,
14518                text: text.into(),
14519            });
14520
14521            if let Some(new_selected_ranges) = new_selected_ranges {
14522                this.change_selections(None, cx, |selections| {
14523                    selections.select_ranges(new_selected_ranges)
14524                });
14525                this.backspace(&Default::default(), cx);
14526            }
14527
14528            this.handle_input(text, cx);
14529        });
14530
14531        if let Some(transaction) = self.ime_transaction {
14532            self.buffer.update(cx, |buffer, cx| {
14533                buffer.group_until_transaction(transaction, cx);
14534            });
14535        }
14536
14537        self.unmark_text(cx);
14538    }
14539
14540    fn replace_and_mark_text_in_range(
14541        &mut self,
14542        range_utf16: Option<Range<usize>>,
14543        text: &str,
14544        new_selected_range_utf16: Option<Range<usize>>,
14545        cx: &mut ViewContext<Self>,
14546    ) {
14547        if !self.input_enabled {
14548            return;
14549        }
14550
14551        let transaction = self.transact(cx, |this, cx| {
14552            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14553                let snapshot = this.buffer.read(cx).read(cx);
14554                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14555                    for marked_range in &mut marked_ranges {
14556                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14557                        marked_range.start.0 += relative_range_utf16.start;
14558                        marked_range.start =
14559                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14560                        marked_range.end =
14561                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14562                    }
14563                }
14564                Some(marked_ranges)
14565            } else if let Some(range_utf16) = range_utf16 {
14566                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14567                Some(this.selection_replacement_ranges(range_utf16, cx))
14568            } else {
14569                None
14570            };
14571
14572            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14573                let newest_selection_id = this.selections.newest_anchor().id;
14574                this.selections
14575                    .all::<OffsetUtf16>(cx)
14576                    .iter()
14577                    .zip(ranges_to_replace.iter())
14578                    .find_map(|(selection, range)| {
14579                        if selection.id == newest_selection_id {
14580                            Some(
14581                                (range.start.0 as isize - selection.head().0 as isize)
14582                                    ..(range.end.0 as isize - selection.head().0 as isize),
14583                            )
14584                        } else {
14585                            None
14586                        }
14587                    })
14588            });
14589
14590            cx.emit(EditorEvent::InputHandled {
14591                utf16_range_to_replace: range_to_replace,
14592                text: text.into(),
14593            });
14594
14595            if let Some(ranges) = ranges_to_replace {
14596                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14597            }
14598
14599            let marked_ranges = {
14600                let snapshot = this.buffer.read(cx).read(cx);
14601                this.selections
14602                    .disjoint_anchors()
14603                    .iter()
14604                    .map(|selection| {
14605                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14606                    })
14607                    .collect::<Vec<_>>()
14608            };
14609
14610            if text.is_empty() {
14611                this.unmark_text(cx);
14612            } else {
14613                this.highlight_text::<InputComposition>(
14614                    marked_ranges.clone(),
14615                    HighlightStyle {
14616                        underline: Some(UnderlineStyle {
14617                            thickness: px(1.),
14618                            color: None,
14619                            wavy: false,
14620                        }),
14621                        ..Default::default()
14622                    },
14623                    cx,
14624                );
14625            }
14626
14627            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14628            let use_autoclose = this.use_autoclose;
14629            let use_auto_surround = this.use_auto_surround;
14630            this.set_use_autoclose(false);
14631            this.set_use_auto_surround(false);
14632            this.handle_input(text, cx);
14633            this.set_use_autoclose(use_autoclose);
14634            this.set_use_auto_surround(use_auto_surround);
14635
14636            if let Some(new_selected_range) = new_selected_range_utf16 {
14637                let snapshot = this.buffer.read(cx).read(cx);
14638                let new_selected_ranges = marked_ranges
14639                    .into_iter()
14640                    .map(|marked_range| {
14641                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14642                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14643                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14644                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14645                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14646                    })
14647                    .collect::<Vec<_>>();
14648
14649                drop(snapshot);
14650                this.change_selections(None, cx, |selections| {
14651                    selections.select_ranges(new_selected_ranges)
14652                });
14653            }
14654        });
14655
14656        self.ime_transaction = self.ime_transaction.or(transaction);
14657        if let Some(transaction) = self.ime_transaction {
14658            self.buffer.update(cx, |buffer, cx| {
14659                buffer.group_until_transaction(transaction, cx);
14660            });
14661        }
14662
14663        if self.text_highlights::<InputComposition>(cx).is_none() {
14664            self.ime_transaction.take();
14665        }
14666    }
14667
14668    fn bounds_for_range(
14669        &mut self,
14670        range_utf16: Range<usize>,
14671        element_bounds: gpui::Bounds<Pixels>,
14672        cx: &mut ViewContext<Self>,
14673    ) -> Option<gpui::Bounds<Pixels>> {
14674        let text_layout_details = self.text_layout_details(cx);
14675        let style = &text_layout_details.editor_style;
14676        let font_id = cx.text_system().resolve_font(&style.text.font());
14677        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14678        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14679
14680        let em_width = cx
14681            .text_system()
14682            .typographic_bounds(font_id, font_size, 'm')
14683            .unwrap()
14684            .size
14685            .width;
14686
14687        let snapshot = self.snapshot(cx);
14688        let scroll_position = snapshot.scroll_position();
14689        let scroll_left = scroll_position.x * em_width;
14690
14691        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14692        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14693            + self.gutter_dimensions.width;
14694        let y = line_height * (start.row().as_f32() - scroll_position.y);
14695
14696        Some(Bounds {
14697            origin: element_bounds.origin + point(x, y),
14698            size: size(em_width, line_height),
14699        })
14700    }
14701}
14702
14703trait SelectionExt {
14704    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14705    fn spanned_rows(
14706        &self,
14707        include_end_if_at_line_start: bool,
14708        map: &DisplaySnapshot,
14709    ) -> Range<MultiBufferRow>;
14710}
14711
14712impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14713    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14714        let start = self
14715            .start
14716            .to_point(&map.buffer_snapshot)
14717            .to_display_point(map);
14718        let end = self
14719            .end
14720            .to_point(&map.buffer_snapshot)
14721            .to_display_point(map);
14722        if self.reversed {
14723            end..start
14724        } else {
14725            start..end
14726        }
14727    }
14728
14729    fn spanned_rows(
14730        &self,
14731        include_end_if_at_line_start: bool,
14732        map: &DisplaySnapshot,
14733    ) -> Range<MultiBufferRow> {
14734        let start = self.start.to_point(&map.buffer_snapshot);
14735        let mut end = self.end.to_point(&map.buffer_snapshot);
14736        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14737            end.row -= 1;
14738        }
14739
14740        let buffer_start = map.prev_line_boundary(start).0;
14741        let buffer_end = map.next_line_boundary(end).0;
14742        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14743    }
14744}
14745
14746impl<T: InvalidationRegion> InvalidationStack<T> {
14747    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14748    where
14749        S: Clone + ToOffset,
14750    {
14751        while let Some(region) = self.last() {
14752            let all_selections_inside_invalidation_ranges =
14753                if selections.len() == region.ranges().len() {
14754                    selections
14755                        .iter()
14756                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14757                        .all(|(selection, invalidation_range)| {
14758                            let head = selection.head().to_offset(buffer);
14759                            invalidation_range.start <= head && invalidation_range.end >= head
14760                        })
14761                } else {
14762                    false
14763                };
14764
14765            if all_selections_inside_invalidation_ranges {
14766                break;
14767            } else {
14768                self.pop();
14769            }
14770        }
14771    }
14772}
14773
14774impl<T> Default for InvalidationStack<T> {
14775    fn default() -> Self {
14776        Self(Default::default())
14777    }
14778}
14779
14780impl<T> Deref for InvalidationStack<T> {
14781    type Target = Vec<T>;
14782
14783    fn deref(&self) -> &Self::Target {
14784        &self.0
14785    }
14786}
14787
14788impl<T> DerefMut for InvalidationStack<T> {
14789    fn deref_mut(&mut self) -> &mut Self::Target {
14790        &mut self.0
14791    }
14792}
14793
14794impl InvalidationRegion for SnippetState {
14795    fn ranges(&self) -> &[Range<Anchor>] {
14796        &self.ranges[self.active_index]
14797    }
14798}
14799
14800pub fn diagnostic_block_renderer(
14801    diagnostic: Diagnostic,
14802    max_message_rows: Option<u8>,
14803    allow_closing: bool,
14804    _is_valid: bool,
14805) -> RenderBlock {
14806    let (text_without_backticks, code_ranges) =
14807        highlight_diagnostic_message(&diagnostic, max_message_rows);
14808
14809    Arc::new(move |cx: &mut BlockContext| {
14810        let group_id: SharedString = cx.block_id.to_string().into();
14811
14812        let mut text_style = cx.text_style().clone();
14813        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14814        let theme_settings = ThemeSettings::get_global(cx);
14815        text_style.font_family = theme_settings.buffer_font.family.clone();
14816        text_style.font_style = theme_settings.buffer_font.style;
14817        text_style.font_features = theme_settings.buffer_font.features.clone();
14818        text_style.font_weight = theme_settings.buffer_font.weight;
14819
14820        let multi_line_diagnostic = diagnostic.message.contains('\n');
14821
14822        let buttons = |diagnostic: &Diagnostic| {
14823            if multi_line_diagnostic {
14824                v_flex()
14825            } else {
14826                h_flex()
14827            }
14828            .when(allow_closing, |div| {
14829                div.children(diagnostic.is_primary.then(|| {
14830                    IconButton::new("close-block", IconName::XCircle)
14831                        .icon_color(Color::Muted)
14832                        .size(ButtonSize::Compact)
14833                        .style(ButtonStyle::Transparent)
14834                        .visible_on_hover(group_id.clone())
14835                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14836                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14837                }))
14838            })
14839            .child(
14840                IconButton::new("copy-block", IconName::Copy)
14841                    .icon_color(Color::Muted)
14842                    .size(ButtonSize::Compact)
14843                    .style(ButtonStyle::Transparent)
14844                    .visible_on_hover(group_id.clone())
14845                    .on_click({
14846                        let message = diagnostic.message.clone();
14847                        move |_click, cx| {
14848                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14849                        }
14850                    })
14851                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14852            )
14853        };
14854
14855        let icon_size = buttons(&diagnostic)
14856            .into_any_element()
14857            .layout_as_root(AvailableSpace::min_size(), cx);
14858
14859        h_flex()
14860            .id(cx.block_id)
14861            .group(group_id.clone())
14862            .relative()
14863            .size_full()
14864            .block_mouse_down()
14865            .pl(cx.gutter_dimensions.width)
14866            .w(cx.max_width - cx.gutter_dimensions.full_width())
14867            .child(
14868                div()
14869                    .flex()
14870                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14871                    .flex_shrink(),
14872            )
14873            .child(buttons(&diagnostic))
14874            .child(div().flex().flex_shrink_0().child(
14875                StyledText::new(text_without_backticks.clone()).with_highlights(
14876                    &text_style,
14877                    code_ranges.iter().map(|range| {
14878                        (
14879                            range.clone(),
14880                            HighlightStyle {
14881                                font_weight: Some(FontWeight::BOLD),
14882                                ..Default::default()
14883                            },
14884                        )
14885                    }),
14886                ),
14887            ))
14888            .into_any_element()
14889    })
14890}
14891
14892pub fn highlight_diagnostic_message(
14893    diagnostic: &Diagnostic,
14894    mut max_message_rows: Option<u8>,
14895) -> (SharedString, Vec<Range<usize>>) {
14896    let mut text_without_backticks = String::new();
14897    let mut code_ranges = Vec::new();
14898
14899    if let Some(source) = &diagnostic.source {
14900        text_without_backticks.push_str(source);
14901        code_ranges.push(0..source.len());
14902        text_without_backticks.push_str(": ");
14903    }
14904
14905    let mut prev_offset = 0;
14906    let mut in_code_block = false;
14907    let has_row_limit = max_message_rows.is_some();
14908    let mut newline_indices = diagnostic
14909        .message
14910        .match_indices('\n')
14911        .filter(|_| has_row_limit)
14912        .map(|(ix, _)| ix)
14913        .fuse()
14914        .peekable();
14915
14916    for (quote_ix, _) in diagnostic
14917        .message
14918        .match_indices('`')
14919        .chain([(diagnostic.message.len(), "")])
14920    {
14921        let mut first_newline_ix = None;
14922        let mut last_newline_ix = None;
14923        while let Some(newline_ix) = newline_indices.peek() {
14924            if *newline_ix < quote_ix {
14925                if first_newline_ix.is_none() {
14926                    first_newline_ix = Some(*newline_ix);
14927                }
14928                last_newline_ix = Some(*newline_ix);
14929
14930                if let Some(rows_left) = &mut max_message_rows {
14931                    if *rows_left == 0 {
14932                        break;
14933                    } else {
14934                        *rows_left -= 1;
14935                    }
14936                }
14937                let _ = newline_indices.next();
14938            } else {
14939                break;
14940            }
14941        }
14942        let prev_len = text_without_backticks.len();
14943        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14944        text_without_backticks.push_str(new_text);
14945        if in_code_block {
14946            code_ranges.push(prev_len..text_without_backticks.len());
14947        }
14948        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14949        in_code_block = !in_code_block;
14950        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14951            text_without_backticks.push_str("...");
14952            break;
14953        }
14954    }
14955
14956    (text_without_backticks.into(), code_ranges)
14957}
14958
14959fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14960    match severity {
14961        DiagnosticSeverity::ERROR => colors.error,
14962        DiagnosticSeverity::WARNING => colors.warning,
14963        DiagnosticSeverity::INFORMATION => colors.info,
14964        DiagnosticSeverity::HINT => colors.info,
14965        _ => colors.ignored,
14966    }
14967}
14968
14969pub fn styled_runs_for_code_label<'a>(
14970    label: &'a CodeLabel,
14971    syntax_theme: &'a theme::SyntaxTheme,
14972) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14973    let fade_out = HighlightStyle {
14974        fade_out: Some(0.35),
14975        ..Default::default()
14976    };
14977
14978    let mut prev_end = label.filter_range.end;
14979    label
14980        .runs
14981        .iter()
14982        .enumerate()
14983        .flat_map(move |(ix, (range, highlight_id))| {
14984            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14985                style
14986            } else {
14987                return Default::default();
14988            };
14989            let mut muted_style = style;
14990            muted_style.highlight(fade_out);
14991
14992            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14993            if range.start >= label.filter_range.end {
14994                if range.start > prev_end {
14995                    runs.push((prev_end..range.start, fade_out));
14996                }
14997                runs.push((range.clone(), muted_style));
14998            } else if range.end <= label.filter_range.end {
14999                runs.push((range.clone(), style));
15000            } else {
15001                runs.push((range.start..label.filter_range.end, style));
15002                runs.push((label.filter_range.end..range.end, muted_style));
15003            }
15004            prev_end = cmp::max(prev_end, range.end);
15005
15006            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15007                runs.push((prev_end..label.text.len(), fade_out));
15008            }
15009
15010            runs
15011        })
15012}
15013
15014pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15015    let mut prev_index = 0;
15016    let mut prev_codepoint: Option<char> = None;
15017    text.char_indices()
15018        .chain([(text.len(), '\0')])
15019        .filter_map(move |(index, codepoint)| {
15020            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15021            let is_boundary = index == text.len()
15022                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15023                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15024            if is_boundary {
15025                let chunk = &text[prev_index..index];
15026                prev_index = index;
15027                Some(chunk)
15028            } else {
15029                None
15030            }
15031        })
15032}
15033
15034pub trait RangeToAnchorExt: Sized {
15035    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15036
15037    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15038        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15039        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15040    }
15041}
15042
15043impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15044    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15045        let start_offset = self.start.to_offset(snapshot);
15046        let end_offset = self.end.to_offset(snapshot);
15047        if start_offset == end_offset {
15048            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15049        } else {
15050            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15051        }
15052    }
15053}
15054
15055pub trait RowExt {
15056    fn as_f32(&self) -> f32;
15057
15058    fn next_row(&self) -> Self;
15059
15060    fn previous_row(&self) -> Self;
15061
15062    fn minus(&self, other: Self) -> u32;
15063}
15064
15065impl RowExt for DisplayRow {
15066    fn as_f32(&self) -> f32 {
15067        self.0 as f32
15068    }
15069
15070    fn next_row(&self) -> Self {
15071        Self(self.0 + 1)
15072    }
15073
15074    fn previous_row(&self) -> Self {
15075        Self(self.0.saturating_sub(1))
15076    }
15077
15078    fn minus(&self, other: Self) -> u32 {
15079        self.0 - other.0
15080    }
15081}
15082
15083impl RowExt for MultiBufferRow {
15084    fn as_f32(&self) -> f32 {
15085        self.0 as f32
15086    }
15087
15088    fn next_row(&self) -> Self {
15089        Self(self.0 + 1)
15090    }
15091
15092    fn previous_row(&self) -> Self {
15093        Self(self.0.saturating_sub(1))
15094    }
15095
15096    fn minus(&self, other: Self) -> u32 {
15097        self.0 - other.0
15098    }
15099}
15100
15101trait RowRangeExt {
15102    type Row;
15103
15104    fn len(&self) -> usize;
15105
15106    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15107}
15108
15109impl RowRangeExt for Range<MultiBufferRow> {
15110    type Row = MultiBufferRow;
15111
15112    fn len(&self) -> usize {
15113        (self.end.0 - self.start.0) as usize
15114    }
15115
15116    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15117        (self.start.0..self.end.0).map(MultiBufferRow)
15118    }
15119}
15120
15121impl RowRangeExt for Range<DisplayRow> {
15122    type Row = DisplayRow;
15123
15124    fn len(&self) -> usize {
15125        (self.end.0 - self.start.0) as usize
15126    }
15127
15128    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15129        (self.start.0..self.end.0).map(DisplayRow)
15130    }
15131}
15132
15133fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15134    if hunk.diff_base_byte_range.is_empty() {
15135        DiffHunkStatus::Added
15136    } else if hunk.row_range.is_empty() {
15137        DiffHunkStatus::Removed
15138    } else {
15139        DiffHunkStatus::Modified
15140    }
15141}
15142
15143/// If select range has more than one line, we
15144/// just point the cursor to range.start.
15145fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15146    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15147        range
15148    } else {
15149        range.start..range.start
15150    }
15151}
15152
15153const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);