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;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45mod signature_help;
   46#[cfg(any(test, feature = "test-support"))]
   47pub mod test;
   48
   49use ::git::diff::DiffHunkStatus;
   50pub(crate) use actions::*;
   51pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use debounced_delay::DebouncedDelay;
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use gpui::{
   74    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   75    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   76    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   77    FocusableView, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
   78    ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   79    ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
   80    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   81    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   82};
   83use highlight_matching_bracket::refresh_matching_bracket_highlights;
   84use hover_popover::{hide_hover, HoverState};
   85pub(crate) use hunk_diff::HoveredHunk;
   86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   87use indent_guides::ActiveIndentGuidesState;
   88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   89pub use inline_completion::Direction;
   90use inline_completion::{InlayProposal, InlineCompletionProvider, InlineCompletionProviderHandle};
   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(Debug, Copy, Clone, PartialEq, Eq)]
  277pub enum Navigated {
  278    Yes,
  279    No,
  280}
  281
  282impl Navigated {
  283    pub fn from_bool(yes: bool) -> Navigated {
  284        if yes {
  285            Navigated::Yes
  286        } else {
  287            Navigated::No
  288        }
  289    }
  290}
  291
  292pub fn init_settings(cx: &mut AppContext) {
  293    EditorSettings::register(cx);
  294}
  295
  296pub fn init(cx: &mut AppContext) {
  297    init_settings(cx);
  298
  299    workspace::register_project_item::<Editor>(cx);
  300    workspace::FollowableViewRegistry::register::<Editor>(cx);
  301    workspace::register_serializable_item::<Editor>(cx);
  302
  303    cx.observe_new_views(
  304        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  305            workspace.register_action(Editor::new_file);
  306            workspace.register_action(Editor::new_file_vertical);
  307            workspace.register_action(Editor::new_file_horizontal);
  308        },
  309    )
  310    .detach();
  311
  312    cx.on_action(move |_: &workspace::NewFile, cx| {
  313        let app_state = workspace::AppState::global(cx);
  314        if let Some(app_state) = app_state.upgrade() {
  315            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  316                Editor::new_file(workspace, &Default::default(), cx)
  317            })
  318            .detach();
  319        }
  320    });
  321    cx.on_action(move |_: &workspace::NewWindow, cx| {
  322        let app_state = workspace::AppState::global(cx);
  323        if let Some(app_state) = app_state.upgrade() {
  324            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  325                Editor::new_file(workspace, &Default::default(), cx)
  326            })
  327            .detach();
  328        }
  329    });
  330}
  331
  332pub struct SearchWithinRange;
  333
  334trait InvalidationRegion {
  335    fn ranges(&self) -> &[Range<Anchor>];
  336}
  337
  338#[derive(Clone, Debug, PartialEq)]
  339pub enum SelectPhase {
  340    Begin {
  341        position: DisplayPoint,
  342        add: bool,
  343        click_count: usize,
  344    },
  345    BeginColumnar {
  346        position: DisplayPoint,
  347        reset: bool,
  348        goal_column: u32,
  349    },
  350    Extend {
  351        position: DisplayPoint,
  352        click_count: usize,
  353    },
  354    Update {
  355        position: DisplayPoint,
  356        goal_column: u32,
  357        scroll_delta: gpui::Point<f32>,
  358    },
  359    End,
  360}
  361
  362#[derive(Clone, Debug)]
  363pub enum SelectMode {
  364    Character,
  365    Word(Range<Anchor>),
  366    Line(Range<Anchor>),
  367    All,
  368}
  369
  370#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  371pub enum EditorMode {
  372    SingleLine { auto_width: bool },
  373    AutoHeight { max_lines: usize },
  374    Full,
  375}
  376
  377#[derive(Copy, Clone, Debug)]
  378pub enum SoftWrap {
  379    /// Prefer not to wrap at all.
  380    ///
  381    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  382    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  383    GitDiff,
  384    /// Prefer a single line generally, unless an overly long line is encountered.
  385    None,
  386    /// Soft wrap lines that exceed the editor width.
  387    EditorWidth,
  388    /// Soft wrap lines at the preferred line length.
  389    Column(u32),
  390    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  391    Bounded(u32),
  392}
  393
  394#[derive(Clone)]
  395pub struct EditorStyle {
  396    pub background: Hsla,
  397    pub local_player: PlayerColor,
  398    pub text: TextStyle,
  399    pub scrollbar_width: Pixels,
  400    pub syntax: Arc<SyntaxTheme>,
  401    pub status: StatusColors,
  402    pub inlay_hints_style: HighlightStyle,
  403    pub suggestions_style: HighlightStyle,
  404    pub unnecessary_code_fade: f32,
  405}
  406
  407impl Default for EditorStyle {
  408    fn default() -> Self {
  409        Self {
  410            background: Hsla::default(),
  411            local_player: PlayerColor::default(),
  412            text: TextStyle::default(),
  413            scrollbar_width: Pixels::default(),
  414            syntax: Default::default(),
  415            // HACK: Status colors don't have a real default.
  416            // We should look into removing the status colors from the editor
  417            // style and retrieve them directly from the theme.
  418            status: StatusColors::dark(),
  419            inlay_hints_style: HighlightStyle::default(),
  420            suggestions_style: HighlightStyle::default(),
  421            unnecessary_code_fade: Default::default(),
  422        }
  423    }
  424}
  425
  426pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  427    let show_background = language_settings::language_settings(None, None, cx)
  428        .inlay_hints
  429        .show_background;
  430
  431    HighlightStyle {
  432        color: Some(cx.theme().status().hint),
  433        background_color: show_background.then(|| cx.theme().status().hint_background),
  434        ..HighlightStyle::default()
  435    }
  436}
  437
  438type CompletionId = usize;
  439
  440#[derive(Clone, Debug)]
  441struct CompletionState {
  442    // render_inlay_ids represents the inlay hints that are inserted
  443    // for rendering the inline completions. They may be discontinuous
  444    // in the event that the completion provider returns some intersection
  445    // with the existing content.
  446    render_inlay_ids: Vec<InlayId>,
  447    // text is the resulting rope that is inserted when the user accepts a completion.
  448    text: Rope,
  449    // position is the position of the cursor when the completion was triggered.
  450    position: multi_buffer::Anchor,
  451    // delete_range is the range of text that this completion state covers.
  452    // if the completion is accepted, this range should be deleted.
  453    delete_range: Option<Range<multi_buffer::Anchor>>,
  454}
  455
  456#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  457struct EditorActionId(usize);
  458
  459impl EditorActionId {
  460    pub fn post_inc(&mut self) -> Self {
  461        let answer = self.0;
  462
  463        *self = Self(answer + 1);
  464
  465        Self(answer)
  466    }
  467}
  468
  469// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  470// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  471
  472type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  473type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  474
  475#[derive(Default)]
  476struct ScrollbarMarkerState {
  477    scrollbar_size: Size<Pixels>,
  478    dirty: bool,
  479    markers: Arc<[PaintQuad]>,
  480    pending_refresh: Option<Task<Result<()>>>,
  481}
  482
  483impl ScrollbarMarkerState {
  484    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  485        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  486    }
  487}
  488
  489#[derive(Clone, Debug)]
  490struct RunnableTasks {
  491    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  492    offset: MultiBufferOffset,
  493    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  494    column: u32,
  495    // Values of all named captures, including those starting with '_'
  496    extra_variables: HashMap<String, String>,
  497    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  498    context_range: Range<BufferOffset>,
  499}
  500
  501impl RunnableTasks {
  502    fn resolve<'a>(
  503        &'a self,
  504        cx: &'a task::TaskContext,
  505    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  506        self.templates.iter().filter_map(|(kind, template)| {
  507            template
  508                .resolve_task(&kind.to_id_base(), cx)
  509                .map(|task| (kind.clone(), task))
  510        })
  511    }
  512}
  513
  514#[derive(Clone)]
  515struct ResolvedTasks {
  516    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  517    position: Anchor,
  518}
  519#[derive(Copy, Clone, Debug)]
  520struct MultiBufferOffset(usize);
  521#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  522struct BufferOffset(usize);
  523
  524// Addons allow storing per-editor state in other crates (e.g. Vim)
  525pub trait Addon: 'static {
  526    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  527
  528    fn to_any(&self) -> &dyn std::any::Any;
  529}
  530
  531#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  532pub enum IsVimMode {
  533    Yes,
  534    No,
  535}
  536
  537pub trait ActiveLineTrailerProvider {
  538    fn render_active_line_trailer(
  539        &mut self,
  540        style: &EditorStyle,
  541        focus_handle: &FocusHandle,
  542        cx: &mut WindowContext,
  543    ) -> Option<AnyElement>;
  544}
  545
  546/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  547///
  548/// See the [module level documentation](self) for more information.
  549pub struct Editor {
  550    focus_handle: FocusHandle,
  551    last_focused_descendant: Option<WeakFocusHandle>,
  552    /// The text buffer being edited
  553    buffer: Model<MultiBuffer>,
  554    /// Map of how text in the buffer should be displayed.
  555    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  556    pub display_map: Model<DisplayMap>,
  557    pub selections: SelectionsCollection,
  558    pub scroll_manager: ScrollManager,
  559    /// When inline assist editors are linked, they all render cursors because
  560    /// typing enters text into each of them, even the ones that aren't focused.
  561    pub(crate) show_cursor_when_unfocused: bool,
  562    columnar_selection_tail: Option<Anchor>,
  563    add_selections_state: Option<AddSelectionsState>,
  564    select_next_state: Option<SelectNextState>,
  565    select_prev_state: Option<SelectNextState>,
  566    selection_history: SelectionHistory,
  567    autoclose_regions: Vec<AutocloseRegion>,
  568    snippet_stack: InvalidationStack<SnippetState>,
  569    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  570    ime_transaction: Option<TransactionId>,
  571    active_diagnostics: Option<ActiveDiagnosticGroup>,
  572    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  573
  574    project: Option<Model<Project>>,
  575    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  576    completion_provider: Option<Box<dyn CompletionProvider>>,
  577    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  578    blink_manager: Model<BlinkManager>,
  579    show_cursor_names: bool,
  580    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  581    pub show_local_selections: bool,
  582    mode: EditorMode,
  583    show_breadcrumbs: bool,
  584    show_gutter: bool,
  585    show_line_numbers: Option<bool>,
  586    use_relative_line_numbers: Option<bool>,
  587    show_git_diff_gutter: Option<bool>,
  588    show_code_actions: Option<bool>,
  589    show_runnables: Option<bool>,
  590    show_wrap_guides: Option<bool>,
  591    show_indent_guides: Option<bool>,
  592    placeholder_text: Option<Arc<str>>,
  593    highlight_order: usize,
  594    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  595    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  596    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  597    scrollbar_marker_state: ScrollbarMarkerState,
  598    active_indent_guides_state: ActiveIndentGuidesState,
  599    nav_history: Option<ItemNavHistory>,
  600    context_menu: RwLock<Option<ContextMenu>>,
  601    mouse_context_menu: Option<MouseContextMenu>,
  602    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  603    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  604    signature_help_state: SignatureHelpState,
  605    auto_signature_help: Option<bool>,
  606    find_all_references_task_sources: Vec<Anchor>,
  607    next_completion_id: CompletionId,
  608    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  609    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  610    code_actions_task: Option<Task<Result<()>>>,
  611    document_highlights_task: Option<Task<()>>,
  612    linked_editing_range_task: Option<Task<Option<()>>>,
  613    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  614    pending_rename: Option<RenameState>,
  615    searchable: bool,
  616    cursor_shape: CursorShape,
  617    current_line_highlight: Option<CurrentLineHighlight>,
  618    collapse_matches: bool,
  619    autoindent_mode: Option<AutoindentMode>,
  620    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  621    input_enabled: bool,
  622    use_modal_editing: bool,
  623    read_only: bool,
  624    leader_peer_id: Option<PeerId>,
  625    remote_id: Option<ViewId>,
  626    hover_state: HoverState,
  627    gutter_hovered: bool,
  628    hovered_link_state: Option<HoveredLinkState>,
  629    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  630    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  631    active_inline_completion: Option<CompletionState>,
  632    // enable_inline_completions is a switch that Vim can use to disable
  633    // inline completions based on its mode.
  634    enable_inline_completions: bool,
  635    show_inline_completions_override: Option<bool>,
  636    inlay_hint_cache: InlayHintCache,
  637    expanded_hunks: ExpandedHunks,
  638    next_inlay_id: usize,
  639    _subscriptions: Vec<Subscription>,
  640    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  641    gutter_dimensions: GutterDimensions,
  642    style: Option<EditorStyle>,
  643    text_style_refinement: Option<TextStyleRefinement>,
  644    next_editor_action_id: EditorActionId,
  645    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  646    use_autoclose: bool,
  647    use_auto_surround: bool,
  648    auto_replace_emoji_shortcode: bool,
  649    show_git_blame_gutter: bool,
  650    show_git_blame_inline: bool,
  651    show_git_blame_inline_delay_task: Option<Task<()>>,
  652    git_blame_inline_enabled: bool,
  653    serialize_dirty_buffers: bool,
  654    show_selection_menu: Option<bool>,
  655    blame: Option<Model<GitBlame>>,
  656    blame_subscription: Option<Subscription>,
  657    custom_context_menu: Option<
  658        Box<
  659            dyn 'static
  660                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  661        >,
  662    >,
  663    last_bounds: Option<Bounds<Pixels>>,
  664    expect_bounds_change: Option<Bounds<Pixels>>,
  665    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  666    tasks_update_task: Option<Task<()>>,
  667    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  668    breadcrumb_header: Option<String>,
  669    focused_block: Option<FocusedBlock>,
  670    next_scroll_position: NextScrollCursorCenterTopBottom,
  671    addons: HashMap<TypeId, Box<dyn Addon>>,
  672    _scroll_cursor_center_top_bottom_task: Task<()>,
  673    active_line_trailer_provider: Option<Box<dyn ActiveLineTrailerProvider>>,
  674}
  675
  676#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  677enum NextScrollCursorCenterTopBottom {
  678    #[default]
  679    Center,
  680    Top,
  681    Bottom,
  682}
  683
  684impl NextScrollCursorCenterTopBottom {
  685    fn next(&self) -> Self {
  686        match self {
  687            Self::Center => Self::Top,
  688            Self::Top => Self::Bottom,
  689            Self::Bottom => Self::Center,
  690        }
  691    }
  692}
  693
  694#[derive(Clone)]
  695pub struct EditorSnapshot {
  696    pub mode: EditorMode,
  697    show_gutter: bool,
  698    show_line_numbers: Option<bool>,
  699    show_git_diff_gutter: Option<bool>,
  700    show_code_actions: Option<bool>,
  701    show_runnables: Option<bool>,
  702    git_blame_gutter_max_author_length: Option<usize>,
  703    pub display_snapshot: DisplaySnapshot,
  704    pub placeholder_text: Option<Arc<str>>,
  705    is_focused: bool,
  706    scroll_anchor: ScrollAnchor,
  707    ongoing_scroll: OngoingScroll,
  708    current_line_highlight: CurrentLineHighlight,
  709    gutter_hovered: bool,
  710}
  711
  712const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  713
  714#[derive(Default, Debug, Clone, Copy)]
  715pub struct GutterDimensions {
  716    pub left_padding: Pixels,
  717    pub right_padding: Pixels,
  718    pub width: Pixels,
  719    pub margin: Pixels,
  720    pub git_blame_entries_width: Option<Pixels>,
  721}
  722
  723impl GutterDimensions {
  724    /// The full width of the space taken up by the gutter.
  725    pub fn full_width(&self) -> Pixels {
  726        self.margin + self.width
  727    }
  728
  729    /// The width of the space reserved for the fold indicators,
  730    /// use alongside 'justify_end' and `gutter_width` to
  731    /// right align content with the line numbers
  732    pub fn fold_area_width(&self) -> Pixels {
  733        self.margin + self.right_padding
  734    }
  735}
  736
  737#[derive(Debug)]
  738pub struct RemoteSelection {
  739    pub replica_id: ReplicaId,
  740    pub selection: Selection<Anchor>,
  741    pub cursor_shape: CursorShape,
  742    pub peer_id: PeerId,
  743    pub line_mode: bool,
  744    pub participant_index: Option<ParticipantIndex>,
  745    pub user_name: Option<SharedString>,
  746}
  747
  748#[derive(Clone, Debug)]
  749struct SelectionHistoryEntry {
  750    selections: Arc<[Selection<Anchor>]>,
  751    select_next_state: Option<SelectNextState>,
  752    select_prev_state: Option<SelectNextState>,
  753    add_selections_state: Option<AddSelectionsState>,
  754}
  755
  756enum SelectionHistoryMode {
  757    Normal,
  758    Undoing,
  759    Redoing,
  760}
  761
  762#[derive(Clone, PartialEq, Eq, Hash)]
  763struct HoveredCursor {
  764    replica_id: u16,
  765    selection_id: usize,
  766}
  767
  768impl Default for SelectionHistoryMode {
  769    fn default() -> Self {
  770        Self::Normal
  771    }
  772}
  773
  774#[derive(Default)]
  775struct SelectionHistory {
  776    #[allow(clippy::type_complexity)]
  777    selections_by_transaction:
  778        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  779    mode: SelectionHistoryMode,
  780    undo_stack: VecDeque<SelectionHistoryEntry>,
  781    redo_stack: VecDeque<SelectionHistoryEntry>,
  782}
  783
  784impl SelectionHistory {
  785    fn insert_transaction(
  786        &mut self,
  787        transaction_id: TransactionId,
  788        selections: Arc<[Selection<Anchor>]>,
  789    ) {
  790        self.selections_by_transaction
  791            .insert(transaction_id, (selections, None));
  792    }
  793
  794    #[allow(clippy::type_complexity)]
  795    fn transaction(
  796        &self,
  797        transaction_id: TransactionId,
  798    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  799        self.selections_by_transaction.get(&transaction_id)
  800    }
  801
  802    #[allow(clippy::type_complexity)]
  803    fn transaction_mut(
  804        &mut self,
  805        transaction_id: TransactionId,
  806    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  807        self.selections_by_transaction.get_mut(&transaction_id)
  808    }
  809
  810    fn push(&mut self, entry: SelectionHistoryEntry) {
  811        if !entry.selections.is_empty() {
  812            match self.mode {
  813                SelectionHistoryMode::Normal => {
  814                    self.push_undo(entry);
  815                    self.redo_stack.clear();
  816                }
  817                SelectionHistoryMode::Undoing => self.push_redo(entry),
  818                SelectionHistoryMode::Redoing => self.push_undo(entry),
  819            }
  820        }
  821    }
  822
  823    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  824        if self
  825            .undo_stack
  826            .back()
  827            .map_or(true, |e| e.selections != entry.selections)
  828        {
  829            self.undo_stack.push_back(entry);
  830            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  831                self.undo_stack.pop_front();
  832            }
  833        }
  834    }
  835
  836    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  837        if self
  838            .redo_stack
  839            .back()
  840            .map_or(true, |e| e.selections != entry.selections)
  841        {
  842            self.redo_stack.push_back(entry);
  843            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  844                self.redo_stack.pop_front();
  845            }
  846        }
  847    }
  848}
  849
  850struct RowHighlight {
  851    index: usize,
  852    range: Range<Anchor>,
  853    color: Hsla,
  854    should_autoscroll: bool,
  855}
  856
  857#[derive(Clone, Debug)]
  858struct AddSelectionsState {
  859    above: bool,
  860    stack: Vec<usize>,
  861}
  862
  863#[derive(Clone)]
  864struct SelectNextState {
  865    query: AhoCorasick,
  866    wordwise: bool,
  867    done: bool,
  868}
  869
  870impl std::fmt::Debug for SelectNextState {
  871    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  872        f.debug_struct(std::any::type_name::<Self>())
  873            .field("wordwise", &self.wordwise)
  874            .field("done", &self.done)
  875            .finish()
  876    }
  877}
  878
  879#[derive(Debug)]
  880struct AutocloseRegion {
  881    selection_id: usize,
  882    range: Range<Anchor>,
  883    pair: BracketPair,
  884}
  885
  886#[derive(Debug)]
  887struct SnippetState {
  888    ranges: Vec<Vec<Range<Anchor>>>,
  889    active_index: usize,
  890    choices: Vec<Option<Vec<String>>>,
  891}
  892
  893#[doc(hidden)]
  894pub struct RenameState {
  895    pub range: Range<Anchor>,
  896    pub old_name: Arc<str>,
  897    pub editor: View<Editor>,
  898    block_id: CustomBlockId,
  899}
  900
  901struct InvalidationStack<T>(Vec<T>);
  902
  903struct RegisteredInlineCompletionProvider {
  904    provider: Arc<dyn InlineCompletionProviderHandle>,
  905    _subscription: Subscription,
  906}
  907
  908enum ContextMenu {
  909    Completions(CompletionsMenu),
  910    CodeActions(CodeActionsMenu),
  911}
  912
  913impl ContextMenu {
  914    fn select_first(
  915        &mut self,
  916        provider: Option<&dyn CompletionProvider>,
  917        cx: &mut ViewContext<Editor>,
  918    ) -> bool {
  919        if self.visible() {
  920            match self {
  921                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  922                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  923            }
  924            true
  925        } else {
  926            false
  927        }
  928    }
  929
  930    fn select_prev(
  931        &mut self,
  932        provider: Option<&dyn CompletionProvider>,
  933        cx: &mut ViewContext<Editor>,
  934    ) -> bool {
  935        if self.visible() {
  936            match self {
  937                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  938                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  939            }
  940            true
  941        } else {
  942            false
  943        }
  944    }
  945
  946    fn select_next(
  947        &mut self,
  948        provider: Option<&dyn CompletionProvider>,
  949        cx: &mut ViewContext<Editor>,
  950    ) -> bool {
  951        if self.visible() {
  952            match self {
  953                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  954                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  955            }
  956            true
  957        } else {
  958            false
  959        }
  960    }
  961
  962    fn select_last(
  963        &mut self,
  964        provider: Option<&dyn CompletionProvider>,
  965        cx: &mut ViewContext<Editor>,
  966    ) -> bool {
  967        if self.visible() {
  968            match self {
  969                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  970                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  971            }
  972            true
  973        } else {
  974            false
  975        }
  976    }
  977
  978    fn visible(&self) -> bool {
  979        match self {
  980            ContextMenu::Completions(menu) => menu.visible(),
  981            ContextMenu::CodeActions(menu) => menu.visible(),
  982        }
  983    }
  984
  985    fn render(
  986        &self,
  987        cursor_position: DisplayPoint,
  988        style: &EditorStyle,
  989        max_height: Pixels,
  990        workspace: Option<WeakView<Workspace>>,
  991        cx: &mut ViewContext<Editor>,
  992    ) -> (ContextMenuOrigin, AnyElement) {
  993        match self {
  994            ContextMenu::Completions(menu) => (
  995                ContextMenuOrigin::EditorPoint(cursor_position),
  996                menu.render(style, max_height, workspace, cx),
  997            ),
  998            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  999        }
 1000    }
 1001}
 1002
 1003enum ContextMenuOrigin {
 1004    EditorPoint(DisplayPoint),
 1005    GutterIndicator(DisplayRow),
 1006}
 1007
 1008#[derive(Clone, Debug)]
 1009struct CompletionsMenu {
 1010    id: CompletionId,
 1011    sort_completions: bool,
 1012    initial_position: Anchor,
 1013    buffer: Model<Buffer>,
 1014    completions: Arc<RwLock<Box<[Completion]>>>,
 1015    match_candidates: Arc<[StringMatchCandidate]>,
 1016    matches: Arc<[StringMatch]>,
 1017    selected_item: usize,
 1018    scroll_handle: UniformListScrollHandle,
 1019    selected_completion_documentation_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
 1020}
 1021
 1022impl CompletionsMenu {
 1023    fn new(
 1024        id: CompletionId,
 1025        sort_completions: bool,
 1026        initial_position: Anchor,
 1027        buffer: Model<Buffer>,
 1028        completions: Box<[Completion]>,
 1029    ) -> Self {
 1030        let match_candidates = completions
 1031            .iter()
 1032            .enumerate()
 1033            .map(|(id, completion)| {
 1034                StringMatchCandidate::new(
 1035                    id,
 1036                    completion.label.text[completion.label.filter_range.clone()].into(),
 1037                )
 1038            })
 1039            .collect();
 1040
 1041        Self {
 1042            id,
 1043            sort_completions,
 1044            initial_position,
 1045            buffer,
 1046            completions: Arc::new(RwLock::new(completions)),
 1047            match_candidates,
 1048            matches: Vec::new().into(),
 1049            selected_item: 0,
 1050            scroll_handle: UniformListScrollHandle::new(),
 1051            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1052                DebouncedDelay::new(),
 1053            ))),
 1054        }
 1055    }
 1056
 1057    fn new_snippet_choices(
 1058        id: CompletionId,
 1059        sort_completions: bool,
 1060        choices: &Vec<String>,
 1061        selection: Range<Anchor>,
 1062        buffer: Model<Buffer>,
 1063    ) -> Self {
 1064        let completions = choices
 1065            .iter()
 1066            .map(|choice| Completion {
 1067                old_range: selection.start.text_anchor..selection.end.text_anchor,
 1068                new_text: choice.to_string(),
 1069                label: CodeLabel {
 1070                    text: choice.to_string(),
 1071                    runs: Default::default(),
 1072                    filter_range: Default::default(),
 1073                },
 1074                server_id: LanguageServerId(usize::MAX),
 1075                documentation: None,
 1076                lsp_completion: Default::default(),
 1077                confirm: None,
 1078            })
 1079            .collect();
 1080
 1081        let match_candidates = choices
 1082            .iter()
 1083            .enumerate()
 1084            .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
 1085            .collect();
 1086        let matches = choices
 1087            .iter()
 1088            .enumerate()
 1089            .map(|(id, completion)| StringMatch {
 1090                candidate_id: id,
 1091                score: 1.,
 1092                positions: vec![],
 1093                string: completion.clone(),
 1094            })
 1095            .collect();
 1096        Self {
 1097            id,
 1098            sort_completions,
 1099            initial_position: selection.start,
 1100            buffer,
 1101            completions: Arc::new(RwLock::new(completions)),
 1102            match_candidates,
 1103            matches,
 1104            selected_item: 0,
 1105            scroll_handle: UniformListScrollHandle::new(),
 1106            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1107                DebouncedDelay::new(),
 1108            ))),
 1109        }
 1110    }
 1111
 1112    fn suppress_documentation_resolution(mut self) -> Self {
 1113        self.selected_completion_documentation_resolve_debounce
 1114            .take();
 1115        self
 1116    }
 1117
 1118    fn select_first(
 1119        &mut self,
 1120        provider: Option<&dyn CompletionProvider>,
 1121        cx: &mut ViewContext<Editor>,
 1122    ) {
 1123        self.selected_item = 0;
 1124        self.scroll_handle
 1125            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1126        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1127        cx.notify();
 1128    }
 1129
 1130    fn select_prev(
 1131        &mut self,
 1132        provider: Option<&dyn CompletionProvider>,
 1133        cx: &mut ViewContext<Editor>,
 1134    ) {
 1135        if self.selected_item > 0 {
 1136            self.selected_item -= 1;
 1137        } else {
 1138            self.selected_item = self.matches.len() - 1;
 1139        }
 1140        self.scroll_handle
 1141            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1142        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1143        cx.notify();
 1144    }
 1145
 1146    fn select_next(
 1147        &mut self,
 1148        provider: Option<&dyn CompletionProvider>,
 1149        cx: &mut ViewContext<Editor>,
 1150    ) {
 1151        if self.selected_item + 1 < self.matches.len() {
 1152            self.selected_item += 1;
 1153        } else {
 1154            self.selected_item = 0;
 1155        }
 1156        self.scroll_handle
 1157            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1158        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1159        cx.notify();
 1160    }
 1161
 1162    fn select_last(
 1163        &mut self,
 1164        provider: Option<&dyn CompletionProvider>,
 1165        cx: &mut ViewContext<Editor>,
 1166    ) {
 1167        self.selected_item = self.matches.len() - 1;
 1168        self.scroll_handle
 1169            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1170        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1171        cx.notify();
 1172    }
 1173
 1174    fn pre_resolve_completion_documentation(
 1175        buffer: Model<Buffer>,
 1176        completions: Arc<RwLock<Box<[Completion]>>>,
 1177        matches: Arc<[StringMatch]>,
 1178        editor: &Editor,
 1179        cx: &mut ViewContext<Editor>,
 1180    ) -> Task<()> {
 1181        let settings = EditorSettings::get_global(cx);
 1182        if !settings.show_completion_documentation {
 1183            return Task::ready(());
 1184        }
 1185
 1186        let Some(provider) = editor.completion_provider.as_ref() else {
 1187            return Task::ready(());
 1188        };
 1189
 1190        let resolve_task = provider.resolve_completions(
 1191            buffer,
 1192            matches.iter().map(|m| m.candidate_id).collect(),
 1193            completions.clone(),
 1194            cx,
 1195        );
 1196
 1197        cx.spawn(move |this, mut cx| async move {
 1198            if let Some(true) = resolve_task.await.log_err() {
 1199                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1200            }
 1201        })
 1202    }
 1203
 1204    fn attempt_resolve_selected_completion_documentation(
 1205        &mut self,
 1206        provider: Option<&dyn CompletionProvider>,
 1207        cx: &mut ViewContext<Editor>,
 1208    ) {
 1209        let settings = EditorSettings::get_global(cx);
 1210        if !settings.show_completion_documentation {
 1211            return;
 1212        }
 1213
 1214        let completion_index = self.matches[self.selected_item].candidate_id;
 1215        let Some(provider) = provider else {
 1216            return;
 1217        };
 1218        let Some(documentation_resolve) = self
 1219            .selected_completion_documentation_resolve_debounce
 1220            .as_ref()
 1221        else {
 1222            return;
 1223        };
 1224
 1225        let resolve_task = provider.resolve_completions(
 1226            self.buffer.clone(),
 1227            vec![completion_index],
 1228            self.completions.clone(),
 1229            cx,
 1230        );
 1231
 1232        let delay_ms =
 1233            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1234        let delay = Duration::from_millis(delay_ms);
 1235
 1236        documentation_resolve.lock().fire_new(delay, cx, |_, cx| {
 1237            cx.spawn(move |this, mut cx| async move {
 1238                if let Some(true) = resolve_task.await.log_err() {
 1239                    this.update(&mut cx, |_, cx| cx.notify()).ok();
 1240                }
 1241            })
 1242        });
 1243    }
 1244
 1245    fn visible(&self) -> bool {
 1246        !self.matches.is_empty()
 1247    }
 1248
 1249    fn render(
 1250        &self,
 1251        style: &EditorStyle,
 1252        max_height: Pixels,
 1253        workspace: Option<WeakView<Workspace>>,
 1254        cx: &mut ViewContext<Editor>,
 1255    ) -> AnyElement {
 1256        let settings = EditorSettings::get_global(cx);
 1257        let show_completion_documentation = settings.show_completion_documentation;
 1258
 1259        let widest_completion_ix = self
 1260            .matches
 1261            .iter()
 1262            .enumerate()
 1263            .max_by_key(|(_, mat)| {
 1264                let completions = self.completions.read();
 1265                let completion = &completions[mat.candidate_id];
 1266                let documentation = &completion.documentation;
 1267
 1268                let mut len = completion.label.text.chars().count();
 1269                if let Some(Documentation::SingleLine(text)) = documentation {
 1270                    if show_completion_documentation {
 1271                        len += text.chars().count();
 1272                    }
 1273                }
 1274
 1275                len
 1276            })
 1277            .map(|(ix, _)| ix);
 1278
 1279        let completions = self.completions.clone();
 1280        let matches = self.matches.clone();
 1281        let selected_item = self.selected_item;
 1282        let style = style.clone();
 1283
 1284        let multiline_docs = if show_completion_documentation {
 1285            let mat = &self.matches[selected_item];
 1286            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1287                Some(Documentation::MultiLinePlainText(text)) => {
 1288                    Some(div().child(SharedString::from(text.clone())))
 1289                }
 1290                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1291                    Some(div().child(render_parsed_markdown(
 1292                        "completions_markdown",
 1293                        parsed,
 1294                        &style,
 1295                        workspace,
 1296                        cx,
 1297                    )))
 1298                }
 1299                _ => None,
 1300            };
 1301            multiline_docs.map(|div| {
 1302                div.id("multiline_docs")
 1303                    .max_h(max_height)
 1304                    .flex_1()
 1305                    .px_1p5()
 1306                    .py_1()
 1307                    .min_w(px(260.))
 1308                    .max_w(px(640.))
 1309                    .w(px(500.))
 1310                    .overflow_y_scroll()
 1311                    .occlude()
 1312            })
 1313        } else {
 1314            None
 1315        };
 1316
 1317        let list = uniform_list(
 1318            cx.view().clone(),
 1319            "completions",
 1320            matches.len(),
 1321            move |_editor, range, cx| {
 1322                let start_ix = range.start;
 1323                let completions_guard = completions.read();
 1324
 1325                matches[range]
 1326                    .iter()
 1327                    .enumerate()
 1328                    .map(|(ix, mat)| {
 1329                        let item_ix = start_ix + ix;
 1330                        let candidate_id = mat.candidate_id;
 1331                        let completion = &completions_guard[candidate_id];
 1332
 1333                        let documentation = if show_completion_documentation {
 1334                            &completion.documentation
 1335                        } else {
 1336                            &None
 1337                        };
 1338
 1339                        let highlights = gpui::combine_highlights(
 1340                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1341                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1342                                |(range, mut highlight)| {
 1343                                    // Ignore font weight for syntax highlighting, as we'll use it
 1344                                    // for fuzzy matches.
 1345                                    highlight.font_weight = None;
 1346
 1347                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1348                                        highlight.strikethrough = Some(StrikethroughStyle {
 1349                                            thickness: 1.0.into(),
 1350                                            ..Default::default()
 1351                                        });
 1352                                        highlight.color = Some(cx.theme().colors().text_muted);
 1353                                    }
 1354
 1355                                    (range, highlight)
 1356                                },
 1357                            ),
 1358                        );
 1359                        let completion_label = StyledText::new(completion.label.text.clone())
 1360                            .with_highlights(&style.text, highlights);
 1361                        let documentation_label =
 1362                            if let Some(Documentation::SingleLine(text)) = documentation {
 1363                                if text.trim().is_empty() {
 1364                                    None
 1365                                } else {
 1366                                    Some(
 1367                                        Label::new(text.clone())
 1368                                            .ml_4()
 1369                                            .size(LabelSize::Small)
 1370                                            .color(Color::Muted),
 1371                                    )
 1372                                }
 1373                            } else {
 1374                                None
 1375                            };
 1376
 1377                        let color_swatch = completion
 1378                            .color()
 1379                            .map(|color| div().size_4().bg(color).rounded_sm());
 1380
 1381                        div().min_w(px(220.)).max_w(px(540.)).child(
 1382                            ListItem::new(mat.candidate_id)
 1383                                .inset(true)
 1384                                .selected(item_ix == selected_item)
 1385                                .on_click(cx.listener(move |editor, _event, cx| {
 1386                                    cx.stop_propagation();
 1387                                    if let Some(task) = editor.confirm_completion(
 1388                                        &ConfirmCompletion {
 1389                                            item_ix: Some(item_ix),
 1390                                        },
 1391                                        cx,
 1392                                    ) {
 1393                                        task.detach_and_log_err(cx)
 1394                                    }
 1395                                }))
 1396                                .start_slot::<Div>(color_swatch)
 1397                                .child(h_flex().overflow_hidden().child(completion_label))
 1398                                .end_slot::<Label>(documentation_label),
 1399                        )
 1400                    })
 1401                    .collect()
 1402            },
 1403        )
 1404        .occlude()
 1405        .max_h(max_height)
 1406        .track_scroll(self.scroll_handle.clone())
 1407        .with_width_from_item(widest_completion_ix)
 1408        .with_sizing_behavior(ListSizingBehavior::Infer);
 1409
 1410        Popover::new()
 1411            .child(list)
 1412            .when_some(multiline_docs, |popover, multiline_docs| {
 1413                popover.aside(multiline_docs)
 1414            })
 1415            .into_any_element()
 1416    }
 1417
 1418    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1419        let mut matches = if let Some(query) = query {
 1420            fuzzy::match_strings(
 1421                &self.match_candidates,
 1422                query,
 1423                query.chars().any(|c| c.is_uppercase()),
 1424                100,
 1425                &Default::default(),
 1426                executor,
 1427            )
 1428            .await
 1429        } else {
 1430            self.match_candidates
 1431                .iter()
 1432                .enumerate()
 1433                .map(|(candidate_id, candidate)| StringMatch {
 1434                    candidate_id,
 1435                    score: Default::default(),
 1436                    positions: Default::default(),
 1437                    string: candidate.string.clone(),
 1438                })
 1439                .collect()
 1440        };
 1441
 1442        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1443        if let Some(query) = query {
 1444            if let Some(query_start) = query.chars().next() {
 1445                matches.retain(|string_match| {
 1446                    split_words(&string_match.string).any(|word| {
 1447                        // Check that the first codepoint of the word as lowercase matches the first
 1448                        // codepoint of the query as lowercase
 1449                        word.chars()
 1450                            .flat_map(|codepoint| codepoint.to_lowercase())
 1451                            .zip(query_start.to_lowercase())
 1452                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1453                    })
 1454                });
 1455            }
 1456        }
 1457
 1458        let completions = self.completions.read();
 1459        if self.sort_completions {
 1460            matches.sort_unstable_by_key(|mat| {
 1461                // We do want to strike a balance here between what the language server tells us
 1462                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1463                // `Creat` and there is a local variable called `CreateComponent`).
 1464                // So what we do is: we bucket all matches into two buckets
 1465                // - Strong matches
 1466                // - Weak matches
 1467                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1468                // and the Weak matches are the rest.
 1469                //
 1470                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1471                // matches, we prefer language-server sort_text first.
 1472                //
 1473                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1474                // Rest of the matches(weak) can be sorted as language-server expects.
 1475
 1476                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1477                enum MatchScore<'a> {
 1478                    Strong {
 1479                        score: Reverse<OrderedFloat<f64>>,
 1480                        sort_text: Option<&'a str>,
 1481                        sort_key: (usize, &'a str),
 1482                    },
 1483                    Weak {
 1484                        sort_text: Option<&'a str>,
 1485                        score: Reverse<OrderedFloat<f64>>,
 1486                        sort_key: (usize, &'a str),
 1487                    },
 1488                }
 1489
 1490                let completion = &completions[mat.candidate_id];
 1491                let sort_key = completion.sort_key();
 1492                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1493                let score = Reverse(OrderedFloat(mat.score));
 1494
 1495                if mat.score >= 0.2 {
 1496                    MatchScore::Strong {
 1497                        score,
 1498                        sort_text,
 1499                        sort_key,
 1500                    }
 1501                } else {
 1502                    MatchScore::Weak {
 1503                        sort_text,
 1504                        score,
 1505                        sort_key,
 1506                    }
 1507                }
 1508            });
 1509        }
 1510
 1511        for mat in &mut matches {
 1512            let completion = &completions[mat.candidate_id];
 1513            mat.string.clone_from(&completion.label.text);
 1514            for position in &mut mat.positions {
 1515                *position += completion.label.filter_range.start;
 1516            }
 1517        }
 1518        drop(completions);
 1519
 1520        self.matches = matches.into();
 1521        self.selected_item = 0;
 1522    }
 1523}
 1524
 1525#[derive(Clone)]
 1526struct AvailableCodeAction {
 1527    excerpt_id: ExcerptId,
 1528    action: CodeAction,
 1529    provider: Arc<dyn CodeActionProvider>,
 1530}
 1531
 1532#[derive(Clone)]
 1533struct CodeActionContents {
 1534    tasks: Option<Arc<ResolvedTasks>>,
 1535    actions: Option<Arc<[AvailableCodeAction]>>,
 1536}
 1537
 1538impl CodeActionContents {
 1539    fn len(&self) -> usize {
 1540        match (&self.tasks, &self.actions) {
 1541            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1542            (Some(tasks), None) => tasks.templates.len(),
 1543            (None, Some(actions)) => actions.len(),
 1544            (None, None) => 0,
 1545        }
 1546    }
 1547
 1548    fn is_empty(&self) -> bool {
 1549        match (&self.tasks, &self.actions) {
 1550            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1551            (Some(tasks), None) => tasks.templates.is_empty(),
 1552            (None, Some(actions)) => actions.is_empty(),
 1553            (None, None) => true,
 1554        }
 1555    }
 1556
 1557    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1558        self.tasks
 1559            .iter()
 1560            .flat_map(|tasks| {
 1561                tasks
 1562                    .templates
 1563                    .iter()
 1564                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1565            })
 1566            .chain(self.actions.iter().flat_map(|actions| {
 1567                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1568                    excerpt_id: available.excerpt_id,
 1569                    action: available.action.clone(),
 1570                    provider: available.provider.clone(),
 1571                })
 1572            }))
 1573    }
 1574    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1575        match (&self.tasks, &self.actions) {
 1576            (Some(tasks), Some(actions)) => {
 1577                if index < tasks.templates.len() {
 1578                    tasks
 1579                        .templates
 1580                        .get(index)
 1581                        .cloned()
 1582                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1583                } else {
 1584                    actions.get(index - tasks.templates.len()).map(|available| {
 1585                        CodeActionsItem::CodeAction {
 1586                            excerpt_id: available.excerpt_id,
 1587                            action: available.action.clone(),
 1588                            provider: available.provider.clone(),
 1589                        }
 1590                    })
 1591                }
 1592            }
 1593            (Some(tasks), None) => tasks
 1594                .templates
 1595                .get(index)
 1596                .cloned()
 1597                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1598            (None, Some(actions)) => {
 1599                actions
 1600                    .get(index)
 1601                    .map(|available| CodeActionsItem::CodeAction {
 1602                        excerpt_id: available.excerpt_id,
 1603                        action: available.action.clone(),
 1604                        provider: available.provider.clone(),
 1605                    })
 1606            }
 1607            (None, None) => None,
 1608        }
 1609    }
 1610}
 1611
 1612#[allow(clippy::large_enum_variant)]
 1613#[derive(Clone)]
 1614enum CodeActionsItem {
 1615    Task(TaskSourceKind, ResolvedTask),
 1616    CodeAction {
 1617        excerpt_id: ExcerptId,
 1618        action: CodeAction,
 1619        provider: Arc<dyn CodeActionProvider>,
 1620    },
 1621}
 1622
 1623impl CodeActionsItem {
 1624    fn as_task(&self) -> Option<&ResolvedTask> {
 1625        let Self::Task(_, task) = self else {
 1626            return None;
 1627        };
 1628        Some(task)
 1629    }
 1630    fn as_code_action(&self) -> Option<&CodeAction> {
 1631        let Self::CodeAction { action, .. } = self else {
 1632            return None;
 1633        };
 1634        Some(action)
 1635    }
 1636    fn label(&self) -> String {
 1637        match self {
 1638            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1639            Self::Task(_, task) => task.resolved_label.clone(),
 1640        }
 1641    }
 1642}
 1643
 1644struct CodeActionsMenu {
 1645    actions: CodeActionContents,
 1646    buffer: Model<Buffer>,
 1647    selected_item: usize,
 1648    scroll_handle: UniformListScrollHandle,
 1649    deployed_from_indicator: Option<DisplayRow>,
 1650}
 1651
 1652impl CodeActionsMenu {
 1653    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1654        self.selected_item = 0;
 1655        self.scroll_handle
 1656            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1657        cx.notify()
 1658    }
 1659
 1660    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1661        if self.selected_item > 0 {
 1662            self.selected_item -= 1;
 1663        } else {
 1664            self.selected_item = self.actions.len() - 1;
 1665        }
 1666        self.scroll_handle
 1667            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1668        cx.notify();
 1669    }
 1670
 1671    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1672        if self.selected_item + 1 < self.actions.len() {
 1673            self.selected_item += 1;
 1674        } else {
 1675            self.selected_item = 0;
 1676        }
 1677        self.scroll_handle
 1678            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1679        cx.notify();
 1680    }
 1681
 1682    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1683        self.selected_item = self.actions.len() - 1;
 1684        self.scroll_handle
 1685            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1686        cx.notify()
 1687    }
 1688
 1689    fn visible(&self) -> bool {
 1690        !self.actions.is_empty()
 1691    }
 1692
 1693    fn render(
 1694        &self,
 1695        cursor_position: DisplayPoint,
 1696        _style: &EditorStyle,
 1697        max_height: Pixels,
 1698        cx: &mut ViewContext<Editor>,
 1699    ) -> (ContextMenuOrigin, AnyElement) {
 1700        let actions = self.actions.clone();
 1701        let selected_item = self.selected_item;
 1702        let element = uniform_list(
 1703            cx.view().clone(),
 1704            "code_actions_menu",
 1705            self.actions.len(),
 1706            move |_this, range, cx| {
 1707                actions
 1708                    .iter()
 1709                    .skip(range.start)
 1710                    .take(range.end - range.start)
 1711                    .enumerate()
 1712                    .map(|(ix, action)| {
 1713                        let item_ix = range.start + ix;
 1714                        let selected = selected_item == item_ix;
 1715                        let colors = cx.theme().colors();
 1716                        div()
 1717                            .px_1()
 1718                            .rounded_md()
 1719                            .text_color(colors.text)
 1720                            .when(selected, |style| {
 1721                                style
 1722                                    .bg(colors.element_active)
 1723                                    .text_color(colors.text_accent)
 1724                            })
 1725                            .hover(|style| {
 1726                                style
 1727                                    .bg(colors.element_hover)
 1728                                    .text_color(colors.text_accent)
 1729                            })
 1730                            .whitespace_nowrap()
 1731                            .when_some(action.as_code_action(), |this, action| {
 1732                                this.on_mouse_down(
 1733                                    MouseButton::Left,
 1734                                    cx.listener(move |editor, _, cx| {
 1735                                        cx.stop_propagation();
 1736                                        if let Some(task) = editor.confirm_code_action(
 1737                                            &ConfirmCodeAction {
 1738                                                item_ix: Some(item_ix),
 1739                                            },
 1740                                            cx,
 1741                                        ) {
 1742                                            task.detach_and_log_err(cx)
 1743                                        }
 1744                                    }),
 1745                                )
 1746                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1747                                .child(SharedString::from(action.lsp_action.title.clone()))
 1748                            })
 1749                            .when_some(action.as_task(), |this, task| {
 1750                                this.on_mouse_down(
 1751                                    MouseButton::Left,
 1752                                    cx.listener(move |editor, _, cx| {
 1753                                        cx.stop_propagation();
 1754                                        if let Some(task) = editor.confirm_code_action(
 1755                                            &ConfirmCodeAction {
 1756                                                item_ix: Some(item_ix),
 1757                                            },
 1758                                            cx,
 1759                                        ) {
 1760                                            task.detach_and_log_err(cx)
 1761                                        }
 1762                                    }),
 1763                                )
 1764                                .child(SharedString::from(task.resolved_label.clone()))
 1765                            })
 1766                    })
 1767                    .collect()
 1768            },
 1769        )
 1770        .elevation_1(cx)
 1771        .p_1()
 1772        .max_h(max_height)
 1773        .occlude()
 1774        .track_scroll(self.scroll_handle.clone())
 1775        .with_width_from_item(
 1776            self.actions
 1777                .iter()
 1778                .enumerate()
 1779                .max_by_key(|(_, action)| match action {
 1780                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1781                    CodeActionsItem::CodeAction { action, .. } => {
 1782                        action.lsp_action.title.chars().count()
 1783                    }
 1784                })
 1785                .map(|(ix, _)| ix),
 1786        )
 1787        .with_sizing_behavior(ListSizingBehavior::Infer)
 1788        .into_any_element();
 1789
 1790        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1791            ContextMenuOrigin::GutterIndicator(row)
 1792        } else {
 1793            ContextMenuOrigin::EditorPoint(cursor_position)
 1794        };
 1795
 1796        (cursor_position, element)
 1797    }
 1798}
 1799
 1800#[derive(Debug)]
 1801struct ActiveDiagnosticGroup {
 1802    primary_range: Range<Anchor>,
 1803    primary_message: String,
 1804    group_id: usize,
 1805    blocks: HashMap<CustomBlockId, Diagnostic>,
 1806    is_valid: bool,
 1807}
 1808
 1809#[derive(Serialize, Deserialize, Clone, Debug)]
 1810pub struct ClipboardSelection {
 1811    pub len: usize,
 1812    pub is_entire_line: bool,
 1813    pub first_line_indent: u32,
 1814}
 1815
 1816#[derive(Debug)]
 1817pub(crate) struct NavigationData {
 1818    cursor_anchor: Anchor,
 1819    cursor_position: Point,
 1820    scroll_anchor: ScrollAnchor,
 1821    scroll_top_row: u32,
 1822}
 1823
 1824#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1825pub enum GotoDefinitionKind {
 1826    Symbol,
 1827    Declaration,
 1828    Type,
 1829    Implementation,
 1830}
 1831
 1832#[derive(Debug, Clone)]
 1833enum InlayHintRefreshReason {
 1834    Toggle(bool),
 1835    SettingsChange(InlayHintSettings),
 1836    NewLinesShown,
 1837    BufferEdited(HashSet<Arc<Language>>),
 1838    RefreshRequested,
 1839    ExcerptsRemoved(Vec<ExcerptId>),
 1840}
 1841
 1842impl InlayHintRefreshReason {
 1843    fn description(&self) -> &'static str {
 1844        match self {
 1845            Self::Toggle(_) => "toggle",
 1846            Self::SettingsChange(_) => "settings change",
 1847            Self::NewLinesShown => "new lines shown",
 1848            Self::BufferEdited(_) => "buffer edited",
 1849            Self::RefreshRequested => "refresh requested",
 1850            Self::ExcerptsRemoved(_) => "excerpts removed",
 1851        }
 1852    }
 1853}
 1854
 1855pub(crate) struct FocusedBlock {
 1856    id: BlockId,
 1857    focus_handle: WeakFocusHandle,
 1858}
 1859
 1860#[derive(Clone)]
 1861struct JumpData {
 1862    excerpt_id: ExcerptId,
 1863    position: Point,
 1864    anchor: text::Anchor,
 1865    path: Option<project::ProjectPath>,
 1866    line_offset_from_top: u32,
 1867}
 1868
 1869impl Editor {
 1870    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1871        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1872        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1873        Self::new(
 1874            EditorMode::SingleLine { auto_width: false },
 1875            buffer,
 1876            None,
 1877            false,
 1878            cx,
 1879        )
 1880    }
 1881
 1882    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1883        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1884        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1885        Self::new(EditorMode::Full, buffer, None, false, cx)
 1886    }
 1887
 1888    pub fn auto_width(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(
 1892            EditorMode::SingleLine { auto_width: true },
 1893            buffer,
 1894            None,
 1895            false,
 1896            cx,
 1897        )
 1898    }
 1899
 1900    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1901        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1902        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1903        Self::new(
 1904            EditorMode::AutoHeight { max_lines },
 1905            buffer,
 1906            None,
 1907            false,
 1908            cx,
 1909        )
 1910    }
 1911
 1912    pub fn for_buffer(
 1913        buffer: Model<Buffer>,
 1914        project: Option<Model<Project>>,
 1915        cx: &mut ViewContext<Self>,
 1916    ) -> Self {
 1917        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1918        Self::new(EditorMode::Full, buffer, project, false, cx)
 1919    }
 1920
 1921    pub fn for_multibuffer(
 1922        buffer: Model<MultiBuffer>,
 1923        project: Option<Model<Project>>,
 1924        show_excerpt_controls: bool,
 1925        cx: &mut ViewContext<Self>,
 1926    ) -> Self {
 1927        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1928    }
 1929
 1930    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1931        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1932        let mut clone = Self::new(
 1933            self.mode,
 1934            self.buffer.clone(),
 1935            self.project.clone(),
 1936            show_excerpt_controls,
 1937            cx,
 1938        );
 1939        self.display_map.update(cx, |display_map, cx| {
 1940            let snapshot = display_map.snapshot(cx);
 1941            clone.display_map.update(cx, |display_map, cx| {
 1942                display_map.set_state(&snapshot, cx);
 1943            });
 1944        });
 1945        clone.selections.clone_state(&self.selections);
 1946        clone.scroll_manager.clone_state(&self.scroll_manager);
 1947        clone.searchable = self.searchable;
 1948        clone
 1949    }
 1950
 1951    pub fn new(
 1952        mode: EditorMode,
 1953        buffer: Model<MultiBuffer>,
 1954        project: Option<Model<Project>>,
 1955        show_excerpt_controls: bool,
 1956        cx: &mut ViewContext<Self>,
 1957    ) -> Self {
 1958        let style = cx.text_style();
 1959        let font_size = style.font_size.to_pixels(cx.rem_size());
 1960        let editor = cx.view().downgrade();
 1961        let fold_placeholder = FoldPlaceholder {
 1962            constrain_width: true,
 1963            render: Arc::new(move |fold_id, fold_range, cx| {
 1964                let editor = editor.clone();
 1965                div()
 1966                    .id(fold_id)
 1967                    .bg(cx.theme().colors().ghost_element_background)
 1968                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1969                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1970                    .rounded_sm()
 1971                    .size_full()
 1972                    .cursor_pointer()
 1973                    .child("")
 1974                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1975                    .on_click(move |_, cx| {
 1976                        editor
 1977                            .update(cx, |editor, cx| {
 1978                                editor.unfold_ranges(
 1979                                    &[fold_range.start..fold_range.end],
 1980                                    true,
 1981                                    false,
 1982                                    cx,
 1983                                );
 1984                                cx.stop_propagation();
 1985                            })
 1986                            .ok();
 1987                    })
 1988                    .into_any()
 1989            }),
 1990            merge_adjacent: true,
 1991            ..Default::default()
 1992        };
 1993        let display_map = cx.new_model(|cx| {
 1994            DisplayMap::new(
 1995                buffer.clone(),
 1996                style.font(),
 1997                font_size,
 1998                None,
 1999                show_excerpt_controls,
 2000                FILE_HEADER_HEIGHT,
 2001                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 2002                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 2003                fold_placeholder,
 2004                cx,
 2005            )
 2006        });
 2007
 2008        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 2009
 2010        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 2011
 2012        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 2013            .then(|| language_settings::SoftWrap::None);
 2014
 2015        let mut project_subscriptions = Vec::new();
 2016        if mode == EditorMode::Full {
 2017            if let Some(project) = project.as_ref() {
 2018                if buffer.read(cx).is_singleton() {
 2019                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 2020                        cx.emit(EditorEvent::TitleChanged);
 2021                    }));
 2022                }
 2023                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 2024                    if let project::Event::RefreshInlayHints = event {
 2025                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 2026                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 2027                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 2028                            let focus_handle = editor.focus_handle(cx);
 2029                            if focus_handle.is_focused(cx) {
 2030                                let snapshot = buffer.read(cx).snapshot();
 2031                                for (range, snippet) in snippet_edits {
 2032                                    let editor_range =
 2033                                        language::range_from_lsp(*range).to_offset(&snapshot);
 2034                                    editor
 2035                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 2036                                        .ok();
 2037                                }
 2038                            }
 2039                        }
 2040                    }
 2041                }));
 2042                if let Some(task_inventory) = project
 2043                    .read(cx)
 2044                    .task_store()
 2045                    .read(cx)
 2046                    .task_inventory()
 2047                    .cloned()
 2048                {
 2049                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 2050                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 2051                    }));
 2052                }
 2053            }
 2054        }
 2055
 2056        let inlay_hint_settings = inlay_hint_settings(
 2057            selections.newest_anchor().head(),
 2058            &buffer.read(cx).snapshot(cx),
 2059            cx,
 2060        );
 2061        let focus_handle = cx.focus_handle();
 2062        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 2063        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 2064            .detach();
 2065        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 2066            .detach();
 2067        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 2068
 2069        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 2070            Some(false)
 2071        } else {
 2072            None
 2073        };
 2074
 2075        let mut code_action_providers = Vec::new();
 2076        if let Some(project) = project.clone() {
 2077            code_action_providers.push(Arc::new(project) as Arc<_>);
 2078        }
 2079
 2080        let mut this = Self {
 2081            focus_handle,
 2082            show_cursor_when_unfocused: false,
 2083            last_focused_descendant: None,
 2084            buffer: buffer.clone(),
 2085            display_map: display_map.clone(),
 2086            selections,
 2087            scroll_manager: ScrollManager::new(cx),
 2088            columnar_selection_tail: None,
 2089            add_selections_state: None,
 2090            select_next_state: None,
 2091            select_prev_state: None,
 2092            selection_history: Default::default(),
 2093            autoclose_regions: Default::default(),
 2094            snippet_stack: Default::default(),
 2095            select_larger_syntax_node_stack: Vec::new(),
 2096            ime_transaction: Default::default(),
 2097            active_diagnostics: None,
 2098            soft_wrap_mode_override,
 2099            completion_provider: project.clone().map(|project| Box::new(project) as _),
 2100            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 2101            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 2102            project,
 2103            blink_manager: blink_manager.clone(),
 2104            show_local_selections: true,
 2105            mode,
 2106            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2107            show_gutter: mode == EditorMode::Full,
 2108            show_line_numbers: None,
 2109            use_relative_line_numbers: None,
 2110            show_git_diff_gutter: None,
 2111            show_code_actions: None,
 2112            show_runnables: None,
 2113            show_wrap_guides: None,
 2114            show_indent_guides,
 2115            placeholder_text: None,
 2116            highlight_order: 0,
 2117            highlighted_rows: HashMap::default(),
 2118            background_highlights: Default::default(),
 2119            gutter_highlights: TreeMap::default(),
 2120            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2121            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2122            nav_history: None,
 2123            context_menu: RwLock::new(None),
 2124            mouse_context_menu: None,
 2125            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2126            completion_tasks: Default::default(),
 2127            signature_help_state: SignatureHelpState::default(),
 2128            auto_signature_help: None,
 2129            find_all_references_task_sources: Vec::new(),
 2130            next_completion_id: 0,
 2131            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2132            next_inlay_id: 0,
 2133            code_action_providers,
 2134            available_code_actions: Default::default(),
 2135            code_actions_task: Default::default(),
 2136            document_highlights_task: Default::default(),
 2137            linked_editing_range_task: Default::default(),
 2138            pending_rename: Default::default(),
 2139            searchable: true,
 2140            cursor_shape: EditorSettings::get_global(cx)
 2141                .cursor_shape
 2142                .unwrap_or_default(),
 2143            current_line_highlight: None,
 2144            autoindent_mode: Some(AutoindentMode::EachLine),
 2145            collapse_matches: false,
 2146            workspace: None,
 2147            input_enabled: true,
 2148            use_modal_editing: mode == EditorMode::Full,
 2149            read_only: false,
 2150            use_autoclose: true,
 2151            use_auto_surround: true,
 2152            auto_replace_emoji_shortcode: false,
 2153            leader_peer_id: None,
 2154            remote_id: None,
 2155            hover_state: Default::default(),
 2156            hovered_link_state: Default::default(),
 2157            inline_completion_provider: None,
 2158            active_inline_completion: None,
 2159            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2160            expanded_hunks: ExpandedHunks::default(),
 2161            gutter_hovered: false,
 2162            pixel_position_of_newest_cursor: None,
 2163            last_bounds: None,
 2164            expect_bounds_change: None,
 2165            gutter_dimensions: GutterDimensions::default(),
 2166            style: None,
 2167            show_cursor_names: false,
 2168            hovered_cursors: Default::default(),
 2169            next_editor_action_id: EditorActionId::default(),
 2170            editor_actions: Rc::default(),
 2171            show_inline_completions_override: None,
 2172            enable_inline_completions: true,
 2173            custom_context_menu: None,
 2174            show_git_blame_gutter: false,
 2175            show_git_blame_inline: false,
 2176            show_selection_menu: None,
 2177            show_git_blame_inline_delay_task: None,
 2178            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2179            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2180                .session
 2181                .restore_unsaved_buffers,
 2182            blame: None,
 2183            blame_subscription: None,
 2184            tasks: Default::default(),
 2185            _subscriptions: vec![
 2186                cx.observe(&buffer, Self::on_buffer_changed),
 2187                cx.subscribe(&buffer, Self::on_buffer_event),
 2188                cx.observe(&display_map, Self::on_display_map_changed),
 2189                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2190                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2191                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2192                cx.observe_window_activation(|editor, cx| {
 2193                    let active = cx.is_window_active();
 2194                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2195                        if active {
 2196                            blink_manager.enable(cx);
 2197                        } else {
 2198                            blink_manager.disable(cx);
 2199                        }
 2200                    });
 2201                }),
 2202            ],
 2203            tasks_update_task: None,
 2204            linked_edit_ranges: Default::default(),
 2205            previous_search_ranges: None,
 2206            breadcrumb_header: None,
 2207            focused_block: None,
 2208            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2209            addons: HashMap::default(),
 2210            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2211            text_style_refinement: None,
 2212            active_line_trailer_provider: None,
 2213        };
 2214        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2215        this._subscriptions.extend(project_subscriptions);
 2216
 2217        this.end_selection(cx);
 2218        this.scroll_manager.show_scrollbar(cx);
 2219
 2220        if mode == EditorMode::Full {
 2221            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2222            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2223
 2224            if this.git_blame_inline_enabled {
 2225                this.git_blame_inline_enabled = true;
 2226                this.start_git_blame_inline(false, cx);
 2227            }
 2228        }
 2229
 2230        this.report_editor_event("open", None, cx);
 2231        this
 2232    }
 2233
 2234    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2235        self.mouse_context_menu
 2236            .as_ref()
 2237            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2238    }
 2239
 2240    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2241        let mut key_context = KeyContext::new_with_defaults();
 2242        key_context.add("Editor");
 2243        let mode = match self.mode {
 2244            EditorMode::SingleLine { .. } => "single_line",
 2245            EditorMode::AutoHeight { .. } => "auto_height",
 2246            EditorMode::Full => "full",
 2247        };
 2248
 2249        if EditorSettings::jupyter_enabled(cx) {
 2250            key_context.add("jupyter");
 2251        }
 2252
 2253        key_context.set("mode", mode);
 2254        if self.pending_rename.is_some() {
 2255            key_context.add("renaming");
 2256        }
 2257        if self.context_menu_visible() {
 2258            match self.context_menu.read().as_ref() {
 2259                Some(ContextMenu::Completions(_)) => {
 2260                    key_context.add("menu");
 2261                    key_context.add("showing_completions")
 2262                }
 2263                Some(ContextMenu::CodeActions(_)) => {
 2264                    key_context.add("menu");
 2265                    key_context.add("showing_code_actions")
 2266                }
 2267                None => {}
 2268            }
 2269        }
 2270
 2271        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2272        if !self.focus_handle(cx).contains_focused(cx)
 2273            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2274        {
 2275            for addon in self.addons.values() {
 2276                addon.extend_key_context(&mut key_context, cx)
 2277            }
 2278        }
 2279
 2280        if let Some(extension) = self
 2281            .buffer
 2282            .read(cx)
 2283            .as_singleton()
 2284            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2285        {
 2286            key_context.set("extension", extension.to_string());
 2287        }
 2288
 2289        if self.has_active_inline_completion(cx) {
 2290            key_context.add("copilot_suggestion");
 2291            key_context.add("inline_completion");
 2292        }
 2293
 2294        key_context
 2295    }
 2296
 2297    pub fn new_file(
 2298        workspace: &mut Workspace,
 2299        _: &workspace::NewFile,
 2300        cx: &mut ViewContext<Workspace>,
 2301    ) {
 2302        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2303            "Failed to create buffer",
 2304            cx,
 2305            |e, _| match e.error_code() {
 2306                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2307                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2308                e.error_tag("required").unwrap_or("the latest version")
 2309            )),
 2310                _ => None,
 2311            },
 2312        );
 2313    }
 2314
 2315    pub fn new_in_workspace(
 2316        workspace: &mut Workspace,
 2317        cx: &mut ViewContext<Workspace>,
 2318    ) -> Task<Result<View<Editor>>> {
 2319        let project = workspace.project().clone();
 2320        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2321
 2322        cx.spawn(|workspace, mut cx| async move {
 2323            let buffer = create.await?;
 2324            workspace.update(&mut cx, |workspace, cx| {
 2325                let editor =
 2326                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2327                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2328                editor
 2329            })
 2330        })
 2331    }
 2332
 2333    fn new_file_vertical(
 2334        workspace: &mut Workspace,
 2335        _: &workspace::NewFileSplitVertical,
 2336        cx: &mut ViewContext<Workspace>,
 2337    ) {
 2338        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2339    }
 2340
 2341    fn new_file_horizontal(
 2342        workspace: &mut Workspace,
 2343        _: &workspace::NewFileSplitHorizontal,
 2344        cx: &mut ViewContext<Workspace>,
 2345    ) {
 2346        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2347    }
 2348
 2349    fn new_file_in_direction(
 2350        workspace: &mut Workspace,
 2351        direction: SplitDirection,
 2352        cx: &mut ViewContext<Workspace>,
 2353    ) {
 2354        let project = workspace.project().clone();
 2355        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2356
 2357        cx.spawn(|workspace, mut cx| async move {
 2358            let buffer = create.await?;
 2359            workspace.update(&mut cx, move |workspace, cx| {
 2360                workspace.split_item(
 2361                    direction,
 2362                    Box::new(
 2363                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2364                    ),
 2365                    cx,
 2366                )
 2367            })?;
 2368            anyhow::Ok(())
 2369        })
 2370        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2371            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2372                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2373                e.error_tag("required").unwrap_or("the latest version")
 2374            )),
 2375            _ => None,
 2376        });
 2377    }
 2378
 2379    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2380        self.leader_peer_id
 2381    }
 2382
 2383    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2384        &self.buffer
 2385    }
 2386
 2387    pub fn workspace(&self) -> Option<View<Workspace>> {
 2388        self.workspace.as_ref()?.0.upgrade()
 2389    }
 2390
 2391    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2392        self.buffer().read(cx).title(cx)
 2393    }
 2394
 2395    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2396        let git_blame_gutter_max_author_length = self
 2397            .render_git_blame_gutter(cx)
 2398            .then(|| {
 2399                if let Some(blame) = self.blame.as_ref() {
 2400                    let max_author_length =
 2401                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2402                    Some(max_author_length)
 2403                } else {
 2404                    None
 2405                }
 2406            })
 2407            .flatten();
 2408
 2409        EditorSnapshot {
 2410            mode: self.mode,
 2411            show_gutter: self.show_gutter,
 2412            show_line_numbers: self.show_line_numbers,
 2413            show_git_diff_gutter: self.show_git_diff_gutter,
 2414            show_code_actions: self.show_code_actions,
 2415            show_runnables: self.show_runnables,
 2416            git_blame_gutter_max_author_length,
 2417            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2418            scroll_anchor: self.scroll_manager.anchor(),
 2419            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2420            placeholder_text: self.placeholder_text.clone(),
 2421            is_focused: self.focus_handle.is_focused(cx),
 2422            current_line_highlight: self
 2423                .current_line_highlight
 2424                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2425            gutter_hovered: self.gutter_hovered,
 2426        }
 2427    }
 2428
 2429    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2430        self.buffer.read(cx).language_at(point, cx)
 2431    }
 2432
 2433    pub fn file_at<T: ToOffset>(
 2434        &self,
 2435        point: T,
 2436        cx: &AppContext,
 2437    ) -> Option<Arc<dyn language::File>> {
 2438        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2439    }
 2440
 2441    pub fn active_excerpt(
 2442        &self,
 2443        cx: &AppContext,
 2444    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2445        self.buffer
 2446            .read(cx)
 2447            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2448    }
 2449
 2450    pub fn mode(&self) -> EditorMode {
 2451        self.mode
 2452    }
 2453
 2454    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2455        self.collaboration_hub.as_deref()
 2456    }
 2457
 2458    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2459        self.collaboration_hub = Some(hub);
 2460    }
 2461
 2462    pub fn set_custom_context_menu(
 2463        &mut self,
 2464        f: impl 'static
 2465            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2466    ) {
 2467        self.custom_context_menu = Some(Box::new(f))
 2468    }
 2469
 2470    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2471        self.completion_provider = provider;
 2472    }
 2473
 2474    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2475        self.semantics_provider.clone()
 2476    }
 2477
 2478    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2479        self.semantics_provider = provider;
 2480    }
 2481
 2482    pub fn set_inline_completion_provider<T>(
 2483        &mut self,
 2484        provider: Option<Model<T>>,
 2485        cx: &mut ViewContext<Self>,
 2486    ) where
 2487        T: InlineCompletionProvider,
 2488    {
 2489        self.inline_completion_provider =
 2490            provider.map(|provider| RegisteredInlineCompletionProvider {
 2491                _subscription: cx.observe(&provider, |this, _, cx| {
 2492                    if this.focus_handle.is_focused(cx) {
 2493                        this.update_visible_inline_completion(cx);
 2494                    }
 2495                }),
 2496                provider: Arc::new(provider),
 2497            });
 2498        self.refresh_inline_completion(false, false, cx);
 2499    }
 2500
 2501    pub fn set_active_line_trailer_provider<T>(
 2502        &mut self,
 2503        provider: Option<T>,
 2504        _cx: &mut ViewContext<Self>,
 2505    ) where
 2506        T: ActiveLineTrailerProvider + 'static,
 2507    {
 2508        self.active_line_trailer_provider = provider.map(|provider| Box::new(provider) as Box<_>);
 2509    }
 2510
 2511    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2512        self.placeholder_text.as_deref()
 2513    }
 2514
 2515    pub fn set_placeholder_text(
 2516        &mut self,
 2517        placeholder_text: impl Into<Arc<str>>,
 2518        cx: &mut ViewContext<Self>,
 2519    ) {
 2520        let placeholder_text = Some(placeholder_text.into());
 2521        if self.placeholder_text != placeholder_text {
 2522            self.placeholder_text = placeholder_text;
 2523            cx.notify();
 2524        }
 2525    }
 2526
 2527    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2528        self.cursor_shape = cursor_shape;
 2529
 2530        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2531        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2532
 2533        cx.notify();
 2534    }
 2535
 2536    pub fn set_current_line_highlight(
 2537        &mut self,
 2538        current_line_highlight: Option<CurrentLineHighlight>,
 2539    ) {
 2540        self.current_line_highlight = current_line_highlight;
 2541    }
 2542
 2543    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2544        self.collapse_matches = collapse_matches;
 2545    }
 2546
 2547    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2548        if self.collapse_matches {
 2549            return range.start..range.start;
 2550        }
 2551        range.clone()
 2552    }
 2553
 2554    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2555        if self.display_map.read(cx).clip_at_line_ends != clip {
 2556            self.display_map
 2557                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2558        }
 2559    }
 2560
 2561    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2562        self.input_enabled = input_enabled;
 2563    }
 2564
 2565    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2566        self.enable_inline_completions = enabled;
 2567    }
 2568
 2569    pub fn set_autoindent(&mut self, autoindent: bool) {
 2570        if autoindent {
 2571            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2572        } else {
 2573            self.autoindent_mode = None;
 2574        }
 2575    }
 2576
 2577    pub fn read_only(&self, cx: &AppContext) -> bool {
 2578        self.read_only || self.buffer.read(cx).read_only()
 2579    }
 2580
 2581    pub fn set_read_only(&mut self, read_only: bool) {
 2582        self.read_only = read_only;
 2583    }
 2584
 2585    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2586        self.use_autoclose = autoclose;
 2587    }
 2588
 2589    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2590        self.use_auto_surround = auto_surround;
 2591    }
 2592
 2593    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2594        self.auto_replace_emoji_shortcode = auto_replace;
 2595    }
 2596
 2597    pub fn toggle_inline_completions(
 2598        &mut self,
 2599        _: &ToggleInlineCompletions,
 2600        cx: &mut ViewContext<Self>,
 2601    ) {
 2602        if self.show_inline_completions_override.is_some() {
 2603            self.set_show_inline_completions(None, cx);
 2604        } else {
 2605            let cursor = self.selections.newest_anchor().head();
 2606            if let Some((buffer, cursor_buffer_position)) =
 2607                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2608            {
 2609                let show_inline_completions =
 2610                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2611                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2612            }
 2613        }
 2614    }
 2615
 2616    pub fn set_show_inline_completions(
 2617        &mut self,
 2618        show_inline_completions: Option<bool>,
 2619        cx: &mut ViewContext<Self>,
 2620    ) {
 2621        self.show_inline_completions_override = show_inline_completions;
 2622        self.refresh_inline_completion(false, true, cx);
 2623    }
 2624
 2625    fn should_show_inline_completions(
 2626        &self,
 2627        buffer: &Model<Buffer>,
 2628        buffer_position: language::Anchor,
 2629        cx: &AppContext,
 2630    ) -> bool {
 2631        if !self.snippet_stack.is_empty() {
 2632            return false;
 2633        }
 2634
 2635        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2636            return false;
 2637        }
 2638
 2639        if let Some(provider) = self.inline_completion_provider() {
 2640            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2641                show_inline_completions
 2642            } else {
 2643                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2644            }
 2645        } else {
 2646            false
 2647        }
 2648    }
 2649
 2650    fn inline_completions_disabled_in_scope(
 2651        &self,
 2652        buffer: &Model<Buffer>,
 2653        buffer_position: language::Anchor,
 2654        cx: &AppContext,
 2655    ) -> bool {
 2656        let snapshot = buffer.read(cx).snapshot();
 2657        let settings = snapshot.settings_at(buffer_position, cx);
 2658
 2659        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2660            return false;
 2661        };
 2662
 2663        scope.override_name().map_or(false, |scope_name| {
 2664            settings
 2665                .inline_completions_disabled_in
 2666                .iter()
 2667                .any(|s| s == scope_name)
 2668        })
 2669    }
 2670
 2671    pub fn set_use_modal_editing(&mut self, to: bool) {
 2672        self.use_modal_editing = to;
 2673    }
 2674
 2675    pub fn use_modal_editing(&self) -> bool {
 2676        self.use_modal_editing
 2677    }
 2678
 2679    fn selections_did_change(
 2680        &mut self,
 2681        local: bool,
 2682        old_cursor_position: &Anchor,
 2683        show_completions: bool,
 2684        cx: &mut ViewContext<Self>,
 2685    ) {
 2686        cx.invalidate_character_coordinates();
 2687
 2688        // Copy selections to primary selection buffer
 2689        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2690        if local {
 2691            let selections = self.selections.all::<usize>(cx);
 2692            let buffer_handle = self.buffer.read(cx).read(cx);
 2693
 2694            let mut text = String::new();
 2695            for (index, selection) in selections.iter().enumerate() {
 2696                let text_for_selection = buffer_handle
 2697                    .text_for_range(selection.start..selection.end)
 2698                    .collect::<String>();
 2699
 2700                text.push_str(&text_for_selection);
 2701                if index != selections.len() - 1 {
 2702                    text.push('\n');
 2703                }
 2704            }
 2705
 2706            if !text.is_empty() {
 2707                cx.write_to_primary(ClipboardItem::new_string(text));
 2708            }
 2709        }
 2710
 2711        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2712            self.buffer.update(cx, |buffer, cx| {
 2713                buffer.set_active_selections(
 2714                    &self.selections.disjoint_anchors(),
 2715                    self.selections.line_mode,
 2716                    self.cursor_shape,
 2717                    cx,
 2718                )
 2719            });
 2720        }
 2721        let display_map = self
 2722            .display_map
 2723            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2724        let buffer = &display_map.buffer_snapshot;
 2725        self.add_selections_state = None;
 2726        self.select_next_state = None;
 2727        self.select_prev_state = None;
 2728        self.select_larger_syntax_node_stack.clear();
 2729        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2730        self.snippet_stack
 2731            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2732        self.take_rename(false, cx);
 2733
 2734        let new_cursor_position = self.selections.newest_anchor().head();
 2735
 2736        self.push_to_nav_history(
 2737            *old_cursor_position,
 2738            Some(new_cursor_position.to_point(buffer)),
 2739            cx,
 2740        );
 2741
 2742        if local {
 2743            let new_cursor_position = self.selections.newest_anchor().head();
 2744            let mut context_menu = self.context_menu.write();
 2745            let completion_menu = match context_menu.as_ref() {
 2746                Some(ContextMenu::Completions(menu)) => Some(menu),
 2747
 2748                _ => {
 2749                    *context_menu = None;
 2750                    None
 2751                }
 2752            };
 2753
 2754            if let Some(completion_menu) = completion_menu {
 2755                let cursor_position = new_cursor_position.to_offset(buffer);
 2756                let (word_range, kind) =
 2757                    buffer.surrounding_word(completion_menu.initial_position, true);
 2758                if kind == Some(CharKind::Word)
 2759                    && word_range.to_inclusive().contains(&cursor_position)
 2760                {
 2761                    let mut completion_menu = completion_menu.clone();
 2762                    drop(context_menu);
 2763
 2764                    let query = Self::completion_query(buffer, cursor_position);
 2765                    cx.spawn(move |this, mut cx| async move {
 2766                        completion_menu
 2767                            .filter(query.as_deref(), cx.background_executor().clone())
 2768                            .await;
 2769
 2770                        this.update(&mut cx, |this, cx| {
 2771                            let mut context_menu = this.context_menu.write();
 2772                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2773                                return;
 2774                            };
 2775
 2776                            if menu.id > completion_menu.id {
 2777                                return;
 2778                            }
 2779
 2780                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2781                            drop(context_menu);
 2782                            cx.notify();
 2783                        })
 2784                    })
 2785                    .detach();
 2786
 2787                    if show_completions {
 2788                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2789                    }
 2790                } else {
 2791                    drop(context_menu);
 2792                    self.hide_context_menu(cx);
 2793                }
 2794            } else {
 2795                drop(context_menu);
 2796            }
 2797
 2798            hide_hover(self, cx);
 2799
 2800            if old_cursor_position.to_display_point(&display_map).row()
 2801                != new_cursor_position.to_display_point(&display_map).row()
 2802            {
 2803                self.available_code_actions.take();
 2804            }
 2805            self.refresh_code_actions(cx);
 2806            self.refresh_document_highlights(cx);
 2807            refresh_matching_bracket_highlights(self, cx);
 2808            self.discard_inline_completion(false, cx);
 2809            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2810            if self.git_blame_inline_enabled {
 2811                self.start_inline_blame_timer(cx);
 2812            }
 2813        }
 2814
 2815        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2816        cx.emit(EditorEvent::SelectionsChanged { local });
 2817
 2818        if self.selections.disjoint_anchors().len() == 1 {
 2819            cx.emit(SearchEvent::ActiveMatchChanged)
 2820        }
 2821        cx.notify();
 2822    }
 2823
 2824    pub fn change_selections<R>(
 2825        &mut self,
 2826        autoscroll: Option<Autoscroll>,
 2827        cx: &mut ViewContext<Self>,
 2828        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2829    ) -> R {
 2830        self.change_selections_inner(autoscroll, true, cx, change)
 2831    }
 2832
 2833    pub fn change_selections_inner<R>(
 2834        &mut self,
 2835        autoscroll: Option<Autoscroll>,
 2836        request_completions: bool,
 2837        cx: &mut ViewContext<Self>,
 2838        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2839    ) -> R {
 2840        let old_cursor_position = self.selections.newest_anchor().head();
 2841        self.push_to_selection_history();
 2842
 2843        let (changed, result) = self.selections.change_with(cx, change);
 2844
 2845        if changed {
 2846            if let Some(autoscroll) = autoscroll {
 2847                self.request_autoscroll(autoscroll, cx);
 2848            }
 2849            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2850
 2851            if self.should_open_signature_help_automatically(
 2852                &old_cursor_position,
 2853                self.signature_help_state.backspace_pressed(),
 2854                cx,
 2855            ) {
 2856                self.show_signature_help(&ShowSignatureHelp, cx);
 2857            }
 2858            self.signature_help_state.set_backspace_pressed(false);
 2859        }
 2860
 2861        result
 2862    }
 2863
 2864    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2865    where
 2866        I: IntoIterator<Item = (Range<S>, T)>,
 2867        S: ToOffset,
 2868        T: Into<Arc<str>>,
 2869    {
 2870        if self.read_only(cx) {
 2871            return;
 2872        }
 2873
 2874        self.buffer
 2875            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2876    }
 2877
 2878    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2879    where
 2880        I: IntoIterator<Item = (Range<S>, T)>,
 2881        S: ToOffset,
 2882        T: Into<Arc<str>>,
 2883    {
 2884        if self.read_only(cx) {
 2885            return;
 2886        }
 2887
 2888        self.buffer.update(cx, |buffer, cx| {
 2889            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2890        });
 2891    }
 2892
 2893    pub fn edit_with_block_indent<I, S, T>(
 2894        &mut self,
 2895        edits: I,
 2896        original_indent_columns: Vec<u32>,
 2897        cx: &mut ViewContext<Self>,
 2898    ) where
 2899        I: IntoIterator<Item = (Range<S>, T)>,
 2900        S: ToOffset,
 2901        T: Into<Arc<str>>,
 2902    {
 2903        if self.read_only(cx) {
 2904            return;
 2905        }
 2906
 2907        self.buffer.update(cx, |buffer, cx| {
 2908            buffer.edit(
 2909                edits,
 2910                Some(AutoindentMode::Block {
 2911                    original_indent_columns,
 2912                }),
 2913                cx,
 2914            )
 2915        });
 2916    }
 2917
 2918    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2919        self.hide_context_menu(cx);
 2920
 2921        match phase {
 2922            SelectPhase::Begin {
 2923                position,
 2924                add,
 2925                click_count,
 2926            } => self.begin_selection(position, add, click_count, cx),
 2927            SelectPhase::BeginColumnar {
 2928                position,
 2929                goal_column,
 2930                reset,
 2931            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2932            SelectPhase::Extend {
 2933                position,
 2934                click_count,
 2935            } => self.extend_selection(position, click_count, cx),
 2936            SelectPhase::Update {
 2937                position,
 2938                goal_column,
 2939                scroll_delta,
 2940            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2941            SelectPhase::End => self.end_selection(cx),
 2942        }
 2943    }
 2944
 2945    fn extend_selection(
 2946        &mut self,
 2947        position: DisplayPoint,
 2948        click_count: usize,
 2949        cx: &mut ViewContext<Self>,
 2950    ) {
 2951        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2952        let tail = self.selections.newest::<usize>(cx).tail();
 2953        self.begin_selection(position, false, click_count, cx);
 2954
 2955        let position = position.to_offset(&display_map, Bias::Left);
 2956        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2957
 2958        let mut pending_selection = self
 2959            .selections
 2960            .pending_anchor()
 2961            .expect("extend_selection not called with pending selection");
 2962        if position >= tail {
 2963            pending_selection.start = tail_anchor;
 2964        } else {
 2965            pending_selection.end = tail_anchor;
 2966            pending_selection.reversed = true;
 2967        }
 2968
 2969        let mut pending_mode = self.selections.pending_mode().unwrap();
 2970        match &mut pending_mode {
 2971            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2972            _ => {}
 2973        }
 2974
 2975        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2976            s.set_pending(pending_selection, pending_mode)
 2977        });
 2978    }
 2979
 2980    fn begin_selection(
 2981        &mut self,
 2982        position: DisplayPoint,
 2983        add: bool,
 2984        click_count: usize,
 2985        cx: &mut ViewContext<Self>,
 2986    ) {
 2987        if !self.focus_handle.is_focused(cx) {
 2988            self.last_focused_descendant = None;
 2989            cx.focus(&self.focus_handle);
 2990        }
 2991
 2992        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2993        let buffer = &display_map.buffer_snapshot;
 2994        let newest_selection = self.selections.newest_anchor().clone();
 2995        let position = display_map.clip_point(position, Bias::Left);
 2996
 2997        let start;
 2998        let end;
 2999        let mode;
 3000        let auto_scroll;
 3001        match click_count {
 3002            1 => {
 3003                start = buffer.anchor_before(position.to_point(&display_map));
 3004                end = start;
 3005                mode = SelectMode::Character;
 3006                auto_scroll = true;
 3007            }
 3008            2 => {
 3009                let range = movement::surrounding_word(&display_map, position);
 3010                start = buffer.anchor_before(range.start.to_point(&display_map));
 3011                end = buffer.anchor_before(range.end.to_point(&display_map));
 3012                mode = SelectMode::Word(start..end);
 3013                auto_scroll = true;
 3014            }
 3015            3 => {
 3016                let position = display_map
 3017                    .clip_point(position, Bias::Left)
 3018                    .to_point(&display_map);
 3019                let line_start = display_map.prev_line_boundary(position).0;
 3020                let next_line_start = buffer.clip_point(
 3021                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3022                    Bias::Left,
 3023                );
 3024                start = buffer.anchor_before(line_start);
 3025                end = buffer.anchor_before(next_line_start);
 3026                mode = SelectMode::Line(start..end);
 3027                auto_scroll = true;
 3028            }
 3029            _ => {
 3030                start = buffer.anchor_before(0);
 3031                end = buffer.anchor_before(buffer.len());
 3032                mode = SelectMode::All;
 3033                auto_scroll = false;
 3034            }
 3035        }
 3036
 3037        let point_to_delete: Option<usize> = {
 3038            let selected_points: Vec<Selection<Point>> =
 3039                self.selections.disjoint_in_range(start..end, cx);
 3040
 3041            if !add || click_count > 1 {
 3042                None
 3043            } else if !selected_points.is_empty() {
 3044                Some(selected_points[0].id)
 3045            } else {
 3046                let clicked_point_already_selected =
 3047                    self.selections.disjoint.iter().find(|selection| {
 3048                        selection.start.to_point(buffer) == start.to_point(buffer)
 3049                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3050                    });
 3051
 3052                clicked_point_already_selected.map(|selection| selection.id)
 3053            }
 3054        };
 3055
 3056        let selections_count = self.selections.count();
 3057
 3058        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 3059            if let Some(point_to_delete) = point_to_delete {
 3060                s.delete(point_to_delete);
 3061
 3062                if selections_count == 1 {
 3063                    s.set_pending_anchor_range(start..end, mode);
 3064                }
 3065            } else {
 3066                if !add {
 3067                    s.clear_disjoint();
 3068                } else if click_count > 1 {
 3069                    s.delete(newest_selection.id)
 3070                }
 3071
 3072                s.set_pending_anchor_range(start..end, mode);
 3073            }
 3074        });
 3075    }
 3076
 3077    fn begin_columnar_selection(
 3078        &mut self,
 3079        position: DisplayPoint,
 3080        goal_column: u32,
 3081        reset: bool,
 3082        cx: &mut ViewContext<Self>,
 3083    ) {
 3084        if !self.focus_handle.is_focused(cx) {
 3085            self.last_focused_descendant = None;
 3086            cx.focus(&self.focus_handle);
 3087        }
 3088
 3089        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3090
 3091        if reset {
 3092            let pointer_position = display_map
 3093                .buffer_snapshot
 3094                .anchor_before(position.to_point(&display_map));
 3095
 3096            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 3097                s.clear_disjoint();
 3098                s.set_pending_anchor_range(
 3099                    pointer_position..pointer_position,
 3100                    SelectMode::Character,
 3101                );
 3102            });
 3103        }
 3104
 3105        let tail = self.selections.newest::<Point>(cx).tail();
 3106        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3107
 3108        if !reset {
 3109            self.select_columns(
 3110                tail.to_display_point(&display_map),
 3111                position,
 3112                goal_column,
 3113                &display_map,
 3114                cx,
 3115            );
 3116        }
 3117    }
 3118
 3119    fn update_selection(
 3120        &mut self,
 3121        position: DisplayPoint,
 3122        goal_column: u32,
 3123        scroll_delta: gpui::Point<f32>,
 3124        cx: &mut ViewContext<Self>,
 3125    ) {
 3126        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3127
 3128        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3129            let tail = tail.to_display_point(&display_map);
 3130            self.select_columns(tail, position, goal_column, &display_map, cx);
 3131        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3132            let buffer = self.buffer.read(cx).snapshot(cx);
 3133            let head;
 3134            let tail;
 3135            let mode = self.selections.pending_mode().unwrap();
 3136            match &mode {
 3137                SelectMode::Character => {
 3138                    head = position.to_point(&display_map);
 3139                    tail = pending.tail().to_point(&buffer);
 3140                }
 3141                SelectMode::Word(original_range) => {
 3142                    let original_display_range = original_range.start.to_display_point(&display_map)
 3143                        ..original_range.end.to_display_point(&display_map);
 3144                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3145                        ..original_display_range.end.to_point(&display_map);
 3146                    if movement::is_inside_word(&display_map, position)
 3147                        || original_display_range.contains(&position)
 3148                    {
 3149                        let word_range = movement::surrounding_word(&display_map, position);
 3150                        if word_range.start < original_display_range.start {
 3151                            head = word_range.start.to_point(&display_map);
 3152                        } else {
 3153                            head = word_range.end.to_point(&display_map);
 3154                        }
 3155                    } else {
 3156                        head = position.to_point(&display_map);
 3157                    }
 3158
 3159                    if head <= original_buffer_range.start {
 3160                        tail = original_buffer_range.end;
 3161                    } else {
 3162                        tail = original_buffer_range.start;
 3163                    }
 3164                }
 3165                SelectMode::Line(original_range) => {
 3166                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3167
 3168                    let position = display_map
 3169                        .clip_point(position, Bias::Left)
 3170                        .to_point(&display_map);
 3171                    let line_start = display_map.prev_line_boundary(position).0;
 3172                    let next_line_start = buffer.clip_point(
 3173                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3174                        Bias::Left,
 3175                    );
 3176
 3177                    if line_start < original_range.start {
 3178                        head = line_start
 3179                    } else {
 3180                        head = next_line_start
 3181                    }
 3182
 3183                    if head <= original_range.start {
 3184                        tail = original_range.end;
 3185                    } else {
 3186                        tail = original_range.start;
 3187                    }
 3188                }
 3189                SelectMode::All => {
 3190                    return;
 3191                }
 3192            };
 3193
 3194            if head < tail {
 3195                pending.start = buffer.anchor_before(head);
 3196                pending.end = buffer.anchor_before(tail);
 3197                pending.reversed = true;
 3198            } else {
 3199                pending.start = buffer.anchor_before(tail);
 3200                pending.end = buffer.anchor_before(head);
 3201                pending.reversed = false;
 3202            }
 3203
 3204            self.change_selections(None, cx, |s| {
 3205                s.set_pending(pending, mode);
 3206            });
 3207        } else {
 3208            log::error!("update_selection dispatched with no pending selection");
 3209            return;
 3210        }
 3211
 3212        self.apply_scroll_delta(scroll_delta, cx);
 3213        cx.notify();
 3214    }
 3215
 3216    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3217        self.columnar_selection_tail.take();
 3218        if self.selections.pending_anchor().is_some() {
 3219            let selections = self.selections.all::<usize>(cx);
 3220            self.change_selections(None, cx, |s| {
 3221                s.select(selections);
 3222                s.clear_pending();
 3223            });
 3224        }
 3225    }
 3226
 3227    fn select_columns(
 3228        &mut self,
 3229        tail: DisplayPoint,
 3230        head: DisplayPoint,
 3231        goal_column: u32,
 3232        display_map: &DisplaySnapshot,
 3233        cx: &mut ViewContext<Self>,
 3234    ) {
 3235        let start_row = cmp::min(tail.row(), head.row());
 3236        let end_row = cmp::max(tail.row(), head.row());
 3237        let start_column = cmp::min(tail.column(), goal_column);
 3238        let end_column = cmp::max(tail.column(), goal_column);
 3239        let reversed = start_column < tail.column();
 3240
 3241        let selection_ranges = (start_row.0..=end_row.0)
 3242            .map(DisplayRow)
 3243            .filter_map(|row| {
 3244                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3245                    let start = display_map
 3246                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3247                        .to_point(display_map);
 3248                    let end = display_map
 3249                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3250                        .to_point(display_map);
 3251                    if reversed {
 3252                        Some(end..start)
 3253                    } else {
 3254                        Some(start..end)
 3255                    }
 3256                } else {
 3257                    None
 3258                }
 3259            })
 3260            .collect::<Vec<_>>();
 3261
 3262        self.change_selections(None, cx, |s| {
 3263            s.select_ranges(selection_ranges);
 3264        });
 3265        cx.notify();
 3266    }
 3267
 3268    pub fn has_pending_nonempty_selection(&self) -> bool {
 3269        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3270            Some(Selection { start, end, .. }) => start != end,
 3271            None => false,
 3272        };
 3273
 3274        pending_nonempty_selection
 3275            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3276    }
 3277
 3278    pub fn has_pending_selection(&self) -> bool {
 3279        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3280    }
 3281
 3282    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3283        if self.clear_expanded_diff_hunks(cx) {
 3284            cx.notify();
 3285            return;
 3286        }
 3287        if self.dismiss_menus_and_popups(true, cx) {
 3288            return;
 3289        }
 3290
 3291        if self.mode == EditorMode::Full
 3292            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3293        {
 3294            return;
 3295        }
 3296
 3297        cx.propagate();
 3298    }
 3299
 3300    pub fn dismiss_menus_and_popups(
 3301        &mut self,
 3302        should_report_inline_completion_event: bool,
 3303        cx: &mut ViewContext<Self>,
 3304    ) -> bool {
 3305        if self.take_rename(false, cx).is_some() {
 3306            return true;
 3307        }
 3308
 3309        if hide_hover(self, cx) {
 3310            return true;
 3311        }
 3312
 3313        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3314            return true;
 3315        }
 3316
 3317        if self.hide_context_menu(cx).is_some() {
 3318            return true;
 3319        }
 3320
 3321        if self.mouse_context_menu.take().is_some() {
 3322            return true;
 3323        }
 3324
 3325        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3326            return true;
 3327        }
 3328
 3329        if self.snippet_stack.pop().is_some() {
 3330            return true;
 3331        }
 3332
 3333        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3334            self.dismiss_diagnostics(cx);
 3335            return true;
 3336        }
 3337
 3338        false
 3339    }
 3340
 3341    fn linked_editing_ranges_for(
 3342        &self,
 3343        selection: Range<text::Anchor>,
 3344        cx: &AppContext,
 3345    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3346        if self.linked_edit_ranges.is_empty() {
 3347            return None;
 3348        }
 3349        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3350            selection.end.buffer_id.and_then(|end_buffer_id| {
 3351                if selection.start.buffer_id != Some(end_buffer_id) {
 3352                    return None;
 3353                }
 3354                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3355                let snapshot = buffer.read(cx).snapshot();
 3356                self.linked_edit_ranges
 3357                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3358                    .map(|ranges| (ranges, snapshot, buffer))
 3359            })?;
 3360        use text::ToOffset as TO;
 3361        // find offset from the start of current range to current cursor position
 3362        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3363
 3364        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3365        let start_difference = start_offset - start_byte_offset;
 3366        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3367        let end_difference = end_offset - start_byte_offset;
 3368        // Current range has associated linked ranges.
 3369        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3370        for range in linked_ranges.iter() {
 3371            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3372            let end_offset = start_offset + end_difference;
 3373            let start_offset = start_offset + start_difference;
 3374            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3375                continue;
 3376            }
 3377            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3378                if s.start.buffer_id != selection.start.buffer_id
 3379                    || s.end.buffer_id != selection.end.buffer_id
 3380                {
 3381                    return false;
 3382                }
 3383                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3384                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3385            }) {
 3386                continue;
 3387            }
 3388            let start = buffer_snapshot.anchor_after(start_offset);
 3389            let end = buffer_snapshot.anchor_after(end_offset);
 3390            linked_edits
 3391                .entry(buffer.clone())
 3392                .or_default()
 3393                .push(start..end);
 3394        }
 3395        Some(linked_edits)
 3396    }
 3397
 3398    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3399        let text: Arc<str> = text.into();
 3400
 3401        if self.read_only(cx) {
 3402            return;
 3403        }
 3404
 3405        let selections = self.selections.all_adjusted(cx);
 3406        let mut bracket_inserted = false;
 3407        let mut edits = Vec::new();
 3408        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3409        let mut new_selections = Vec::with_capacity(selections.len());
 3410        let mut new_autoclose_regions = Vec::new();
 3411        let snapshot = self.buffer.read(cx).read(cx);
 3412
 3413        for (selection, autoclose_region) in
 3414            self.selections_with_autoclose_regions(selections, &snapshot)
 3415        {
 3416            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3417                // Determine if the inserted text matches the opening or closing
 3418                // bracket of any of this language's bracket pairs.
 3419                let mut bracket_pair = None;
 3420                let mut is_bracket_pair_start = false;
 3421                let mut is_bracket_pair_end = false;
 3422                if !text.is_empty() {
 3423                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3424                    //  and they are removing the character that triggered IME popup.
 3425                    for (pair, enabled) in scope.brackets() {
 3426                        if !pair.close && !pair.surround {
 3427                            continue;
 3428                        }
 3429
 3430                        if enabled && pair.start.ends_with(text.as_ref()) {
 3431                            let prefix_len = pair.start.len() - text.len();
 3432                            let preceding_text_matches_prefix = prefix_len == 0
 3433                                || (selection.start.column >= (prefix_len as u32)
 3434                                    && snapshot.contains_str_at(
 3435                                        Point::new(
 3436                                            selection.start.row,
 3437                                            selection.start.column - (prefix_len as u32),
 3438                                        ),
 3439                                        &pair.start[..prefix_len],
 3440                                    ));
 3441                            if preceding_text_matches_prefix {
 3442                                bracket_pair = Some(pair.clone());
 3443                                is_bracket_pair_start = true;
 3444                                break;
 3445                            }
 3446                        }
 3447                        if pair.end.as_str() == text.as_ref() {
 3448                            bracket_pair = Some(pair.clone());
 3449                            is_bracket_pair_end = true;
 3450                            break;
 3451                        }
 3452                    }
 3453                }
 3454
 3455                if let Some(bracket_pair) = bracket_pair {
 3456                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3457                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3458                    let auto_surround =
 3459                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3460                    if selection.is_empty() {
 3461                        if is_bracket_pair_start {
 3462                            // If the inserted text is a suffix of an opening bracket and the
 3463                            // selection is preceded by the rest of the opening bracket, then
 3464                            // insert the closing bracket.
 3465                            let following_text_allows_autoclose = snapshot
 3466                                .chars_at(selection.start)
 3467                                .next()
 3468                                .map_or(true, |c| scope.should_autoclose_before(c));
 3469
 3470                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3471                                && bracket_pair.start.len() == 1
 3472                            {
 3473                                let target = bracket_pair.start.chars().next().unwrap();
 3474                                let current_line_count = snapshot
 3475                                    .reversed_chars_at(selection.start)
 3476                                    .take_while(|&c| c != '\n')
 3477                                    .filter(|&c| c == target)
 3478                                    .count();
 3479                                current_line_count % 2 == 1
 3480                            } else {
 3481                                false
 3482                            };
 3483
 3484                            if autoclose
 3485                                && bracket_pair.close
 3486                                && following_text_allows_autoclose
 3487                                && !is_closing_quote
 3488                            {
 3489                                let anchor = snapshot.anchor_before(selection.end);
 3490                                new_selections.push((selection.map(|_| anchor), text.len()));
 3491                                new_autoclose_regions.push((
 3492                                    anchor,
 3493                                    text.len(),
 3494                                    selection.id,
 3495                                    bracket_pair.clone(),
 3496                                ));
 3497                                edits.push((
 3498                                    selection.range(),
 3499                                    format!("{}{}", text, bracket_pair.end).into(),
 3500                                ));
 3501                                bracket_inserted = true;
 3502                                continue;
 3503                            }
 3504                        }
 3505
 3506                        if let Some(region) = autoclose_region {
 3507                            // If the selection is followed by an auto-inserted closing bracket,
 3508                            // then don't insert that closing bracket again; just move the selection
 3509                            // past the closing bracket.
 3510                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3511                                && text.as_ref() == region.pair.end.as_str();
 3512                            if should_skip {
 3513                                let anchor = snapshot.anchor_after(selection.end);
 3514                                new_selections
 3515                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3516                                continue;
 3517                            }
 3518                        }
 3519
 3520                        let always_treat_brackets_as_autoclosed = snapshot
 3521                            .settings_at(selection.start, cx)
 3522                            .always_treat_brackets_as_autoclosed;
 3523                        if always_treat_brackets_as_autoclosed
 3524                            && is_bracket_pair_end
 3525                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3526                        {
 3527                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3528                            // and the inserted text is a closing bracket and the selection is followed
 3529                            // by the closing bracket then move the selection past the closing bracket.
 3530                            let anchor = snapshot.anchor_after(selection.end);
 3531                            new_selections.push((selection.map(|_| anchor), text.len()));
 3532                            continue;
 3533                        }
 3534                    }
 3535                    // If an opening bracket is 1 character long and is typed while
 3536                    // text is selected, then surround that text with the bracket pair.
 3537                    else if auto_surround
 3538                        && bracket_pair.surround
 3539                        && is_bracket_pair_start
 3540                        && bracket_pair.start.chars().count() == 1
 3541                    {
 3542                        edits.push((selection.start..selection.start, text.clone()));
 3543                        edits.push((
 3544                            selection.end..selection.end,
 3545                            bracket_pair.end.as_str().into(),
 3546                        ));
 3547                        bracket_inserted = true;
 3548                        new_selections.push((
 3549                            Selection {
 3550                                id: selection.id,
 3551                                start: snapshot.anchor_after(selection.start),
 3552                                end: snapshot.anchor_before(selection.end),
 3553                                reversed: selection.reversed,
 3554                                goal: selection.goal,
 3555                            },
 3556                            0,
 3557                        ));
 3558                        continue;
 3559                    }
 3560                }
 3561            }
 3562
 3563            if self.auto_replace_emoji_shortcode
 3564                && selection.is_empty()
 3565                && text.as_ref().ends_with(':')
 3566            {
 3567                if let Some(possible_emoji_short_code) =
 3568                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3569                {
 3570                    if !possible_emoji_short_code.is_empty() {
 3571                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3572                            let emoji_shortcode_start = Point::new(
 3573                                selection.start.row,
 3574                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3575                            );
 3576
 3577                            // Remove shortcode from buffer
 3578                            edits.push((
 3579                                emoji_shortcode_start..selection.start,
 3580                                "".to_string().into(),
 3581                            ));
 3582                            new_selections.push((
 3583                                Selection {
 3584                                    id: selection.id,
 3585                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3586                                    end: snapshot.anchor_before(selection.start),
 3587                                    reversed: selection.reversed,
 3588                                    goal: selection.goal,
 3589                                },
 3590                                0,
 3591                            ));
 3592
 3593                            // Insert emoji
 3594                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3595                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3596                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3597
 3598                            continue;
 3599                        }
 3600                    }
 3601                }
 3602            }
 3603
 3604            // If not handling any auto-close operation, then just replace the selected
 3605            // text with the given input and move the selection to the end of the
 3606            // newly inserted text.
 3607            let anchor = snapshot.anchor_after(selection.end);
 3608            if !self.linked_edit_ranges.is_empty() {
 3609                let start_anchor = snapshot.anchor_before(selection.start);
 3610
 3611                let is_word_char = text.chars().next().map_or(true, |char| {
 3612                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3613                    classifier.is_word(char)
 3614                });
 3615
 3616                if is_word_char {
 3617                    if let Some(ranges) = self
 3618                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3619                    {
 3620                        for (buffer, edits) in ranges {
 3621                            linked_edits
 3622                                .entry(buffer.clone())
 3623                                .or_default()
 3624                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3625                        }
 3626                    }
 3627                }
 3628            }
 3629
 3630            new_selections.push((selection.map(|_| anchor), 0));
 3631            edits.push((selection.start..selection.end, text.clone()));
 3632        }
 3633
 3634        drop(snapshot);
 3635
 3636        self.transact(cx, |this, cx| {
 3637            this.buffer.update(cx, |buffer, cx| {
 3638                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3639            });
 3640            for (buffer, edits) in linked_edits {
 3641                buffer.update(cx, |buffer, cx| {
 3642                    let snapshot = buffer.snapshot();
 3643                    let edits = edits
 3644                        .into_iter()
 3645                        .map(|(range, text)| {
 3646                            use text::ToPoint as TP;
 3647                            let end_point = TP::to_point(&range.end, &snapshot);
 3648                            let start_point = TP::to_point(&range.start, &snapshot);
 3649                            (start_point..end_point, text)
 3650                        })
 3651                        .sorted_by_key(|(range, _)| range.start)
 3652                        .collect::<Vec<_>>();
 3653                    buffer.edit(edits, None, cx);
 3654                })
 3655            }
 3656            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3657            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3658            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3659            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3660                .zip(new_selection_deltas)
 3661                .map(|(selection, delta)| Selection {
 3662                    id: selection.id,
 3663                    start: selection.start + delta,
 3664                    end: selection.end + delta,
 3665                    reversed: selection.reversed,
 3666                    goal: SelectionGoal::None,
 3667                })
 3668                .collect::<Vec<_>>();
 3669
 3670            let mut i = 0;
 3671            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3672                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3673                let start = map.buffer_snapshot.anchor_before(position);
 3674                let end = map.buffer_snapshot.anchor_after(position);
 3675                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3676                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3677                        Ordering::Less => i += 1,
 3678                        Ordering::Greater => break,
 3679                        Ordering::Equal => {
 3680                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3681                                Ordering::Less => i += 1,
 3682                                Ordering::Equal => break,
 3683                                Ordering::Greater => break,
 3684                            }
 3685                        }
 3686                    }
 3687                }
 3688                this.autoclose_regions.insert(
 3689                    i,
 3690                    AutocloseRegion {
 3691                        selection_id,
 3692                        range: start..end,
 3693                        pair,
 3694                    },
 3695                );
 3696            }
 3697
 3698            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3699            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3700                s.select(new_selections)
 3701            });
 3702
 3703            if !bracket_inserted {
 3704                if let Some(on_type_format_task) =
 3705                    this.trigger_on_type_formatting(text.to_string(), cx)
 3706                {
 3707                    on_type_format_task.detach_and_log_err(cx);
 3708                }
 3709            }
 3710
 3711            let editor_settings = EditorSettings::get_global(cx);
 3712            if bracket_inserted
 3713                && (editor_settings.auto_signature_help
 3714                    || editor_settings.show_signature_help_after_edits)
 3715            {
 3716                this.show_signature_help(&ShowSignatureHelp, cx);
 3717            }
 3718
 3719            let trigger_in_words = !had_active_inline_completion;
 3720            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3721            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3722            this.refresh_inline_completion(true, false, cx);
 3723        });
 3724    }
 3725
 3726    fn find_possible_emoji_shortcode_at_position(
 3727        snapshot: &MultiBufferSnapshot,
 3728        position: Point,
 3729    ) -> Option<String> {
 3730        let mut chars = Vec::new();
 3731        let mut found_colon = false;
 3732        for char in snapshot.reversed_chars_at(position).take(100) {
 3733            // Found a possible emoji shortcode in the middle of the buffer
 3734            if found_colon {
 3735                if char.is_whitespace() {
 3736                    chars.reverse();
 3737                    return Some(chars.iter().collect());
 3738                }
 3739                // If the previous character is not a whitespace, we are in the middle of a word
 3740                // and we only want to complete the shortcode if the word is made up of other emojis
 3741                let mut containing_word = String::new();
 3742                for ch in snapshot
 3743                    .reversed_chars_at(position)
 3744                    .skip(chars.len() + 1)
 3745                    .take(100)
 3746                {
 3747                    if ch.is_whitespace() {
 3748                        break;
 3749                    }
 3750                    containing_word.push(ch);
 3751                }
 3752                let containing_word = containing_word.chars().rev().collect::<String>();
 3753                if util::word_consists_of_emojis(containing_word.as_str()) {
 3754                    chars.reverse();
 3755                    return Some(chars.iter().collect());
 3756                }
 3757            }
 3758
 3759            if char.is_whitespace() || !char.is_ascii() {
 3760                return None;
 3761            }
 3762            if char == ':' {
 3763                found_colon = true;
 3764            } else {
 3765                chars.push(char);
 3766            }
 3767        }
 3768        // Found a possible emoji shortcode at the beginning of the buffer
 3769        chars.reverse();
 3770        Some(chars.iter().collect())
 3771    }
 3772
 3773    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3774        self.transact(cx, |this, cx| {
 3775            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3776                let selections = this.selections.all::<usize>(cx);
 3777                let multi_buffer = this.buffer.read(cx);
 3778                let buffer = multi_buffer.snapshot(cx);
 3779                selections
 3780                    .iter()
 3781                    .map(|selection| {
 3782                        let start_point = selection.start.to_point(&buffer);
 3783                        let mut indent =
 3784                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3785                        indent.len = cmp::min(indent.len, start_point.column);
 3786                        let start = selection.start;
 3787                        let end = selection.end;
 3788                        let selection_is_empty = start == end;
 3789                        let language_scope = buffer.language_scope_at(start);
 3790                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3791                            &language_scope
 3792                        {
 3793                            let leading_whitespace_len = buffer
 3794                                .reversed_chars_at(start)
 3795                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3796                                .map(|c| c.len_utf8())
 3797                                .sum::<usize>();
 3798
 3799                            let trailing_whitespace_len = buffer
 3800                                .chars_at(end)
 3801                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3802                                .map(|c| c.len_utf8())
 3803                                .sum::<usize>();
 3804
 3805                            let insert_extra_newline =
 3806                                language.brackets().any(|(pair, enabled)| {
 3807                                    let pair_start = pair.start.trim_end();
 3808                                    let pair_end = pair.end.trim_start();
 3809
 3810                                    enabled
 3811                                        && pair.newline
 3812                                        && buffer.contains_str_at(
 3813                                            end + trailing_whitespace_len,
 3814                                            pair_end,
 3815                                        )
 3816                                        && buffer.contains_str_at(
 3817                                            (start - leading_whitespace_len)
 3818                                                .saturating_sub(pair_start.len()),
 3819                                            pair_start,
 3820                                        )
 3821                                });
 3822
 3823                            // Comment extension on newline is allowed only for cursor selections
 3824                            let comment_delimiter = maybe!({
 3825                                if !selection_is_empty {
 3826                                    return None;
 3827                                }
 3828
 3829                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3830                                    return None;
 3831                                }
 3832
 3833                                let delimiters = language.line_comment_prefixes();
 3834                                let max_len_of_delimiter =
 3835                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3836                                let (snapshot, range) =
 3837                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3838
 3839                                let mut index_of_first_non_whitespace = 0;
 3840                                let comment_candidate = snapshot
 3841                                    .chars_for_range(range)
 3842                                    .skip_while(|c| {
 3843                                        let should_skip = c.is_whitespace();
 3844                                        if should_skip {
 3845                                            index_of_first_non_whitespace += 1;
 3846                                        }
 3847                                        should_skip
 3848                                    })
 3849                                    .take(max_len_of_delimiter)
 3850                                    .collect::<String>();
 3851                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3852                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3853                                })?;
 3854                                let cursor_is_placed_after_comment_marker =
 3855                                    index_of_first_non_whitespace + comment_prefix.len()
 3856                                        <= start_point.column as usize;
 3857                                if cursor_is_placed_after_comment_marker {
 3858                                    Some(comment_prefix.clone())
 3859                                } else {
 3860                                    None
 3861                                }
 3862                            });
 3863                            (comment_delimiter, insert_extra_newline)
 3864                        } else {
 3865                            (None, false)
 3866                        };
 3867
 3868                        let capacity_for_delimiter = comment_delimiter
 3869                            .as_deref()
 3870                            .map(str::len)
 3871                            .unwrap_or_default();
 3872                        let mut new_text =
 3873                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3874                        new_text.push('\n');
 3875                        new_text.extend(indent.chars());
 3876                        if let Some(delimiter) = &comment_delimiter {
 3877                            new_text.push_str(delimiter);
 3878                        }
 3879                        if insert_extra_newline {
 3880                            new_text = new_text.repeat(2);
 3881                        }
 3882
 3883                        let anchor = buffer.anchor_after(end);
 3884                        let new_selection = selection.map(|_| anchor);
 3885                        (
 3886                            (start..end, new_text),
 3887                            (insert_extra_newline, new_selection),
 3888                        )
 3889                    })
 3890                    .unzip()
 3891            };
 3892
 3893            this.edit_with_autoindent(edits, cx);
 3894            let buffer = this.buffer.read(cx).snapshot(cx);
 3895            let new_selections = selection_fixup_info
 3896                .into_iter()
 3897                .map(|(extra_newline_inserted, new_selection)| {
 3898                    let mut cursor = new_selection.end.to_point(&buffer);
 3899                    if extra_newline_inserted {
 3900                        cursor.row -= 1;
 3901                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3902                    }
 3903                    new_selection.map(|_| cursor)
 3904                })
 3905                .collect();
 3906
 3907            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3908            this.refresh_inline_completion(true, false, cx);
 3909        });
 3910    }
 3911
 3912    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3913        let buffer = self.buffer.read(cx);
 3914        let snapshot = buffer.snapshot(cx);
 3915
 3916        let mut edits = Vec::new();
 3917        let mut rows = Vec::new();
 3918
 3919        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3920            let cursor = selection.head();
 3921            let row = cursor.row;
 3922
 3923            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3924
 3925            let newline = "\n".to_string();
 3926            edits.push((start_of_line..start_of_line, newline));
 3927
 3928            rows.push(row + rows_inserted as u32);
 3929        }
 3930
 3931        self.transact(cx, |editor, cx| {
 3932            editor.edit(edits, cx);
 3933
 3934            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3935                let mut index = 0;
 3936                s.move_cursors_with(|map, _, _| {
 3937                    let row = rows[index];
 3938                    index += 1;
 3939
 3940                    let point = Point::new(row, 0);
 3941                    let boundary = map.next_line_boundary(point).1;
 3942                    let clipped = map.clip_point(boundary, Bias::Left);
 3943
 3944                    (clipped, SelectionGoal::None)
 3945                });
 3946            });
 3947
 3948            let mut indent_edits = Vec::new();
 3949            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3950            for row in rows {
 3951                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3952                for (row, indent) in indents {
 3953                    if indent.len == 0 {
 3954                        continue;
 3955                    }
 3956
 3957                    let text = match indent.kind {
 3958                        IndentKind::Space => " ".repeat(indent.len as usize),
 3959                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3960                    };
 3961                    let point = Point::new(row.0, 0);
 3962                    indent_edits.push((point..point, text));
 3963                }
 3964            }
 3965            editor.edit(indent_edits, cx);
 3966        });
 3967    }
 3968
 3969    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3970        let buffer = self.buffer.read(cx);
 3971        let snapshot = buffer.snapshot(cx);
 3972
 3973        let mut edits = Vec::new();
 3974        let mut rows = Vec::new();
 3975        let mut rows_inserted = 0;
 3976
 3977        for selection in self.selections.all_adjusted(cx) {
 3978            let cursor = selection.head();
 3979            let row = cursor.row;
 3980
 3981            let point = Point::new(row + 1, 0);
 3982            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3983
 3984            let newline = "\n".to_string();
 3985            edits.push((start_of_line..start_of_line, newline));
 3986
 3987            rows_inserted += 1;
 3988            rows.push(row + rows_inserted);
 3989        }
 3990
 3991        self.transact(cx, |editor, cx| {
 3992            editor.edit(edits, cx);
 3993
 3994            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3995                let mut index = 0;
 3996                s.move_cursors_with(|map, _, _| {
 3997                    let row = rows[index];
 3998                    index += 1;
 3999
 4000                    let point = Point::new(row, 0);
 4001                    let boundary = map.next_line_boundary(point).1;
 4002                    let clipped = map.clip_point(boundary, Bias::Left);
 4003
 4004                    (clipped, SelectionGoal::None)
 4005                });
 4006            });
 4007
 4008            let mut indent_edits = Vec::new();
 4009            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4010            for row in rows {
 4011                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4012                for (row, indent) in indents {
 4013                    if indent.len == 0 {
 4014                        continue;
 4015                    }
 4016
 4017                    let text = match indent.kind {
 4018                        IndentKind::Space => " ".repeat(indent.len as usize),
 4019                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4020                    };
 4021                    let point = Point::new(row.0, 0);
 4022                    indent_edits.push((point..point, text));
 4023                }
 4024            }
 4025            editor.edit(indent_edits, cx);
 4026        });
 4027    }
 4028
 4029    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 4030        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4031            original_indent_columns: Vec::new(),
 4032        });
 4033        self.insert_with_autoindent_mode(text, autoindent, cx);
 4034    }
 4035
 4036    fn insert_with_autoindent_mode(
 4037        &mut self,
 4038        text: &str,
 4039        autoindent_mode: Option<AutoindentMode>,
 4040        cx: &mut ViewContext<Self>,
 4041    ) {
 4042        if self.read_only(cx) {
 4043            return;
 4044        }
 4045
 4046        let text: Arc<str> = text.into();
 4047        self.transact(cx, |this, cx| {
 4048            let old_selections = this.selections.all_adjusted(cx);
 4049            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4050                let anchors = {
 4051                    let snapshot = buffer.read(cx);
 4052                    old_selections
 4053                        .iter()
 4054                        .map(|s| {
 4055                            let anchor = snapshot.anchor_after(s.head());
 4056                            s.map(|_| anchor)
 4057                        })
 4058                        .collect::<Vec<_>>()
 4059                };
 4060                buffer.edit(
 4061                    old_selections
 4062                        .iter()
 4063                        .map(|s| (s.start..s.end, text.clone())),
 4064                    autoindent_mode,
 4065                    cx,
 4066                );
 4067                anchors
 4068            });
 4069
 4070            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4071                s.select_anchors(selection_anchors);
 4072            })
 4073        });
 4074    }
 4075
 4076    fn trigger_completion_on_input(
 4077        &mut self,
 4078        text: &str,
 4079        trigger_in_words: bool,
 4080        cx: &mut ViewContext<Self>,
 4081    ) {
 4082        if self.is_completion_trigger(text, trigger_in_words, cx) {
 4083            self.show_completions(
 4084                &ShowCompletions {
 4085                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4086                },
 4087                cx,
 4088            );
 4089        } else {
 4090            self.hide_context_menu(cx);
 4091        }
 4092    }
 4093
 4094    fn is_completion_trigger(
 4095        &self,
 4096        text: &str,
 4097        trigger_in_words: bool,
 4098        cx: &mut ViewContext<Self>,
 4099    ) -> bool {
 4100        let position = self.selections.newest_anchor().head();
 4101        let multibuffer = self.buffer.read(cx);
 4102        let Some(buffer) = position
 4103            .buffer_id
 4104            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4105        else {
 4106            return false;
 4107        };
 4108
 4109        if let Some(completion_provider) = &self.completion_provider {
 4110            completion_provider.is_completion_trigger(
 4111                &buffer,
 4112                position.text_anchor,
 4113                text,
 4114                trigger_in_words,
 4115                cx,
 4116            )
 4117        } else {
 4118            false
 4119        }
 4120    }
 4121
 4122    /// If any empty selections is touching the start of its innermost containing autoclose
 4123    /// region, expand it to select the brackets.
 4124    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4125        let selections = self.selections.all::<usize>(cx);
 4126        let buffer = self.buffer.read(cx).read(cx);
 4127        let new_selections = self
 4128            .selections_with_autoclose_regions(selections, &buffer)
 4129            .map(|(mut selection, region)| {
 4130                if !selection.is_empty() {
 4131                    return selection;
 4132                }
 4133
 4134                if let Some(region) = region {
 4135                    let mut range = region.range.to_offset(&buffer);
 4136                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4137                        range.start -= region.pair.start.len();
 4138                        if buffer.contains_str_at(range.start, &region.pair.start)
 4139                            && buffer.contains_str_at(range.end, &region.pair.end)
 4140                        {
 4141                            range.end += region.pair.end.len();
 4142                            selection.start = range.start;
 4143                            selection.end = range.end;
 4144
 4145                            return selection;
 4146                        }
 4147                    }
 4148                }
 4149
 4150                let always_treat_brackets_as_autoclosed = buffer
 4151                    .settings_at(selection.start, cx)
 4152                    .always_treat_brackets_as_autoclosed;
 4153
 4154                if !always_treat_brackets_as_autoclosed {
 4155                    return selection;
 4156                }
 4157
 4158                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4159                    for (pair, enabled) in scope.brackets() {
 4160                        if !enabled || !pair.close {
 4161                            continue;
 4162                        }
 4163
 4164                        if buffer.contains_str_at(selection.start, &pair.end) {
 4165                            let pair_start_len = pair.start.len();
 4166                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 4167                            {
 4168                                selection.start -= pair_start_len;
 4169                                selection.end += pair.end.len();
 4170
 4171                                return selection;
 4172                            }
 4173                        }
 4174                    }
 4175                }
 4176
 4177                selection
 4178            })
 4179            .collect();
 4180
 4181        drop(buffer);
 4182        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4183    }
 4184
 4185    /// Iterate the given selections, and for each one, find the smallest surrounding
 4186    /// autoclose region. This uses the ordering of the selections and the autoclose
 4187    /// regions to avoid repeated comparisons.
 4188    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4189        &'a self,
 4190        selections: impl IntoIterator<Item = Selection<D>>,
 4191        buffer: &'a MultiBufferSnapshot,
 4192    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4193        let mut i = 0;
 4194        let mut regions = self.autoclose_regions.as_slice();
 4195        selections.into_iter().map(move |selection| {
 4196            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4197
 4198            let mut enclosing = None;
 4199            while let Some(pair_state) = regions.get(i) {
 4200                if pair_state.range.end.to_offset(buffer) < range.start {
 4201                    regions = &regions[i + 1..];
 4202                    i = 0;
 4203                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4204                    break;
 4205                } else {
 4206                    if pair_state.selection_id == selection.id {
 4207                        enclosing = Some(pair_state);
 4208                    }
 4209                    i += 1;
 4210                }
 4211            }
 4212
 4213            (selection, enclosing)
 4214        })
 4215    }
 4216
 4217    /// Remove any autoclose regions that no longer contain their selection.
 4218    fn invalidate_autoclose_regions(
 4219        &mut self,
 4220        mut selections: &[Selection<Anchor>],
 4221        buffer: &MultiBufferSnapshot,
 4222    ) {
 4223        self.autoclose_regions.retain(|state| {
 4224            let mut i = 0;
 4225            while let Some(selection) = selections.get(i) {
 4226                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4227                    selections = &selections[1..];
 4228                    continue;
 4229                }
 4230                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4231                    break;
 4232                }
 4233                if selection.id == state.selection_id {
 4234                    return true;
 4235                } else {
 4236                    i += 1;
 4237                }
 4238            }
 4239            false
 4240        });
 4241    }
 4242
 4243    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4244        let offset = position.to_offset(buffer);
 4245        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4246        if offset > word_range.start && kind == Some(CharKind::Word) {
 4247            Some(
 4248                buffer
 4249                    .text_for_range(word_range.start..offset)
 4250                    .collect::<String>(),
 4251            )
 4252        } else {
 4253            None
 4254        }
 4255    }
 4256
 4257    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4258        self.refresh_inlay_hints(
 4259            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4260            cx,
 4261        );
 4262    }
 4263
 4264    pub fn inlay_hints_enabled(&self) -> bool {
 4265        self.inlay_hint_cache.enabled
 4266    }
 4267
 4268    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4269        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4270            return;
 4271        }
 4272
 4273        let reason_description = reason.description();
 4274        let ignore_debounce = matches!(
 4275            reason,
 4276            InlayHintRefreshReason::SettingsChange(_)
 4277                | InlayHintRefreshReason::Toggle(_)
 4278                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4279        );
 4280        let (invalidate_cache, required_languages) = match reason {
 4281            InlayHintRefreshReason::Toggle(enabled) => {
 4282                self.inlay_hint_cache.enabled = enabled;
 4283                if enabled {
 4284                    (InvalidationStrategy::RefreshRequested, None)
 4285                } else {
 4286                    self.inlay_hint_cache.clear();
 4287                    self.splice_inlays(
 4288                        self.visible_inlay_hints(cx)
 4289                            .iter()
 4290                            .map(|inlay| inlay.id)
 4291                            .collect(),
 4292                        Vec::new(),
 4293                        cx,
 4294                    );
 4295                    return;
 4296                }
 4297            }
 4298            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4299                match self.inlay_hint_cache.update_settings(
 4300                    &self.buffer,
 4301                    new_settings,
 4302                    self.visible_inlay_hints(cx),
 4303                    cx,
 4304                ) {
 4305                    ControlFlow::Break(Some(InlaySplice {
 4306                        to_remove,
 4307                        to_insert,
 4308                    })) => {
 4309                        self.splice_inlays(to_remove, to_insert, cx);
 4310                        return;
 4311                    }
 4312                    ControlFlow::Break(None) => return,
 4313                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4314                }
 4315            }
 4316            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4317                if let Some(InlaySplice {
 4318                    to_remove,
 4319                    to_insert,
 4320                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4321                {
 4322                    self.splice_inlays(to_remove, to_insert, cx);
 4323                }
 4324                return;
 4325            }
 4326            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4327            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4328                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4329            }
 4330            InlayHintRefreshReason::RefreshRequested => {
 4331                (InvalidationStrategy::RefreshRequested, None)
 4332            }
 4333        };
 4334
 4335        if let Some(InlaySplice {
 4336            to_remove,
 4337            to_insert,
 4338        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4339            reason_description,
 4340            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4341            invalidate_cache,
 4342            ignore_debounce,
 4343            cx,
 4344        ) {
 4345            self.splice_inlays(to_remove, to_insert, cx);
 4346        }
 4347    }
 4348
 4349    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4350        self.display_map
 4351            .read(cx)
 4352            .current_inlays()
 4353            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4354            .cloned()
 4355            .collect()
 4356    }
 4357
 4358    pub fn excerpts_for_inlay_hints_query(
 4359        &self,
 4360        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4361        cx: &mut ViewContext<Editor>,
 4362    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4363        let Some(project) = self.project.as_ref() else {
 4364            return HashMap::default();
 4365        };
 4366        let project = project.read(cx);
 4367        let multi_buffer = self.buffer().read(cx);
 4368        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4369        let multi_buffer_visible_start = self
 4370            .scroll_manager
 4371            .anchor()
 4372            .anchor
 4373            .to_point(&multi_buffer_snapshot);
 4374        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4375            multi_buffer_visible_start
 4376                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4377            Bias::Left,
 4378        );
 4379        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4380        multi_buffer
 4381            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4382            .into_iter()
 4383            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4384            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4385                let buffer = buffer_handle.read(cx);
 4386                let buffer_file = project::File::from_dyn(buffer.file())?;
 4387                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4388                let worktree_entry = buffer_worktree
 4389                    .read(cx)
 4390                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4391                if worktree_entry.is_ignored {
 4392                    return None;
 4393                }
 4394
 4395                let language = buffer.language()?;
 4396                if let Some(restrict_to_languages) = restrict_to_languages {
 4397                    if !restrict_to_languages.contains(language) {
 4398                        return None;
 4399                    }
 4400                }
 4401                Some((
 4402                    excerpt_id,
 4403                    (
 4404                        buffer_handle,
 4405                        buffer.version().clone(),
 4406                        excerpt_visible_range,
 4407                    ),
 4408                ))
 4409            })
 4410            .collect()
 4411    }
 4412
 4413    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4414        TextLayoutDetails {
 4415            text_system: cx.text_system().clone(),
 4416            editor_style: self.style.clone().unwrap(),
 4417            rem_size: cx.rem_size(),
 4418            scroll_anchor: self.scroll_manager.anchor(),
 4419            visible_rows: self.visible_line_count(),
 4420            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4421        }
 4422    }
 4423
 4424    fn splice_inlays(
 4425        &self,
 4426        to_remove: Vec<InlayId>,
 4427        to_insert: Vec<Inlay>,
 4428        cx: &mut ViewContext<Self>,
 4429    ) {
 4430        self.display_map.update(cx, |display_map, cx| {
 4431            display_map.splice_inlays(to_remove, to_insert, cx);
 4432        });
 4433        cx.notify();
 4434    }
 4435
 4436    fn trigger_on_type_formatting(
 4437        &self,
 4438        input: String,
 4439        cx: &mut ViewContext<Self>,
 4440    ) -> Option<Task<Result<()>>> {
 4441        if input.len() != 1 {
 4442            return None;
 4443        }
 4444
 4445        let project = self.project.as_ref()?;
 4446        let position = self.selections.newest_anchor().head();
 4447        let (buffer, buffer_position) = self
 4448            .buffer
 4449            .read(cx)
 4450            .text_anchor_for_position(position, cx)?;
 4451
 4452        let settings = language_settings::language_settings(
 4453            buffer
 4454                .read(cx)
 4455                .language_at(buffer_position)
 4456                .map(|l| l.name()),
 4457            buffer.read(cx).file(),
 4458            cx,
 4459        );
 4460        if !settings.use_on_type_format {
 4461            return None;
 4462        }
 4463
 4464        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4465        // hence we do LSP request & edit on host side only — add formats to host's history.
 4466        let push_to_lsp_host_history = true;
 4467        // If this is not the host, append its history with new edits.
 4468        let push_to_client_history = project.read(cx).is_via_collab();
 4469
 4470        let on_type_formatting = project.update(cx, |project, cx| {
 4471            project.on_type_format(
 4472                buffer.clone(),
 4473                buffer_position,
 4474                input,
 4475                push_to_lsp_host_history,
 4476                cx,
 4477            )
 4478        });
 4479        Some(cx.spawn(|editor, mut cx| async move {
 4480            if let Some(transaction) = on_type_formatting.await? {
 4481                if push_to_client_history {
 4482                    buffer
 4483                        .update(&mut cx, |buffer, _| {
 4484                            buffer.push_transaction(transaction, Instant::now());
 4485                        })
 4486                        .ok();
 4487                }
 4488                editor.update(&mut cx, |editor, cx| {
 4489                    editor.refresh_document_highlights(cx);
 4490                })?;
 4491            }
 4492            Ok(())
 4493        }))
 4494    }
 4495
 4496    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4497        if self.pending_rename.is_some() {
 4498            return;
 4499        }
 4500
 4501        let Some(provider) = self.completion_provider.as_ref() else {
 4502            return;
 4503        };
 4504
 4505        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4506            return;
 4507        }
 4508
 4509        let position = self.selections.newest_anchor().head();
 4510        let (buffer, buffer_position) =
 4511            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4512                output
 4513            } else {
 4514                return;
 4515            };
 4516
 4517        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4518        let is_followup_invoke = {
 4519            let context_menu_state = self.context_menu.read();
 4520            matches!(
 4521                context_menu_state.deref(),
 4522                Some(ContextMenu::Completions(_))
 4523            )
 4524        };
 4525        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4526            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4527            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4528                CompletionTriggerKind::TRIGGER_CHARACTER
 4529            }
 4530
 4531            _ => CompletionTriggerKind::INVOKED,
 4532        };
 4533        let completion_context = CompletionContext {
 4534            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4535                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4536                    Some(String::from(trigger))
 4537                } else {
 4538                    None
 4539                }
 4540            }),
 4541            trigger_kind,
 4542        };
 4543        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4544        let sort_completions = provider.sort_completions();
 4545
 4546        let id = post_inc(&mut self.next_completion_id);
 4547        let task = cx.spawn(|this, mut cx| {
 4548            async move {
 4549                this.update(&mut cx, |this, _| {
 4550                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4551                })?;
 4552                let completions = completions.await.log_err();
 4553                let menu = if let Some(completions) = completions {
 4554                    let mut menu = CompletionsMenu::new(
 4555                        id,
 4556                        sort_completions,
 4557                        position,
 4558                        buffer.clone(),
 4559                        completions.into(),
 4560                    );
 4561                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4562                        .await;
 4563
 4564                    if menu.matches.is_empty() {
 4565                        None
 4566                    } else {
 4567                        this.update(&mut cx, |editor, cx| {
 4568                            let completions = menu.completions.clone();
 4569                            let matches = menu.matches.clone();
 4570
 4571                            let delay_ms = EditorSettings::get_global(cx)
 4572                                .completion_documentation_secondary_query_debounce;
 4573                            let delay = Duration::from_millis(delay_ms);
 4574                            editor
 4575                                .completion_documentation_pre_resolve_debounce
 4576                                .fire_new(delay, cx, |editor, cx| {
 4577                                    CompletionsMenu::pre_resolve_completion_documentation(
 4578                                        buffer,
 4579                                        completions,
 4580                                        matches,
 4581                                        editor,
 4582                                        cx,
 4583                                    )
 4584                                });
 4585                        })
 4586                        .ok();
 4587                        Some(menu)
 4588                    }
 4589                } else {
 4590                    None
 4591                };
 4592
 4593                this.update(&mut cx, |this, cx| {
 4594                    let mut context_menu = this.context_menu.write();
 4595                    match context_menu.as_ref() {
 4596                        None => {}
 4597
 4598                        Some(ContextMenu::Completions(prev_menu)) => {
 4599                            if prev_menu.id > id {
 4600                                return;
 4601                            }
 4602                        }
 4603
 4604                        _ => return,
 4605                    }
 4606
 4607                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4608                        let menu = menu.unwrap();
 4609                        *context_menu = Some(ContextMenu::Completions(menu));
 4610                        drop(context_menu);
 4611                        this.discard_inline_completion(false, cx);
 4612                        cx.notify();
 4613                    } else if this.completion_tasks.len() <= 1 {
 4614                        // If there are no more completion tasks and the last menu was
 4615                        // empty, we should hide it. If it was already hidden, we should
 4616                        // also show the copilot completion when available.
 4617                        drop(context_menu);
 4618                        if this.hide_context_menu(cx).is_none() {
 4619                            this.update_visible_inline_completion(cx);
 4620                        }
 4621                    }
 4622                })?;
 4623
 4624                Ok::<_, anyhow::Error>(())
 4625            }
 4626            .log_err()
 4627        });
 4628
 4629        self.completion_tasks.push((id, task));
 4630    }
 4631
 4632    pub fn confirm_completion(
 4633        &mut self,
 4634        action: &ConfirmCompletion,
 4635        cx: &mut ViewContext<Self>,
 4636    ) -> Option<Task<Result<()>>> {
 4637        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4638    }
 4639
 4640    pub fn compose_completion(
 4641        &mut self,
 4642        action: &ComposeCompletion,
 4643        cx: &mut ViewContext<Self>,
 4644    ) -> Option<Task<Result<()>>> {
 4645        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4646    }
 4647
 4648    fn do_completion(
 4649        &mut self,
 4650        item_ix: Option<usize>,
 4651        intent: CompletionIntent,
 4652        cx: &mut ViewContext<Editor>,
 4653    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4654        use language::ToOffset as _;
 4655
 4656        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4657            menu
 4658        } else {
 4659            return None;
 4660        };
 4661
 4662        let mat = completions_menu
 4663            .matches
 4664            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4665        let buffer_handle = completions_menu.buffer;
 4666        let completions = completions_menu.completions.read();
 4667        let completion = completions.get(mat.candidate_id)?;
 4668        cx.stop_propagation();
 4669
 4670        let snippet;
 4671        let text;
 4672
 4673        if completion.is_snippet() {
 4674            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4675            text = snippet.as_ref().unwrap().text.clone();
 4676        } else {
 4677            snippet = None;
 4678            text = completion.new_text.clone();
 4679        };
 4680        let selections = self.selections.all::<usize>(cx);
 4681        let buffer = buffer_handle.read(cx);
 4682        let old_range = completion.old_range.to_offset(buffer);
 4683        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4684
 4685        let newest_selection = self.selections.newest_anchor();
 4686        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4687            return None;
 4688        }
 4689
 4690        let lookbehind = newest_selection
 4691            .start
 4692            .text_anchor
 4693            .to_offset(buffer)
 4694            .saturating_sub(old_range.start);
 4695        let lookahead = old_range
 4696            .end
 4697            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4698        let mut common_prefix_len = old_text
 4699            .bytes()
 4700            .zip(text.bytes())
 4701            .take_while(|(a, b)| a == b)
 4702            .count();
 4703
 4704        let snapshot = self.buffer.read(cx).snapshot(cx);
 4705        let mut range_to_replace: Option<Range<isize>> = None;
 4706        let mut ranges = Vec::new();
 4707        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4708        for selection in &selections {
 4709            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4710                let start = selection.start.saturating_sub(lookbehind);
 4711                let end = selection.end + lookahead;
 4712                if selection.id == newest_selection.id {
 4713                    range_to_replace = Some(
 4714                        ((start + common_prefix_len) as isize - selection.start as isize)
 4715                            ..(end as isize - selection.start as isize),
 4716                    );
 4717                }
 4718                ranges.push(start + common_prefix_len..end);
 4719            } else {
 4720                common_prefix_len = 0;
 4721                ranges.clear();
 4722                ranges.extend(selections.iter().map(|s| {
 4723                    if s.id == newest_selection.id {
 4724                        range_to_replace = Some(
 4725                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4726                                - selection.start as isize
 4727                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4728                                    - selection.start as isize,
 4729                        );
 4730                        old_range.clone()
 4731                    } else {
 4732                        s.start..s.end
 4733                    }
 4734                }));
 4735                break;
 4736            }
 4737            if !self.linked_edit_ranges.is_empty() {
 4738                let start_anchor = snapshot.anchor_before(selection.head());
 4739                let end_anchor = snapshot.anchor_after(selection.tail());
 4740                if let Some(ranges) = self
 4741                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4742                {
 4743                    for (buffer, edits) in ranges {
 4744                        linked_edits.entry(buffer.clone()).or_default().extend(
 4745                            edits
 4746                                .into_iter()
 4747                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4748                        );
 4749                    }
 4750                }
 4751            }
 4752        }
 4753        let text = &text[common_prefix_len..];
 4754
 4755        cx.emit(EditorEvent::InputHandled {
 4756            utf16_range_to_replace: range_to_replace,
 4757            text: text.into(),
 4758        });
 4759
 4760        self.transact(cx, |this, cx| {
 4761            if let Some(mut snippet) = snippet {
 4762                snippet.text = text.to_string();
 4763                for tabstop in snippet
 4764                    .tabstops
 4765                    .iter_mut()
 4766                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4767                {
 4768                    tabstop.start -= common_prefix_len as isize;
 4769                    tabstop.end -= common_prefix_len as isize;
 4770                }
 4771
 4772                this.insert_snippet(&ranges, snippet, cx).log_err();
 4773            } else {
 4774                this.buffer.update(cx, |buffer, cx| {
 4775                    buffer.edit(
 4776                        ranges.iter().map(|range| (range.clone(), text)),
 4777                        this.autoindent_mode.clone(),
 4778                        cx,
 4779                    );
 4780                });
 4781            }
 4782            for (buffer, edits) in linked_edits {
 4783                buffer.update(cx, |buffer, cx| {
 4784                    let snapshot = buffer.snapshot();
 4785                    let edits = edits
 4786                        .into_iter()
 4787                        .map(|(range, text)| {
 4788                            use text::ToPoint as TP;
 4789                            let end_point = TP::to_point(&range.end, &snapshot);
 4790                            let start_point = TP::to_point(&range.start, &snapshot);
 4791                            (start_point..end_point, text)
 4792                        })
 4793                        .sorted_by_key(|(range, _)| range.start)
 4794                        .collect::<Vec<_>>();
 4795                    buffer.edit(edits, None, cx);
 4796                })
 4797            }
 4798
 4799            this.refresh_inline_completion(true, false, cx);
 4800        });
 4801
 4802        let show_new_completions_on_confirm = completion
 4803            .confirm
 4804            .as_ref()
 4805            .map_or(false, |confirm| confirm(intent, cx));
 4806        if show_new_completions_on_confirm {
 4807            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4808        }
 4809
 4810        let provider = self.completion_provider.as_ref()?;
 4811        let apply_edits = provider.apply_additional_edits_for_completion(
 4812            buffer_handle,
 4813            completion.clone(),
 4814            true,
 4815            cx,
 4816        );
 4817
 4818        let editor_settings = EditorSettings::get_global(cx);
 4819        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4820            // After the code completion is finished, users often want to know what signatures are needed.
 4821            // so we should automatically call signature_help
 4822            self.show_signature_help(&ShowSignatureHelp, cx);
 4823        }
 4824
 4825        Some(cx.foreground_executor().spawn(async move {
 4826            apply_edits.await?;
 4827            Ok(())
 4828        }))
 4829    }
 4830
 4831    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4832        let mut context_menu = self.context_menu.write();
 4833        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4834            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4835                // Toggle if we're selecting the same one
 4836                *context_menu = None;
 4837                cx.notify();
 4838                return;
 4839            } else {
 4840                // Otherwise, clear it and start a new one
 4841                *context_menu = None;
 4842                cx.notify();
 4843            }
 4844        }
 4845        drop(context_menu);
 4846        let snapshot = self.snapshot(cx);
 4847        let deployed_from_indicator = action.deployed_from_indicator;
 4848        let mut task = self.code_actions_task.take();
 4849        let action = action.clone();
 4850        cx.spawn(|editor, mut cx| async move {
 4851            while let Some(prev_task) = task {
 4852                prev_task.await.log_err();
 4853                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4854            }
 4855
 4856            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4857                if editor.focus_handle.is_focused(cx) {
 4858                    let multibuffer_point = action
 4859                        .deployed_from_indicator
 4860                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4861                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4862                    let (buffer, buffer_row) = snapshot
 4863                        .buffer_snapshot
 4864                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4865                        .and_then(|(buffer_snapshot, range)| {
 4866                            editor
 4867                                .buffer
 4868                                .read(cx)
 4869                                .buffer(buffer_snapshot.remote_id())
 4870                                .map(|buffer| (buffer, range.start.row))
 4871                        })?;
 4872                    let (_, code_actions) = editor
 4873                        .available_code_actions
 4874                        .clone()
 4875                        .and_then(|(location, code_actions)| {
 4876                            let snapshot = location.buffer.read(cx).snapshot();
 4877                            let point_range = location.range.to_point(&snapshot);
 4878                            let point_range = point_range.start.row..=point_range.end.row;
 4879                            if point_range.contains(&buffer_row) {
 4880                                Some((location, code_actions))
 4881                            } else {
 4882                                None
 4883                            }
 4884                        })
 4885                        .unzip();
 4886                    let buffer_id = buffer.read(cx).remote_id();
 4887                    let tasks = editor
 4888                        .tasks
 4889                        .get(&(buffer_id, buffer_row))
 4890                        .map(|t| Arc::new(t.to_owned()));
 4891                    if tasks.is_none() && code_actions.is_none() {
 4892                        return None;
 4893                    }
 4894
 4895                    editor.completion_tasks.clear();
 4896                    editor.discard_inline_completion(false, cx);
 4897                    let task_context =
 4898                        tasks
 4899                            .as_ref()
 4900                            .zip(editor.project.clone())
 4901                            .map(|(tasks, project)| {
 4902                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4903                            });
 4904
 4905                    Some(cx.spawn(|editor, mut cx| async move {
 4906                        let task_context = match task_context {
 4907                            Some(task_context) => task_context.await,
 4908                            None => None,
 4909                        };
 4910                        let resolved_tasks =
 4911                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4912                                Arc::new(ResolvedTasks {
 4913                                    templates: tasks.resolve(&task_context).collect(),
 4914                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4915                                        multibuffer_point.row,
 4916                                        tasks.column,
 4917                                    )),
 4918                                })
 4919                            });
 4920                        let spawn_straight_away = resolved_tasks
 4921                            .as_ref()
 4922                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4923                            && code_actions
 4924                                .as_ref()
 4925                                .map_or(true, |actions| actions.is_empty());
 4926                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4927                            *editor.context_menu.write() =
 4928                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4929                                    buffer,
 4930                                    actions: CodeActionContents {
 4931                                        tasks: resolved_tasks,
 4932                                        actions: code_actions,
 4933                                    },
 4934                                    selected_item: Default::default(),
 4935                                    scroll_handle: UniformListScrollHandle::default(),
 4936                                    deployed_from_indicator,
 4937                                }));
 4938                            if spawn_straight_away {
 4939                                if let Some(task) = editor.confirm_code_action(
 4940                                    &ConfirmCodeAction { item_ix: Some(0) },
 4941                                    cx,
 4942                                ) {
 4943                                    cx.notify();
 4944                                    return task;
 4945                                }
 4946                            }
 4947                            cx.notify();
 4948                            Task::ready(Ok(()))
 4949                        }) {
 4950                            task.await
 4951                        } else {
 4952                            Ok(())
 4953                        }
 4954                    }))
 4955                } else {
 4956                    Some(Task::ready(Ok(())))
 4957                }
 4958            })?;
 4959            if let Some(task) = spawned_test_task {
 4960                task.await?;
 4961            }
 4962
 4963            Ok::<_, anyhow::Error>(())
 4964        })
 4965        .detach_and_log_err(cx);
 4966    }
 4967
 4968    pub fn confirm_code_action(
 4969        &mut self,
 4970        action: &ConfirmCodeAction,
 4971        cx: &mut ViewContext<Self>,
 4972    ) -> Option<Task<Result<()>>> {
 4973        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4974            menu
 4975        } else {
 4976            return None;
 4977        };
 4978        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4979        let action = actions_menu.actions.get(action_ix)?;
 4980        let title = action.label();
 4981        let buffer = actions_menu.buffer;
 4982        let workspace = self.workspace()?;
 4983
 4984        match action {
 4985            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4986                workspace.update(cx, |workspace, cx| {
 4987                    workspace::tasks::schedule_resolved_task(
 4988                        workspace,
 4989                        task_source_kind,
 4990                        resolved_task,
 4991                        false,
 4992                        cx,
 4993                    );
 4994
 4995                    Some(Task::ready(Ok(())))
 4996                })
 4997            }
 4998            CodeActionsItem::CodeAction {
 4999                excerpt_id,
 5000                action,
 5001                provider,
 5002            } => {
 5003                let apply_code_action =
 5004                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 5005                let workspace = workspace.downgrade();
 5006                Some(cx.spawn(|editor, cx| async move {
 5007                    let project_transaction = apply_code_action.await?;
 5008                    Self::open_project_transaction(
 5009                        &editor,
 5010                        workspace,
 5011                        project_transaction,
 5012                        title,
 5013                        cx,
 5014                    )
 5015                    .await
 5016                }))
 5017            }
 5018        }
 5019    }
 5020
 5021    pub async fn open_project_transaction(
 5022        this: &WeakView<Editor>,
 5023        workspace: WeakView<Workspace>,
 5024        transaction: ProjectTransaction,
 5025        title: String,
 5026        mut cx: AsyncWindowContext,
 5027    ) -> Result<()> {
 5028        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5029        cx.update(|cx| {
 5030            entries.sort_unstable_by_key(|(buffer, _)| {
 5031                buffer.read(cx).file().map(|f| f.path().clone())
 5032            });
 5033        })?;
 5034
 5035        // If the project transaction's edits are all contained within this editor, then
 5036        // avoid opening a new editor to display them.
 5037
 5038        if let Some((buffer, transaction)) = entries.first() {
 5039            if entries.len() == 1 {
 5040                let excerpt = this.update(&mut cx, |editor, cx| {
 5041                    editor
 5042                        .buffer()
 5043                        .read(cx)
 5044                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5045                })?;
 5046                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5047                    if excerpted_buffer == *buffer {
 5048                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 5049                            let excerpt_range = excerpt_range.to_offset(buffer);
 5050                            buffer
 5051                                .edited_ranges_for_transaction::<usize>(transaction)
 5052                                .all(|range| {
 5053                                    excerpt_range.start <= range.start
 5054                                        && excerpt_range.end >= range.end
 5055                                })
 5056                        })?;
 5057
 5058                        if all_edits_within_excerpt {
 5059                            return Ok(());
 5060                        }
 5061                    }
 5062                }
 5063            }
 5064        } else {
 5065            return Ok(());
 5066        }
 5067
 5068        let mut ranges_to_highlight = Vec::new();
 5069        let excerpt_buffer = cx.new_model(|cx| {
 5070            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5071            for (buffer_handle, transaction) in &entries {
 5072                let buffer = buffer_handle.read(cx);
 5073                ranges_to_highlight.extend(
 5074                    multibuffer.push_excerpts_with_context_lines(
 5075                        buffer_handle.clone(),
 5076                        buffer
 5077                            .edited_ranges_for_transaction::<usize>(transaction)
 5078                            .collect(),
 5079                        DEFAULT_MULTIBUFFER_CONTEXT,
 5080                        cx,
 5081                    ),
 5082                );
 5083            }
 5084            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5085            multibuffer
 5086        })?;
 5087
 5088        workspace.update(&mut cx, |workspace, cx| {
 5089            let project = workspace.project().clone();
 5090            let editor =
 5091                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5092            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5093            editor.update(cx, |editor, cx| {
 5094                editor.highlight_background::<Self>(
 5095                    &ranges_to_highlight,
 5096                    |theme| theme.editor_highlighted_line_background,
 5097                    cx,
 5098                );
 5099            });
 5100        })?;
 5101
 5102        Ok(())
 5103    }
 5104
 5105    pub fn clear_code_action_providers(&mut self) {
 5106        self.code_action_providers.clear();
 5107        self.available_code_actions.take();
 5108    }
 5109
 5110    pub fn push_code_action_provider(
 5111        &mut self,
 5112        provider: Arc<dyn CodeActionProvider>,
 5113        cx: &mut ViewContext<Self>,
 5114    ) {
 5115        self.code_action_providers.push(provider);
 5116        self.refresh_code_actions(cx);
 5117    }
 5118
 5119    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5120        let buffer = self.buffer.read(cx);
 5121        let newest_selection = self.selections.newest_anchor().clone();
 5122        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5123        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5124        if start_buffer != end_buffer {
 5125            return None;
 5126        }
 5127
 5128        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5129            cx.background_executor()
 5130                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5131                .await;
 5132
 5133            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5134                let providers = this.code_action_providers.clone();
 5135                let tasks = this
 5136                    .code_action_providers
 5137                    .iter()
 5138                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5139                    .collect::<Vec<_>>();
 5140                (providers, tasks)
 5141            })?;
 5142
 5143            let mut actions = Vec::new();
 5144            for (provider, provider_actions) in
 5145                providers.into_iter().zip(future::join_all(tasks).await)
 5146            {
 5147                if let Some(provider_actions) = provider_actions.log_err() {
 5148                    actions.extend(provider_actions.into_iter().map(|action| {
 5149                        AvailableCodeAction {
 5150                            excerpt_id: newest_selection.start.excerpt_id,
 5151                            action,
 5152                            provider: provider.clone(),
 5153                        }
 5154                    }));
 5155                }
 5156            }
 5157
 5158            this.update(&mut cx, |this, cx| {
 5159                this.available_code_actions = if actions.is_empty() {
 5160                    None
 5161                } else {
 5162                    Some((
 5163                        Location {
 5164                            buffer: start_buffer,
 5165                            range: start..end,
 5166                        },
 5167                        actions.into(),
 5168                    ))
 5169                };
 5170                cx.notify();
 5171            })
 5172        }));
 5173        None
 5174    }
 5175
 5176    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5177        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5178            self.show_git_blame_inline = false;
 5179
 5180            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5181                cx.background_executor().timer(delay).await;
 5182
 5183                this.update(&mut cx, |this, cx| {
 5184                    this.show_git_blame_inline = true;
 5185                    cx.notify();
 5186                })
 5187                .log_err();
 5188            }));
 5189        }
 5190    }
 5191
 5192    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5193        if self.pending_rename.is_some() {
 5194            return None;
 5195        }
 5196
 5197        let provider = self.semantics_provider.clone()?;
 5198        let buffer = self.buffer.read(cx);
 5199        let newest_selection = self.selections.newest_anchor().clone();
 5200        let cursor_position = newest_selection.head();
 5201        let (cursor_buffer, cursor_buffer_position) =
 5202            buffer.text_anchor_for_position(cursor_position, cx)?;
 5203        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5204        if cursor_buffer != tail_buffer {
 5205            return None;
 5206        }
 5207
 5208        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5209            cx.background_executor()
 5210                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5211                .await;
 5212
 5213            let highlights = if let Some(highlights) = cx
 5214                .update(|cx| {
 5215                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5216                })
 5217                .ok()
 5218                .flatten()
 5219            {
 5220                highlights.await.log_err()
 5221            } else {
 5222                None
 5223            };
 5224
 5225            if let Some(highlights) = highlights {
 5226                this.update(&mut cx, |this, cx| {
 5227                    if this.pending_rename.is_some() {
 5228                        return;
 5229                    }
 5230
 5231                    let buffer_id = cursor_position.buffer_id;
 5232                    let buffer = this.buffer.read(cx);
 5233                    if !buffer
 5234                        .text_anchor_for_position(cursor_position, cx)
 5235                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5236                    {
 5237                        return;
 5238                    }
 5239
 5240                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5241                    let mut write_ranges = Vec::new();
 5242                    let mut read_ranges = Vec::new();
 5243                    for highlight in highlights {
 5244                        for (excerpt_id, excerpt_range) in
 5245                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5246                        {
 5247                            let start = highlight
 5248                                .range
 5249                                .start
 5250                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5251                            let end = highlight
 5252                                .range
 5253                                .end
 5254                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5255                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5256                                continue;
 5257                            }
 5258
 5259                            let range = Anchor {
 5260                                buffer_id,
 5261                                excerpt_id,
 5262                                text_anchor: start,
 5263                            }..Anchor {
 5264                                buffer_id,
 5265                                excerpt_id,
 5266                                text_anchor: end,
 5267                            };
 5268                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5269                                write_ranges.push(range);
 5270                            } else {
 5271                                read_ranges.push(range);
 5272                            }
 5273                        }
 5274                    }
 5275
 5276                    this.highlight_background::<DocumentHighlightRead>(
 5277                        &read_ranges,
 5278                        |theme| theme.editor_document_highlight_read_background,
 5279                        cx,
 5280                    );
 5281                    this.highlight_background::<DocumentHighlightWrite>(
 5282                        &write_ranges,
 5283                        |theme| theme.editor_document_highlight_write_background,
 5284                        cx,
 5285                    );
 5286                    cx.notify();
 5287                })
 5288                .log_err();
 5289            }
 5290        }));
 5291        None
 5292    }
 5293
 5294    pub fn refresh_inline_completion(
 5295        &mut self,
 5296        debounce: bool,
 5297        user_requested: bool,
 5298        cx: &mut ViewContext<Self>,
 5299    ) -> Option<()> {
 5300        let provider = self.inline_completion_provider()?;
 5301        let cursor = self.selections.newest_anchor().head();
 5302        let (buffer, cursor_buffer_position) =
 5303            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5304
 5305        if !user_requested
 5306            && (!self.enable_inline_completions
 5307                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5308        {
 5309            self.discard_inline_completion(false, cx);
 5310            return None;
 5311        }
 5312
 5313        self.update_visible_inline_completion(cx);
 5314        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5315        Some(())
 5316    }
 5317
 5318    fn cycle_inline_completion(
 5319        &mut self,
 5320        direction: Direction,
 5321        cx: &mut ViewContext<Self>,
 5322    ) -> Option<()> {
 5323        let provider = self.inline_completion_provider()?;
 5324        let cursor = self.selections.newest_anchor().head();
 5325        let (buffer, cursor_buffer_position) =
 5326            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5327        if !self.enable_inline_completions
 5328            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5329        {
 5330            return None;
 5331        }
 5332
 5333        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5334        self.update_visible_inline_completion(cx);
 5335
 5336        Some(())
 5337    }
 5338
 5339    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5340        if !self.has_active_inline_completion(cx) {
 5341            self.refresh_inline_completion(false, true, cx);
 5342            return;
 5343        }
 5344
 5345        self.update_visible_inline_completion(cx);
 5346    }
 5347
 5348    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5349        self.show_cursor_names(cx);
 5350    }
 5351
 5352    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5353        self.show_cursor_names = true;
 5354        cx.notify();
 5355        cx.spawn(|this, mut cx| async move {
 5356            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5357            this.update(&mut cx, |this, cx| {
 5358                this.show_cursor_names = false;
 5359                cx.notify()
 5360            })
 5361            .ok()
 5362        })
 5363        .detach();
 5364    }
 5365
 5366    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5367        if self.has_active_inline_completion(cx) {
 5368            self.cycle_inline_completion(Direction::Next, cx);
 5369        } else {
 5370            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5371            if is_copilot_disabled {
 5372                cx.propagate();
 5373            }
 5374        }
 5375    }
 5376
 5377    pub fn previous_inline_completion(
 5378        &mut self,
 5379        _: &PreviousInlineCompletion,
 5380        cx: &mut ViewContext<Self>,
 5381    ) {
 5382        if self.has_active_inline_completion(cx) {
 5383            self.cycle_inline_completion(Direction::Prev, cx);
 5384        } else {
 5385            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5386            if is_copilot_disabled {
 5387                cx.propagate();
 5388            }
 5389        }
 5390    }
 5391
 5392    pub fn accept_inline_completion(
 5393        &mut self,
 5394        _: &AcceptInlineCompletion,
 5395        cx: &mut ViewContext<Self>,
 5396    ) {
 5397        let Some(completion) = self.take_active_inline_completion(cx) else {
 5398            return;
 5399        };
 5400        if let Some(provider) = self.inline_completion_provider() {
 5401            provider.accept(cx);
 5402        }
 5403
 5404        cx.emit(EditorEvent::InputHandled {
 5405            utf16_range_to_replace: None,
 5406            text: completion.text.to_string().into(),
 5407        });
 5408
 5409        if let Some(range) = completion.delete_range {
 5410            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5411        }
 5412        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5413        self.refresh_inline_completion(true, true, cx);
 5414        cx.notify();
 5415    }
 5416
 5417    pub fn accept_partial_inline_completion(
 5418        &mut self,
 5419        _: &AcceptPartialInlineCompletion,
 5420        cx: &mut ViewContext<Self>,
 5421    ) {
 5422        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5423            if let Some(completion) = self.take_active_inline_completion(cx) {
 5424                let mut partial_completion = completion
 5425                    .text
 5426                    .chars()
 5427                    .by_ref()
 5428                    .take_while(|c| c.is_alphabetic())
 5429                    .collect::<String>();
 5430                if partial_completion.is_empty() {
 5431                    partial_completion = completion
 5432                        .text
 5433                        .chars()
 5434                        .by_ref()
 5435                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5436                        .collect::<String>();
 5437                }
 5438
 5439                cx.emit(EditorEvent::InputHandled {
 5440                    utf16_range_to_replace: None,
 5441                    text: partial_completion.clone().into(),
 5442                });
 5443
 5444                if let Some(range) = completion.delete_range {
 5445                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5446                }
 5447                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5448
 5449                self.refresh_inline_completion(true, true, cx);
 5450                cx.notify();
 5451            }
 5452        }
 5453    }
 5454
 5455    fn discard_inline_completion(
 5456        &mut self,
 5457        should_report_inline_completion_event: bool,
 5458        cx: &mut ViewContext<Self>,
 5459    ) -> bool {
 5460        if let Some(provider) = self.inline_completion_provider() {
 5461            provider.discard(should_report_inline_completion_event, cx);
 5462        }
 5463
 5464        self.take_active_inline_completion(cx).is_some()
 5465    }
 5466
 5467    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5468        if let Some(completion) = self.active_inline_completion.as_ref() {
 5469            let buffer = self.buffer.read(cx).read(cx);
 5470            completion.position.is_valid(&buffer)
 5471        } else {
 5472            false
 5473        }
 5474    }
 5475
 5476    fn take_active_inline_completion(
 5477        &mut self,
 5478        cx: &mut ViewContext<Self>,
 5479    ) -> Option<CompletionState> {
 5480        let completion = self.active_inline_completion.take()?;
 5481        let render_inlay_ids = completion.render_inlay_ids.clone();
 5482        self.display_map.update(cx, |map, cx| {
 5483            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5484        });
 5485        let buffer = self.buffer.read(cx).read(cx);
 5486
 5487        if completion.position.is_valid(&buffer) {
 5488            Some(completion)
 5489        } else {
 5490            None
 5491        }
 5492    }
 5493
 5494    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5495        let selection = self.selections.newest_anchor();
 5496        let cursor = selection.head();
 5497
 5498        let excerpt_id = cursor.excerpt_id;
 5499
 5500        if self.context_menu.read().is_none()
 5501            && self.completion_tasks.is_empty()
 5502            && selection.start == selection.end
 5503        {
 5504            if let Some(provider) = self.inline_completion_provider() {
 5505                if let Some((buffer, cursor_buffer_position)) =
 5506                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5507                {
 5508                    if let Some(proposal) =
 5509                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5510                    {
 5511                        let mut to_remove = Vec::new();
 5512                        if let Some(completion) = self.active_inline_completion.take() {
 5513                            to_remove.extend(completion.render_inlay_ids.iter());
 5514                        }
 5515
 5516                        let to_add = proposal
 5517                            .inlays
 5518                            .iter()
 5519                            .filter_map(|inlay| {
 5520                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5521                                let id = post_inc(&mut self.next_inlay_id);
 5522                                match inlay {
 5523                                    InlayProposal::Hint(position, hint) => {
 5524                                        let position =
 5525                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5526                                        Some(Inlay::hint(id, position, hint))
 5527                                    }
 5528                                    InlayProposal::Suggestion(position, text) => {
 5529                                        let position =
 5530                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5531                                        Some(Inlay::suggestion(id, position, text.clone()))
 5532                                    }
 5533                                }
 5534                            })
 5535                            .collect_vec();
 5536
 5537                        self.active_inline_completion = Some(CompletionState {
 5538                            position: cursor,
 5539                            text: proposal.text,
 5540                            delete_range: proposal.delete_range.and_then(|range| {
 5541                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5542                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5543                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5544                                Some(start?..end?)
 5545                            }),
 5546                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5547                        });
 5548
 5549                        self.display_map
 5550                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5551
 5552                        cx.notify();
 5553                        return;
 5554                    }
 5555                }
 5556            }
 5557        }
 5558
 5559        self.discard_inline_completion(false, cx);
 5560    }
 5561
 5562    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5563        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5564    }
 5565
 5566    fn render_code_actions_indicator(
 5567        &self,
 5568        _style: &EditorStyle,
 5569        row: DisplayRow,
 5570        is_active: bool,
 5571        cx: &mut ViewContext<Self>,
 5572    ) -> Option<IconButton> {
 5573        if self.available_code_actions.is_some() {
 5574            Some(
 5575                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5576                    .shape(ui::IconButtonShape::Square)
 5577                    .icon_size(IconSize::XSmall)
 5578                    .icon_color(Color::Muted)
 5579                    .selected(is_active)
 5580                    .tooltip({
 5581                        let focus_handle = self.focus_handle.clone();
 5582                        move |cx| {
 5583                            Tooltip::for_action_in(
 5584                                "Toggle Code Actions",
 5585                                &ToggleCodeActions {
 5586                                    deployed_from_indicator: None,
 5587                                },
 5588                                &focus_handle,
 5589                                cx,
 5590                            )
 5591                        }
 5592                    })
 5593                    .on_click(cx.listener(move |editor, _e, cx| {
 5594                        editor.focus(cx);
 5595                        editor.toggle_code_actions(
 5596                            &ToggleCodeActions {
 5597                                deployed_from_indicator: Some(row),
 5598                            },
 5599                            cx,
 5600                        );
 5601                    })),
 5602            )
 5603        } else {
 5604            None
 5605        }
 5606    }
 5607
 5608    fn clear_tasks(&mut self) {
 5609        self.tasks.clear()
 5610    }
 5611
 5612    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5613        if self.tasks.insert(key, value).is_some() {
 5614            // This case should hopefully be rare, but just in case...
 5615            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5616        }
 5617    }
 5618
 5619    fn build_tasks_context(
 5620        project: &Model<Project>,
 5621        buffer: &Model<Buffer>,
 5622        buffer_row: u32,
 5623        tasks: &Arc<RunnableTasks>,
 5624        cx: &mut ViewContext<Self>,
 5625    ) -> Task<Option<task::TaskContext>> {
 5626        let position = Point::new(buffer_row, tasks.column);
 5627        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5628        let location = Location {
 5629            buffer: buffer.clone(),
 5630            range: range_start..range_start,
 5631        };
 5632        // Fill in the environmental variables from the tree-sitter captures
 5633        let mut captured_task_variables = TaskVariables::default();
 5634        for (capture_name, value) in tasks.extra_variables.clone() {
 5635            captured_task_variables.insert(
 5636                task::VariableName::Custom(capture_name.into()),
 5637                value.clone(),
 5638            );
 5639        }
 5640        project.update(cx, |project, cx| {
 5641            project.task_store().update(cx, |task_store, cx| {
 5642                task_store.task_context_for_location(captured_task_variables, location, cx)
 5643            })
 5644        })
 5645    }
 5646
 5647    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5648        let Some((workspace, _)) = self.workspace.clone() else {
 5649            return;
 5650        };
 5651        let Some(project) = self.project.clone() else {
 5652            return;
 5653        };
 5654
 5655        // Try to find a closest, enclosing node using tree-sitter that has a
 5656        // task
 5657        let Some((buffer, buffer_row, tasks)) = self
 5658            .find_enclosing_node_task(cx)
 5659            // Or find the task that's closest in row-distance.
 5660            .or_else(|| self.find_closest_task(cx))
 5661        else {
 5662            return;
 5663        };
 5664
 5665        let reveal_strategy = action.reveal;
 5666        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5667        cx.spawn(|_, mut cx| async move {
 5668            let context = task_context.await?;
 5669            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5670
 5671            let resolved = resolved_task.resolved.as_mut()?;
 5672            resolved.reveal = reveal_strategy;
 5673
 5674            workspace
 5675                .update(&mut cx, |workspace, cx| {
 5676                    workspace::tasks::schedule_resolved_task(
 5677                        workspace,
 5678                        task_source_kind,
 5679                        resolved_task,
 5680                        false,
 5681                        cx,
 5682                    );
 5683                })
 5684                .ok()
 5685        })
 5686        .detach();
 5687    }
 5688
 5689    fn find_closest_task(
 5690        &mut self,
 5691        cx: &mut ViewContext<Self>,
 5692    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5693        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5694
 5695        let ((buffer_id, row), tasks) = self
 5696            .tasks
 5697            .iter()
 5698            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5699
 5700        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5701        let tasks = Arc::new(tasks.to_owned());
 5702        Some((buffer, *row, tasks))
 5703    }
 5704
 5705    fn find_enclosing_node_task(
 5706        &mut self,
 5707        cx: &mut ViewContext<Self>,
 5708    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5709        let snapshot = self.buffer.read(cx).snapshot(cx);
 5710        let offset = self.selections.newest::<usize>(cx).head();
 5711        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5712        let buffer_id = excerpt.buffer().remote_id();
 5713
 5714        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5715        let mut cursor = layer.node().walk();
 5716
 5717        while cursor.goto_first_child_for_byte(offset).is_some() {
 5718            if cursor.node().end_byte() == offset {
 5719                cursor.goto_next_sibling();
 5720            }
 5721        }
 5722
 5723        // Ascend to the smallest ancestor that contains the range and has a task.
 5724        loop {
 5725            let node = cursor.node();
 5726            let node_range = node.byte_range();
 5727            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5728
 5729            // Check if this node contains our offset
 5730            if node_range.start <= offset && node_range.end >= offset {
 5731                // If it contains offset, check for task
 5732                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5733                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5734                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5735                }
 5736            }
 5737
 5738            if !cursor.goto_parent() {
 5739                break;
 5740            }
 5741        }
 5742        None
 5743    }
 5744
 5745    fn render_run_indicator(
 5746        &self,
 5747        _style: &EditorStyle,
 5748        is_active: bool,
 5749        row: DisplayRow,
 5750        cx: &mut ViewContext<Self>,
 5751    ) -> IconButton {
 5752        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5753            .shape(ui::IconButtonShape::Square)
 5754            .icon_size(IconSize::XSmall)
 5755            .icon_color(Color::Muted)
 5756            .selected(is_active)
 5757            .on_click(cx.listener(move |editor, _e, cx| {
 5758                editor.focus(cx);
 5759                editor.toggle_code_actions(
 5760                    &ToggleCodeActions {
 5761                        deployed_from_indicator: Some(row),
 5762                    },
 5763                    cx,
 5764                );
 5765            }))
 5766    }
 5767
 5768    pub fn context_menu_visible(&self) -> bool {
 5769        self.context_menu
 5770            .read()
 5771            .as_ref()
 5772            .map_or(false, |menu| menu.visible())
 5773    }
 5774
 5775    fn render_context_menu(
 5776        &self,
 5777        cursor_position: DisplayPoint,
 5778        style: &EditorStyle,
 5779        max_height: Pixels,
 5780        cx: &mut ViewContext<Editor>,
 5781    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5782        self.context_menu.read().as_ref().map(|menu| {
 5783            menu.render(
 5784                cursor_position,
 5785                style,
 5786                max_height,
 5787                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5788                cx,
 5789            )
 5790        })
 5791    }
 5792
 5793    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5794        cx.notify();
 5795        self.completion_tasks.clear();
 5796        let context_menu = self.context_menu.write().take();
 5797        if context_menu.is_some() {
 5798            self.update_visible_inline_completion(cx);
 5799        }
 5800        context_menu
 5801    }
 5802
 5803    fn show_snippet_choices(
 5804        &mut self,
 5805        choices: &Vec<String>,
 5806        selection: Range<Anchor>,
 5807        cx: &mut ViewContext<Self>,
 5808    ) {
 5809        if selection.start.buffer_id.is_none() {
 5810            return;
 5811        }
 5812        let buffer_id = selection.start.buffer_id.unwrap();
 5813        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5814        let id = post_inc(&mut self.next_completion_id);
 5815
 5816        if let Some(buffer) = buffer {
 5817            *self.context_menu.write() = Some(ContextMenu::Completions(
 5818                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
 5819                    .suppress_documentation_resolution(),
 5820            ));
 5821        }
 5822    }
 5823
 5824    pub fn insert_snippet(
 5825        &mut self,
 5826        insertion_ranges: &[Range<usize>],
 5827        snippet: Snippet,
 5828        cx: &mut ViewContext<Self>,
 5829    ) -> Result<()> {
 5830        struct Tabstop<T> {
 5831            is_end_tabstop: bool,
 5832            ranges: Vec<Range<T>>,
 5833            choices: Option<Vec<String>>,
 5834        }
 5835
 5836        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5837            let snippet_text: Arc<str> = snippet.text.clone().into();
 5838            buffer.edit(
 5839                insertion_ranges
 5840                    .iter()
 5841                    .cloned()
 5842                    .map(|range| (range, snippet_text.clone())),
 5843                Some(AutoindentMode::EachLine),
 5844                cx,
 5845            );
 5846
 5847            let snapshot = &*buffer.read(cx);
 5848            let snippet = &snippet;
 5849            snippet
 5850                .tabstops
 5851                .iter()
 5852                .map(|tabstop| {
 5853                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5854                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5855                    });
 5856                    let mut tabstop_ranges = tabstop
 5857                        .ranges
 5858                        .iter()
 5859                        .flat_map(|tabstop_range| {
 5860                            let mut delta = 0_isize;
 5861                            insertion_ranges.iter().map(move |insertion_range| {
 5862                                let insertion_start = insertion_range.start as isize + delta;
 5863                                delta +=
 5864                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5865
 5866                                let start = ((insertion_start + tabstop_range.start) as usize)
 5867                                    .min(snapshot.len());
 5868                                let end = ((insertion_start + tabstop_range.end) as usize)
 5869                                    .min(snapshot.len());
 5870                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5871                            })
 5872                        })
 5873                        .collect::<Vec<_>>();
 5874                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5875
 5876                    Tabstop {
 5877                        is_end_tabstop,
 5878                        ranges: tabstop_ranges,
 5879                        choices: tabstop.choices.clone(),
 5880                    }
 5881                })
 5882                .collect::<Vec<_>>()
 5883        });
 5884        if let Some(tabstop) = tabstops.first() {
 5885            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5886                s.select_ranges(tabstop.ranges.iter().cloned());
 5887            });
 5888
 5889            if let Some(choices) = &tabstop.choices {
 5890                if let Some(selection) = tabstop.ranges.first() {
 5891                    self.show_snippet_choices(choices, selection.clone(), cx)
 5892                }
 5893            }
 5894
 5895            // If we're already at the last tabstop and it's at the end of the snippet,
 5896            // we're done, we don't need to keep the state around.
 5897            if !tabstop.is_end_tabstop {
 5898                let choices = tabstops
 5899                    .iter()
 5900                    .map(|tabstop| tabstop.choices.clone())
 5901                    .collect();
 5902
 5903                let ranges = tabstops
 5904                    .into_iter()
 5905                    .map(|tabstop| tabstop.ranges)
 5906                    .collect::<Vec<_>>();
 5907
 5908                self.snippet_stack.push(SnippetState {
 5909                    active_index: 0,
 5910                    ranges,
 5911                    choices,
 5912                });
 5913            }
 5914
 5915            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5916            if self.autoclose_regions.is_empty() {
 5917                let snapshot = self.buffer.read(cx).snapshot(cx);
 5918                for selection in &mut self.selections.all::<Point>(cx) {
 5919                    let selection_head = selection.head();
 5920                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5921                        continue;
 5922                    };
 5923
 5924                    let mut bracket_pair = None;
 5925                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5926                    let prev_chars = snapshot
 5927                        .reversed_chars_at(selection_head)
 5928                        .collect::<String>();
 5929                    for (pair, enabled) in scope.brackets() {
 5930                        if enabled
 5931                            && pair.close
 5932                            && prev_chars.starts_with(pair.start.as_str())
 5933                            && next_chars.starts_with(pair.end.as_str())
 5934                        {
 5935                            bracket_pair = Some(pair.clone());
 5936                            break;
 5937                        }
 5938                    }
 5939                    if let Some(pair) = bracket_pair {
 5940                        let start = snapshot.anchor_after(selection_head);
 5941                        let end = snapshot.anchor_after(selection_head);
 5942                        self.autoclose_regions.push(AutocloseRegion {
 5943                            selection_id: selection.id,
 5944                            range: start..end,
 5945                            pair,
 5946                        });
 5947                    }
 5948                }
 5949            }
 5950        }
 5951        Ok(())
 5952    }
 5953
 5954    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5955        self.move_to_snippet_tabstop(Bias::Right, cx)
 5956    }
 5957
 5958    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5959        self.move_to_snippet_tabstop(Bias::Left, cx)
 5960    }
 5961
 5962    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5963        if let Some(mut snippet) = self.snippet_stack.pop() {
 5964            match bias {
 5965                Bias::Left => {
 5966                    if snippet.active_index > 0 {
 5967                        snippet.active_index -= 1;
 5968                    } else {
 5969                        self.snippet_stack.push(snippet);
 5970                        return false;
 5971                    }
 5972                }
 5973                Bias::Right => {
 5974                    if snippet.active_index + 1 < snippet.ranges.len() {
 5975                        snippet.active_index += 1;
 5976                    } else {
 5977                        self.snippet_stack.push(snippet);
 5978                        return false;
 5979                    }
 5980                }
 5981            }
 5982            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5983                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5984                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5985                });
 5986
 5987                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5988                    if let Some(selection) = current_ranges.first() {
 5989                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5990                    }
 5991                }
 5992
 5993                // If snippet state is not at the last tabstop, push it back on the stack
 5994                if snippet.active_index + 1 < snippet.ranges.len() {
 5995                    self.snippet_stack.push(snippet);
 5996                }
 5997                return true;
 5998            }
 5999        }
 6000
 6001        false
 6002    }
 6003
 6004    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 6005        self.transact(cx, |this, cx| {
 6006            this.select_all(&SelectAll, cx);
 6007            this.insert("", cx);
 6008        });
 6009    }
 6010
 6011    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 6012        self.transact(cx, |this, cx| {
 6013            this.select_autoclose_pair(cx);
 6014            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6015            if !this.linked_edit_ranges.is_empty() {
 6016                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6017                let snapshot = this.buffer.read(cx).snapshot(cx);
 6018
 6019                for selection in selections.iter() {
 6020                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6021                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6022                    if selection_start.buffer_id != selection_end.buffer_id {
 6023                        continue;
 6024                    }
 6025                    if let Some(ranges) =
 6026                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6027                    {
 6028                        for (buffer, entries) in ranges {
 6029                            linked_ranges.entry(buffer).or_default().extend(entries);
 6030                        }
 6031                    }
 6032                }
 6033            }
 6034
 6035            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6036            if !this.selections.line_mode {
 6037                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6038                for selection in &mut selections {
 6039                    if selection.is_empty() {
 6040                        let old_head = selection.head();
 6041                        let mut new_head =
 6042                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6043                                .to_point(&display_map);
 6044                        if let Some((buffer, line_buffer_range)) = display_map
 6045                            .buffer_snapshot
 6046                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6047                        {
 6048                            let indent_size =
 6049                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6050                            let indent_len = match indent_size.kind {
 6051                                IndentKind::Space => {
 6052                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6053                                }
 6054                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6055                            };
 6056                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6057                                let indent_len = indent_len.get();
 6058                                new_head = cmp::min(
 6059                                    new_head,
 6060                                    MultiBufferPoint::new(
 6061                                        old_head.row,
 6062                                        ((old_head.column - 1) / indent_len) * indent_len,
 6063                                    ),
 6064                                );
 6065                            }
 6066                        }
 6067
 6068                        selection.set_head(new_head, SelectionGoal::None);
 6069                    }
 6070                }
 6071            }
 6072
 6073            this.signature_help_state.set_backspace_pressed(true);
 6074            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6075            this.insert("", cx);
 6076            let empty_str: Arc<str> = Arc::from("");
 6077            for (buffer, edits) in linked_ranges {
 6078                let snapshot = buffer.read(cx).snapshot();
 6079                use text::ToPoint as TP;
 6080
 6081                let edits = edits
 6082                    .into_iter()
 6083                    .map(|range| {
 6084                        let end_point = TP::to_point(&range.end, &snapshot);
 6085                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6086
 6087                        if end_point == start_point {
 6088                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6089                                .saturating_sub(1);
 6090                            start_point = TP::to_point(&offset, &snapshot);
 6091                        };
 6092
 6093                        (start_point..end_point, empty_str.clone())
 6094                    })
 6095                    .sorted_by_key(|(range, _)| range.start)
 6096                    .collect::<Vec<_>>();
 6097                buffer.update(cx, |this, cx| {
 6098                    this.edit(edits, None, cx);
 6099                })
 6100            }
 6101            this.refresh_inline_completion(true, false, cx);
 6102            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6103        });
 6104    }
 6105
 6106    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6107        self.transact(cx, |this, cx| {
 6108            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6109                let line_mode = s.line_mode;
 6110                s.move_with(|map, selection| {
 6111                    if selection.is_empty() && !line_mode {
 6112                        let cursor = movement::right(map, selection.head());
 6113                        selection.end = cursor;
 6114                        selection.reversed = true;
 6115                        selection.goal = SelectionGoal::None;
 6116                    }
 6117                })
 6118            });
 6119            this.insert("", cx);
 6120            this.refresh_inline_completion(true, false, cx);
 6121        });
 6122    }
 6123
 6124    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6125        if self.move_to_prev_snippet_tabstop(cx) {
 6126            return;
 6127        }
 6128
 6129        self.outdent(&Outdent, cx);
 6130    }
 6131
 6132    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6133        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6134            return;
 6135        }
 6136
 6137        let mut selections = self.selections.all_adjusted(cx);
 6138        let buffer = self.buffer.read(cx);
 6139        let snapshot = buffer.snapshot(cx);
 6140        let rows_iter = selections.iter().map(|s| s.head().row);
 6141        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6142
 6143        let mut edits = Vec::new();
 6144        let mut prev_edited_row = 0;
 6145        let mut row_delta = 0;
 6146        for selection in &mut selections {
 6147            if selection.start.row != prev_edited_row {
 6148                row_delta = 0;
 6149            }
 6150            prev_edited_row = selection.end.row;
 6151
 6152            // If the selection is non-empty, then increase the indentation of the selected lines.
 6153            if !selection.is_empty() {
 6154                row_delta =
 6155                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6156                continue;
 6157            }
 6158
 6159            // If the selection is empty and the cursor is in the leading whitespace before the
 6160            // suggested indentation, then auto-indent the line.
 6161            let cursor = selection.head();
 6162            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6163            if let Some(suggested_indent) =
 6164                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6165            {
 6166                if cursor.column < suggested_indent.len
 6167                    && cursor.column <= current_indent.len
 6168                    && current_indent.len <= suggested_indent.len
 6169                {
 6170                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6171                    selection.end = selection.start;
 6172                    if row_delta == 0 {
 6173                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6174                            cursor.row,
 6175                            current_indent,
 6176                            suggested_indent,
 6177                        ));
 6178                        row_delta = suggested_indent.len - current_indent.len;
 6179                    }
 6180                    continue;
 6181                }
 6182            }
 6183
 6184            // Otherwise, insert a hard or soft tab.
 6185            let settings = buffer.settings_at(cursor, cx);
 6186            let tab_size = if settings.hard_tabs {
 6187                IndentSize::tab()
 6188            } else {
 6189                let tab_size = settings.tab_size.get();
 6190                let char_column = snapshot
 6191                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6192                    .flat_map(str::chars)
 6193                    .count()
 6194                    + row_delta as usize;
 6195                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6196                IndentSize::spaces(chars_to_next_tab_stop)
 6197            };
 6198            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6199            selection.end = selection.start;
 6200            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6201            row_delta += tab_size.len;
 6202        }
 6203
 6204        self.transact(cx, |this, cx| {
 6205            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6206            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6207            this.refresh_inline_completion(true, false, cx);
 6208        });
 6209    }
 6210
 6211    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6212        if self.read_only(cx) {
 6213            return;
 6214        }
 6215        let mut selections = self.selections.all::<Point>(cx);
 6216        let mut prev_edited_row = 0;
 6217        let mut row_delta = 0;
 6218        let mut edits = Vec::new();
 6219        let buffer = self.buffer.read(cx);
 6220        let snapshot = buffer.snapshot(cx);
 6221        for selection in &mut selections {
 6222            if selection.start.row != prev_edited_row {
 6223                row_delta = 0;
 6224            }
 6225            prev_edited_row = selection.end.row;
 6226
 6227            row_delta =
 6228                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6229        }
 6230
 6231        self.transact(cx, |this, cx| {
 6232            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6233            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6234        });
 6235    }
 6236
 6237    fn indent_selection(
 6238        buffer: &MultiBuffer,
 6239        snapshot: &MultiBufferSnapshot,
 6240        selection: &mut Selection<Point>,
 6241        edits: &mut Vec<(Range<Point>, String)>,
 6242        delta_for_start_row: u32,
 6243        cx: &AppContext,
 6244    ) -> u32 {
 6245        let settings = buffer.settings_at(selection.start, cx);
 6246        let tab_size = settings.tab_size.get();
 6247        let indent_kind = if settings.hard_tabs {
 6248            IndentKind::Tab
 6249        } else {
 6250            IndentKind::Space
 6251        };
 6252        let mut start_row = selection.start.row;
 6253        let mut end_row = selection.end.row + 1;
 6254
 6255        // If a selection ends at the beginning of a line, don't indent
 6256        // that last line.
 6257        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6258            end_row -= 1;
 6259        }
 6260
 6261        // Avoid re-indenting a row that has already been indented by a
 6262        // previous selection, but still update this selection's column
 6263        // to reflect that indentation.
 6264        if delta_for_start_row > 0 {
 6265            start_row += 1;
 6266            selection.start.column += delta_for_start_row;
 6267            if selection.end.row == selection.start.row {
 6268                selection.end.column += delta_for_start_row;
 6269            }
 6270        }
 6271
 6272        let mut delta_for_end_row = 0;
 6273        let has_multiple_rows = start_row + 1 != end_row;
 6274        for row in start_row..end_row {
 6275            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6276            let indent_delta = match (current_indent.kind, indent_kind) {
 6277                (IndentKind::Space, IndentKind::Space) => {
 6278                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6279                    IndentSize::spaces(columns_to_next_tab_stop)
 6280                }
 6281                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6282                (_, IndentKind::Tab) => IndentSize::tab(),
 6283            };
 6284
 6285            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6286                0
 6287            } else {
 6288                selection.start.column
 6289            };
 6290            let row_start = Point::new(row, start);
 6291            edits.push((
 6292                row_start..row_start,
 6293                indent_delta.chars().collect::<String>(),
 6294            ));
 6295
 6296            // Update this selection's endpoints to reflect the indentation.
 6297            if row == selection.start.row {
 6298                selection.start.column += indent_delta.len;
 6299            }
 6300            if row == selection.end.row {
 6301                selection.end.column += indent_delta.len;
 6302                delta_for_end_row = indent_delta.len;
 6303            }
 6304        }
 6305
 6306        if selection.start.row == selection.end.row {
 6307            delta_for_start_row + delta_for_end_row
 6308        } else {
 6309            delta_for_end_row
 6310        }
 6311    }
 6312
 6313    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6314        if self.read_only(cx) {
 6315            return;
 6316        }
 6317        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6318        let selections = self.selections.all::<Point>(cx);
 6319        let mut deletion_ranges = Vec::new();
 6320        let mut last_outdent = None;
 6321        {
 6322            let buffer = self.buffer.read(cx);
 6323            let snapshot = buffer.snapshot(cx);
 6324            for selection in &selections {
 6325                let settings = buffer.settings_at(selection.start, cx);
 6326                let tab_size = settings.tab_size.get();
 6327                let mut rows = selection.spanned_rows(false, &display_map);
 6328
 6329                // Avoid re-outdenting a row that has already been outdented by a
 6330                // previous selection.
 6331                if let Some(last_row) = last_outdent {
 6332                    if last_row == rows.start {
 6333                        rows.start = rows.start.next_row();
 6334                    }
 6335                }
 6336                let has_multiple_rows = rows.len() > 1;
 6337                for row in rows.iter_rows() {
 6338                    let indent_size = snapshot.indent_size_for_line(row);
 6339                    if indent_size.len > 0 {
 6340                        let deletion_len = match indent_size.kind {
 6341                            IndentKind::Space => {
 6342                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6343                                if columns_to_prev_tab_stop == 0 {
 6344                                    tab_size
 6345                                } else {
 6346                                    columns_to_prev_tab_stop
 6347                                }
 6348                            }
 6349                            IndentKind::Tab => 1,
 6350                        };
 6351                        let start = if has_multiple_rows
 6352                            || deletion_len > selection.start.column
 6353                            || indent_size.len < selection.start.column
 6354                        {
 6355                            0
 6356                        } else {
 6357                            selection.start.column - deletion_len
 6358                        };
 6359                        deletion_ranges.push(
 6360                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6361                        );
 6362                        last_outdent = Some(row);
 6363                    }
 6364                }
 6365            }
 6366        }
 6367
 6368        self.transact(cx, |this, cx| {
 6369            this.buffer.update(cx, |buffer, cx| {
 6370                let empty_str: Arc<str> = Arc::default();
 6371                buffer.edit(
 6372                    deletion_ranges
 6373                        .into_iter()
 6374                        .map(|range| (range, empty_str.clone())),
 6375                    None,
 6376                    cx,
 6377                );
 6378            });
 6379            let selections = this.selections.all::<usize>(cx);
 6380            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6381        });
 6382    }
 6383
 6384    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6385        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6386        let selections = self.selections.all::<Point>(cx);
 6387
 6388        let mut new_cursors = Vec::new();
 6389        let mut edit_ranges = Vec::new();
 6390        let mut selections = selections.iter().peekable();
 6391        while let Some(selection) = selections.next() {
 6392            let mut rows = selection.spanned_rows(false, &display_map);
 6393            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6394
 6395            // Accumulate contiguous regions of rows that we want to delete.
 6396            while let Some(next_selection) = selections.peek() {
 6397                let next_rows = next_selection.spanned_rows(false, &display_map);
 6398                if next_rows.start <= rows.end {
 6399                    rows.end = next_rows.end;
 6400                    selections.next().unwrap();
 6401                } else {
 6402                    break;
 6403                }
 6404            }
 6405
 6406            let buffer = &display_map.buffer_snapshot;
 6407            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6408            let edit_end;
 6409            let cursor_buffer_row;
 6410            if buffer.max_point().row >= rows.end.0 {
 6411                // If there's a line after the range, delete the \n from the end of the row range
 6412                // and position the cursor on the next line.
 6413                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6414                cursor_buffer_row = rows.end;
 6415            } else {
 6416                // If there isn't a line after the range, delete the \n from the line before the
 6417                // start of the row range and position the cursor there.
 6418                edit_start = edit_start.saturating_sub(1);
 6419                edit_end = buffer.len();
 6420                cursor_buffer_row = rows.start.previous_row();
 6421            }
 6422
 6423            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6424            *cursor.column_mut() =
 6425                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6426
 6427            new_cursors.push((
 6428                selection.id,
 6429                buffer.anchor_after(cursor.to_point(&display_map)),
 6430            ));
 6431            edit_ranges.push(edit_start..edit_end);
 6432        }
 6433
 6434        self.transact(cx, |this, cx| {
 6435            let buffer = this.buffer.update(cx, |buffer, cx| {
 6436                let empty_str: Arc<str> = Arc::default();
 6437                buffer.edit(
 6438                    edit_ranges
 6439                        .into_iter()
 6440                        .map(|range| (range, empty_str.clone())),
 6441                    None,
 6442                    cx,
 6443                );
 6444                buffer.snapshot(cx)
 6445            });
 6446            let new_selections = new_cursors
 6447                .into_iter()
 6448                .map(|(id, cursor)| {
 6449                    let cursor = cursor.to_point(&buffer);
 6450                    Selection {
 6451                        id,
 6452                        start: cursor,
 6453                        end: cursor,
 6454                        reversed: false,
 6455                        goal: SelectionGoal::None,
 6456                    }
 6457                })
 6458                .collect();
 6459
 6460            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6461                s.select(new_selections);
 6462            });
 6463        });
 6464    }
 6465
 6466    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6467        if self.read_only(cx) {
 6468            return;
 6469        }
 6470        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6471        for selection in self.selections.all::<Point>(cx) {
 6472            let start = MultiBufferRow(selection.start.row);
 6473            // Treat single line selections as if they include the next line. Otherwise this action
 6474            // would do nothing for single line selections individual cursors.
 6475            let end = if selection.start.row == selection.end.row {
 6476                MultiBufferRow(selection.start.row + 1)
 6477            } else {
 6478                MultiBufferRow(selection.end.row)
 6479            };
 6480
 6481            if let Some(last_row_range) = row_ranges.last_mut() {
 6482                if start <= last_row_range.end {
 6483                    last_row_range.end = end;
 6484                    continue;
 6485                }
 6486            }
 6487            row_ranges.push(start..end);
 6488        }
 6489
 6490        let snapshot = self.buffer.read(cx).snapshot(cx);
 6491        let mut cursor_positions = Vec::new();
 6492        for row_range in &row_ranges {
 6493            let anchor = snapshot.anchor_before(Point::new(
 6494                row_range.end.previous_row().0,
 6495                snapshot.line_len(row_range.end.previous_row()),
 6496            ));
 6497            cursor_positions.push(anchor..anchor);
 6498        }
 6499
 6500        self.transact(cx, |this, cx| {
 6501            for row_range in row_ranges.into_iter().rev() {
 6502                for row in row_range.iter_rows().rev() {
 6503                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6504                    let next_line_row = row.next_row();
 6505                    let indent = snapshot.indent_size_for_line(next_line_row);
 6506                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6507
 6508                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6509                        " "
 6510                    } else {
 6511                        ""
 6512                    };
 6513
 6514                    this.buffer.update(cx, |buffer, cx| {
 6515                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6516                    });
 6517                }
 6518            }
 6519
 6520            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6521                s.select_anchor_ranges(cursor_positions)
 6522            });
 6523        });
 6524    }
 6525
 6526    pub fn sort_lines_case_sensitive(
 6527        &mut self,
 6528        _: &SortLinesCaseSensitive,
 6529        cx: &mut ViewContext<Self>,
 6530    ) {
 6531        self.manipulate_lines(cx, |lines| lines.sort())
 6532    }
 6533
 6534    pub fn sort_lines_case_insensitive(
 6535        &mut self,
 6536        _: &SortLinesCaseInsensitive,
 6537        cx: &mut ViewContext<Self>,
 6538    ) {
 6539        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6540    }
 6541
 6542    pub fn unique_lines_case_insensitive(
 6543        &mut self,
 6544        _: &UniqueLinesCaseInsensitive,
 6545        cx: &mut ViewContext<Self>,
 6546    ) {
 6547        self.manipulate_lines(cx, |lines| {
 6548            let mut seen = HashSet::default();
 6549            lines.retain(|line| seen.insert(line.to_lowercase()));
 6550        })
 6551    }
 6552
 6553    pub fn unique_lines_case_sensitive(
 6554        &mut self,
 6555        _: &UniqueLinesCaseSensitive,
 6556        cx: &mut ViewContext<Self>,
 6557    ) {
 6558        self.manipulate_lines(cx, |lines| {
 6559            let mut seen = HashSet::default();
 6560            lines.retain(|line| seen.insert(*line));
 6561        })
 6562    }
 6563
 6564    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6565        let mut revert_changes = HashMap::default();
 6566        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6567        for hunk in hunks_for_rows(
 6568            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6569            &multi_buffer_snapshot,
 6570        ) {
 6571            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6572        }
 6573        if !revert_changes.is_empty() {
 6574            self.transact(cx, |editor, cx| {
 6575                editor.revert(revert_changes, cx);
 6576            });
 6577        }
 6578    }
 6579
 6580    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6581        let Some(project) = self.project.clone() else {
 6582            return;
 6583        };
 6584        self.reload(project, cx).detach_and_notify_err(cx);
 6585    }
 6586
 6587    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6588        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6589        if !revert_changes.is_empty() {
 6590            self.transact(cx, |editor, cx| {
 6591                editor.revert(revert_changes, cx);
 6592            });
 6593        }
 6594    }
 6595
 6596    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6597        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6598            let project_path = buffer.read(cx).project_path(cx)?;
 6599            let project = self.project.as_ref()?.read(cx);
 6600            let entry = project.entry_for_path(&project_path, cx)?;
 6601            let parent = match &entry.canonical_path {
 6602                Some(canonical_path) => canonical_path.to_path_buf(),
 6603                None => project.absolute_path(&project_path, cx)?,
 6604            }
 6605            .parent()?
 6606            .to_path_buf();
 6607            Some(parent)
 6608        }) {
 6609            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6610        }
 6611    }
 6612
 6613    fn gather_revert_changes(
 6614        &mut self,
 6615        selections: &[Selection<Anchor>],
 6616        cx: &mut ViewContext<'_, Editor>,
 6617    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6618        let mut revert_changes = HashMap::default();
 6619        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6620        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6621            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6622        }
 6623        revert_changes
 6624    }
 6625
 6626    pub fn prepare_revert_change(
 6627        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6628        multi_buffer: &Model<MultiBuffer>,
 6629        hunk: &MultiBufferDiffHunk,
 6630        cx: &AppContext,
 6631    ) -> Option<()> {
 6632        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6633        let buffer = buffer.read(cx);
 6634        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6635        let buffer_snapshot = buffer.snapshot();
 6636        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6637        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6638            probe
 6639                .0
 6640                .start
 6641                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6642                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6643        }) {
 6644            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6645            Some(())
 6646        } else {
 6647            None
 6648        }
 6649    }
 6650
 6651    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6652        self.manipulate_lines(cx, |lines| lines.reverse())
 6653    }
 6654
 6655    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6656        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6657    }
 6658
 6659    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6660    where
 6661        Fn: FnMut(&mut Vec<&str>),
 6662    {
 6663        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6664        let buffer = self.buffer.read(cx).snapshot(cx);
 6665
 6666        let mut edits = Vec::new();
 6667
 6668        let selections = self.selections.all::<Point>(cx);
 6669        let mut selections = selections.iter().peekable();
 6670        let mut contiguous_row_selections = Vec::new();
 6671        let mut new_selections = Vec::new();
 6672        let mut added_lines = 0;
 6673        let mut removed_lines = 0;
 6674
 6675        while let Some(selection) = selections.next() {
 6676            let (start_row, end_row) = consume_contiguous_rows(
 6677                &mut contiguous_row_selections,
 6678                selection,
 6679                &display_map,
 6680                &mut selections,
 6681            );
 6682
 6683            let start_point = Point::new(start_row.0, 0);
 6684            let end_point = Point::new(
 6685                end_row.previous_row().0,
 6686                buffer.line_len(end_row.previous_row()),
 6687            );
 6688            let text = buffer
 6689                .text_for_range(start_point..end_point)
 6690                .collect::<String>();
 6691
 6692            let mut lines = text.split('\n').collect_vec();
 6693
 6694            let lines_before = lines.len();
 6695            callback(&mut lines);
 6696            let lines_after = lines.len();
 6697
 6698            edits.push((start_point..end_point, lines.join("\n")));
 6699
 6700            // Selections must change based on added and removed line count
 6701            let start_row =
 6702                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6703            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6704            new_selections.push(Selection {
 6705                id: selection.id,
 6706                start: start_row,
 6707                end: end_row,
 6708                goal: SelectionGoal::None,
 6709                reversed: selection.reversed,
 6710            });
 6711
 6712            if lines_after > lines_before {
 6713                added_lines += lines_after - lines_before;
 6714            } else if lines_before > lines_after {
 6715                removed_lines += lines_before - lines_after;
 6716            }
 6717        }
 6718
 6719        self.transact(cx, |this, cx| {
 6720            let buffer = this.buffer.update(cx, |buffer, cx| {
 6721                buffer.edit(edits, None, cx);
 6722                buffer.snapshot(cx)
 6723            });
 6724
 6725            // Recalculate offsets on newly edited buffer
 6726            let new_selections = new_selections
 6727                .iter()
 6728                .map(|s| {
 6729                    let start_point = Point::new(s.start.0, 0);
 6730                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6731                    Selection {
 6732                        id: s.id,
 6733                        start: buffer.point_to_offset(start_point),
 6734                        end: buffer.point_to_offset(end_point),
 6735                        goal: s.goal,
 6736                        reversed: s.reversed,
 6737                    }
 6738                })
 6739                .collect();
 6740
 6741            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6742                s.select(new_selections);
 6743            });
 6744
 6745            this.request_autoscroll(Autoscroll::fit(), cx);
 6746        });
 6747    }
 6748
 6749    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6750        self.manipulate_text(cx, |text| text.to_uppercase())
 6751    }
 6752
 6753    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6754        self.manipulate_text(cx, |text| text.to_lowercase())
 6755    }
 6756
 6757    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6758        self.manipulate_text(cx, |text| {
 6759            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6760            // https://github.com/rutrum/convert-case/issues/16
 6761            text.split('\n')
 6762                .map(|line| line.to_case(Case::Title))
 6763                .join("\n")
 6764        })
 6765    }
 6766
 6767    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6768        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6769    }
 6770
 6771    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6772        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6773    }
 6774
 6775    pub fn convert_to_upper_camel_case(
 6776        &mut self,
 6777        _: &ConvertToUpperCamelCase,
 6778        cx: &mut ViewContext<Self>,
 6779    ) {
 6780        self.manipulate_text(cx, |text| {
 6781            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6782            // https://github.com/rutrum/convert-case/issues/16
 6783            text.split('\n')
 6784                .map(|line| line.to_case(Case::UpperCamel))
 6785                .join("\n")
 6786        })
 6787    }
 6788
 6789    pub fn convert_to_lower_camel_case(
 6790        &mut self,
 6791        _: &ConvertToLowerCamelCase,
 6792        cx: &mut ViewContext<Self>,
 6793    ) {
 6794        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6795    }
 6796
 6797    pub fn convert_to_opposite_case(
 6798        &mut self,
 6799        _: &ConvertToOppositeCase,
 6800        cx: &mut ViewContext<Self>,
 6801    ) {
 6802        self.manipulate_text(cx, |text| {
 6803            text.chars()
 6804                .fold(String::with_capacity(text.len()), |mut t, c| {
 6805                    if c.is_uppercase() {
 6806                        t.extend(c.to_lowercase());
 6807                    } else {
 6808                        t.extend(c.to_uppercase());
 6809                    }
 6810                    t
 6811                })
 6812        })
 6813    }
 6814
 6815    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6816    where
 6817        Fn: FnMut(&str) -> String,
 6818    {
 6819        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6820        let buffer = self.buffer.read(cx).snapshot(cx);
 6821
 6822        let mut new_selections = Vec::new();
 6823        let mut edits = Vec::new();
 6824        let mut selection_adjustment = 0i32;
 6825
 6826        for selection in self.selections.all::<usize>(cx) {
 6827            let selection_is_empty = selection.is_empty();
 6828
 6829            let (start, end) = if selection_is_empty {
 6830                let word_range = movement::surrounding_word(
 6831                    &display_map,
 6832                    selection.start.to_display_point(&display_map),
 6833                );
 6834                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6835                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6836                (start, end)
 6837            } else {
 6838                (selection.start, selection.end)
 6839            };
 6840
 6841            let text = buffer.text_for_range(start..end).collect::<String>();
 6842            let old_length = text.len() as i32;
 6843            let text = callback(&text);
 6844
 6845            new_selections.push(Selection {
 6846                start: (start as i32 - selection_adjustment) as usize,
 6847                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6848                goal: SelectionGoal::None,
 6849                ..selection
 6850            });
 6851
 6852            selection_adjustment += old_length - text.len() as i32;
 6853
 6854            edits.push((start..end, text));
 6855        }
 6856
 6857        self.transact(cx, |this, cx| {
 6858            this.buffer.update(cx, |buffer, cx| {
 6859                buffer.edit(edits, None, cx);
 6860            });
 6861
 6862            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6863                s.select(new_selections);
 6864            });
 6865
 6866            this.request_autoscroll(Autoscroll::fit(), cx);
 6867        });
 6868    }
 6869
 6870    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6871        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6872        let buffer = &display_map.buffer_snapshot;
 6873        let selections = self.selections.all::<Point>(cx);
 6874
 6875        let mut edits = Vec::new();
 6876        let mut selections_iter = selections.iter().peekable();
 6877        while let Some(selection) = selections_iter.next() {
 6878            // Avoid duplicating the same lines twice.
 6879            let mut rows = selection.spanned_rows(false, &display_map);
 6880
 6881            while let Some(next_selection) = selections_iter.peek() {
 6882                let next_rows = next_selection.spanned_rows(false, &display_map);
 6883                if next_rows.start < rows.end {
 6884                    rows.end = next_rows.end;
 6885                    selections_iter.next().unwrap();
 6886                } else {
 6887                    break;
 6888                }
 6889            }
 6890
 6891            // Copy the text from the selected row region and splice it either at the start
 6892            // or end of the region.
 6893            let start = Point::new(rows.start.0, 0);
 6894            let end = Point::new(
 6895                rows.end.previous_row().0,
 6896                buffer.line_len(rows.end.previous_row()),
 6897            );
 6898            let text = buffer
 6899                .text_for_range(start..end)
 6900                .chain(Some("\n"))
 6901                .collect::<String>();
 6902            let insert_location = if upwards {
 6903                Point::new(rows.end.0, 0)
 6904            } else {
 6905                start
 6906            };
 6907            edits.push((insert_location..insert_location, text));
 6908        }
 6909
 6910        self.transact(cx, |this, cx| {
 6911            this.buffer.update(cx, |buffer, cx| {
 6912                buffer.edit(edits, None, cx);
 6913            });
 6914
 6915            this.request_autoscroll(Autoscroll::fit(), cx);
 6916        });
 6917    }
 6918
 6919    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6920        self.duplicate_line(true, cx);
 6921    }
 6922
 6923    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6924        self.duplicate_line(false, cx);
 6925    }
 6926
 6927    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6928        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6929        let buffer = self.buffer.read(cx).snapshot(cx);
 6930
 6931        let mut edits = Vec::new();
 6932        let mut unfold_ranges = Vec::new();
 6933        let mut refold_creases = Vec::new();
 6934
 6935        let selections = self.selections.all::<Point>(cx);
 6936        let mut selections = selections.iter().peekable();
 6937        let mut contiguous_row_selections = Vec::new();
 6938        let mut new_selections = Vec::new();
 6939
 6940        while let Some(selection) = selections.next() {
 6941            // Find all the selections that span a contiguous row range
 6942            let (start_row, end_row) = consume_contiguous_rows(
 6943                &mut contiguous_row_selections,
 6944                selection,
 6945                &display_map,
 6946                &mut selections,
 6947            );
 6948
 6949            // Move the text spanned by the row range to be before the line preceding the row range
 6950            if start_row.0 > 0 {
 6951                let range_to_move = Point::new(
 6952                    start_row.previous_row().0,
 6953                    buffer.line_len(start_row.previous_row()),
 6954                )
 6955                    ..Point::new(
 6956                        end_row.previous_row().0,
 6957                        buffer.line_len(end_row.previous_row()),
 6958                    );
 6959                let insertion_point = display_map
 6960                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6961                    .0;
 6962
 6963                // Don't move lines across excerpts
 6964                if buffer
 6965                    .excerpt_boundaries_in_range((
 6966                        Bound::Excluded(insertion_point),
 6967                        Bound::Included(range_to_move.end),
 6968                    ))
 6969                    .next()
 6970                    .is_none()
 6971                {
 6972                    let text = buffer
 6973                        .text_for_range(range_to_move.clone())
 6974                        .flat_map(|s| s.chars())
 6975                        .skip(1)
 6976                        .chain(['\n'])
 6977                        .collect::<String>();
 6978
 6979                    edits.push((
 6980                        buffer.anchor_after(range_to_move.start)
 6981                            ..buffer.anchor_before(range_to_move.end),
 6982                        String::new(),
 6983                    ));
 6984                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6985                    edits.push((insertion_anchor..insertion_anchor, text));
 6986
 6987                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6988
 6989                    // Move selections up
 6990                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6991                        |mut selection| {
 6992                            selection.start.row -= row_delta;
 6993                            selection.end.row -= row_delta;
 6994                            selection
 6995                        },
 6996                    ));
 6997
 6998                    // Move folds up
 6999                    unfold_ranges.push(range_to_move.clone());
 7000                    for fold in display_map.folds_in_range(
 7001                        buffer.anchor_before(range_to_move.start)
 7002                            ..buffer.anchor_after(range_to_move.end),
 7003                    ) {
 7004                        let mut start = fold.range.start.to_point(&buffer);
 7005                        let mut end = fold.range.end.to_point(&buffer);
 7006                        start.row -= row_delta;
 7007                        end.row -= row_delta;
 7008                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7009                    }
 7010                }
 7011            }
 7012
 7013            // If we didn't move line(s), preserve the existing selections
 7014            new_selections.append(&mut contiguous_row_selections);
 7015        }
 7016
 7017        self.transact(cx, |this, cx| {
 7018            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7019            this.buffer.update(cx, |buffer, cx| {
 7020                for (range, text) in edits {
 7021                    buffer.edit([(range, text)], None, cx);
 7022                }
 7023            });
 7024            this.fold_creases(refold_creases, true, cx);
 7025            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7026                s.select(new_selections);
 7027            })
 7028        });
 7029    }
 7030
 7031    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 7032        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7033        let buffer = self.buffer.read(cx).snapshot(cx);
 7034
 7035        let mut edits = Vec::new();
 7036        let mut unfold_ranges = Vec::new();
 7037        let mut refold_creases = Vec::new();
 7038
 7039        let selections = self.selections.all::<Point>(cx);
 7040        let mut selections = selections.iter().peekable();
 7041        let mut contiguous_row_selections = Vec::new();
 7042        let mut new_selections = Vec::new();
 7043
 7044        while let Some(selection) = selections.next() {
 7045            // Find all the selections that span a contiguous row range
 7046            let (start_row, end_row) = consume_contiguous_rows(
 7047                &mut contiguous_row_selections,
 7048                selection,
 7049                &display_map,
 7050                &mut selections,
 7051            );
 7052
 7053            // Move the text spanned by the row range to be after the last line of the row range
 7054            if end_row.0 <= buffer.max_point().row {
 7055                let range_to_move =
 7056                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7057                let insertion_point = display_map
 7058                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7059                    .0;
 7060
 7061                // Don't move lines across excerpt boundaries
 7062                if buffer
 7063                    .excerpt_boundaries_in_range((
 7064                        Bound::Excluded(range_to_move.start),
 7065                        Bound::Included(insertion_point),
 7066                    ))
 7067                    .next()
 7068                    .is_none()
 7069                {
 7070                    let mut text = String::from("\n");
 7071                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7072                    text.pop(); // Drop trailing newline
 7073                    edits.push((
 7074                        buffer.anchor_after(range_to_move.start)
 7075                            ..buffer.anchor_before(range_to_move.end),
 7076                        String::new(),
 7077                    ));
 7078                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7079                    edits.push((insertion_anchor..insertion_anchor, text));
 7080
 7081                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7082
 7083                    // Move selections down
 7084                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7085                        |mut selection| {
 7086                            selection.start.row += row_delta;
 7087                            selection.end.row += row_delta;
 7088                            selection
 7089                        },
 7090                    ));
 7091
 7092                    // Move folds down
 7093                    unfold_ranges.push(range_to_move.clone());
 7094                    for fold in display_map.folds_in_range(
 7095                        buffer.anchor_before(range_to_move.start)
 7096                            ..buffer.anchor_after(range_to_move.end),
 7097                    ) {
 7098                        let mut start = fold.range.start.to_point(&buffer);
 7099                        let mut end = fold.range.end.to_point(&buffer);
 7100                        start.row += row_delta;
 7101                        end.row += row_delta;
 7102                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7103                    }
 7104                }
 7105            }
 7106
 7107            // If we didn't move line(s), preserve the existing selections
 7108            new_selections.append(&mut contiguous_row_selections);
 7109        }
 7110
 7111        self.transact(cx, |this, cx| {
 7112            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7113            this.buffer.update(cx, |buffer, cx| {
 7114                for (range, text) in edits {
 7115                    buffer.edit([(range, text)], None, cx);
 7116                }
 7117            });
 7118            this.fold_creases(refold_creases, true, cx);
 7119            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7120        });
 7121    }
 7122
 7123    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7124        let text_layout_details = &self.text_layout_details(cx);
 7125        self.transact(cx, |this, cx| {
 7126            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7127                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7128                let line_mode = s.line_mode;
 7129                s.move_with(|display_map, selection| {
 7130                    if !selection.is_empty() || line_mode {
 7131                        return;
 7132                    }
 7133
 7134                    let mut head = selection.head();
 7135                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7136                    if head.column() == display_map.line_len(head.row()) {
 7137                        transpose_offset = display_map
 7138                            .buffer_snapshot
 7139                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7140                    }
 7141
 7142                    if transpose_offset == 0 {
 7143                        return;
 7144                    }
 7145
 7146                    *head.column_mut() += 1;
 7147                    head = display_map.clip_point(head, Bias::Right);
 7148                    let goal = SelectionGoal::HorizontalPosition(
 7149                        display_map
 7150                            .x_for_display_point(head, text_layout_details)
 7151                            .into(),
 7152                    );
 7153                    selection.collapse_to(head, goal);
 7154
 7155                    let transpose_start = display_map
 7156                        .buffer_snapshot
 7157                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7158                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7159                        let transpose_end = display_map
 7160                            .buffer_snapshot
 7161                            .clip_offset(transpose_offset + 1, Bias::Right);
 7162                        if let Some(ch) =
 7163                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7164                        {
 7165                            edits.push((transpose_start..transpose_offset, String::new()));
 7166                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7167                        }
 7168                    }
 7169                });
 7170                edits
 7171            });
 7172            this.buffer
 7173                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7174            let selections = this.selections.all::<usize>(cx);
 7175            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7176                s.select(selections);
 7177            });
 7178        });
 7179    }
 7180
 7181    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7182        self.rewrap_impl(IsVimMode::No, cx)
 7183    }
 7184
 7185    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7186        let buffer = self.buffer.read(cx).snapshot(cx);
 7187        let selections = self.selections.all::<Point>(cx);
 7188        let mut selections = selections.iter().peekable();
 7189
 7190        let mut edits = Vec::new();
 7191        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7192
 7193        while let Some(selection) = selections.next() {
 7194            let mut start_row = selection.start.row;
 7195            let mut end_row = selection.end.row;
 7196
 7197            // Skip selections that overlap with a range that has already been rewrapped.
 7198            let selection_range = start_row..end_row;
 7199            if rewrapped_row_ranges
 7200                .iter()
 7201                .any(|range| range.overlaps(&selection_range))
 7202            {
 7203                continue;
 7204            }
 7205
 7206            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7207
 7208            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7209                match language_scope.language_name().0.as_ref() {
 7210                    "Markdown" | "Plain Text" => {
 7211                        should_rewrap = true;
 7212                    }
 7213                    _ => {}
 7214                }
 7215            }
 7216
 7217            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7218
 7219            // Since not all lines in the selection may be at the same indent
 7220            // level, choose the indent size that is the most common between all
 7221            // of the lines.
 7222            //
 7223            // If there is a tie, we use the deepest indent.
 7224            let (indent_size, indent_end) = {
 7225                let mut indent_size_occurrences = HashMap::default();
 7226                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7227
 7228                for row in start_row..=end_row {
 7229                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7230                    rows_by_indent_size.entry(indent).or_default().push(row);
 7231                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7232                }
 7233
 7234                let indent_size = indent_size_occurrences
 7235                    .into_iter()
 7236                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7237                    .map(|(indent, _)| indent)
 7238                    .unwrap_or_default();
 7239                let row = rows_by_indent_size[&indent_size][0];
 7240                let indent_end = Point::new(row, indent_size.len);
 7241
 7242                (indent_size, indent_end)
 7243            };
 7244
 7245            let mut line_prefix = indent_size.chars().collect::<String>();
 7246
 7247            if let Some(comment_prefix) =
 7248                buffer
 7249                    .language_scope_at(selection.head())
 7250                    .and_then(|language| {
 7251                        language
 7252                            .line_comment_prefixes()
 7253                            .iter()
 7254                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7255                            .cloned()
 7256                    })
 7257            {
 7258                line_prefix.push_str(&comment_prefix);
 7259                should_rewrap = true;
 7260            }
 7261
 7262            if !should_rewrap {
 7263                continue;
 7264            }
 7265
 7266            if selection.is_empty() {
 7267                'expand_upwards: while start_row > 0 {
 7268                    let prev_row = start_row - 1;
 7269                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7270                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7271                    {
 7272                        start_row = prev_row;
 7273                    } else {
 7274                        break 'expand_upwards;
 7275                    }
 7276                }
 7277
 7278                'expand_downwards: while end_row < buffer.max_point().row {
 7279                    let next_row = end_row + 1;
 7280                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7281                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7282                    {
 7283                        end_row = next_row;
 7284                    } else {
 7285                        break 'expand_downwards;
 7286                    }
 7287                }
 7288            }
 7289
 7290            let start = Point::new(start_row, 0);
 7291            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7292            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7293            let Some(lines_without_prefixes) = selection_text
 7294                .lines()
 7295                .map(|line| {
 7296                    line.strip_prefix(&line_prefix)
 7297                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7298                        .ok_or_else(|| {
 7299                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7300                        })
 7301                })
 7302                .collect::<Result<Vec<_>, _>>()
 7303                .log_err()
 7304            else {
 7305                continue;
 7306            };
 7307
 7308            let wrap_column = buffer
 7309                .settings_at(Point::new(start_row, 0), cx)
 7310                .preferred_line_length as usize;
 7311            let wrapped_text = wrap_with_prefix(
 7312                line_prefix,
 7313                lines_without_prefixes.join(" "),
 7314                wrap_column,
 7315                tab_size,
 7316            );
 7317
 7318            // TODO: should always use char-based diff while still supporting cursor behavior that
 7319            // matches vim.
 7320            let diff = match is_vim_mode {
 7321                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7322                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7323            };
 7324            let mut offset = start.to_offset(&buffer);
 7325            let mut moved_since_edit = true;
 7326
 7327            for change in diff.iter_all_changes() {
 7328                let value = change.value();
 7329                match change.tag() {
 7330                    ChangeTag::Equal => {
 7331                        offset += value.len();
 7332                        moved_since_edit = true;
 7333                    }
 7334                    ChangeTag::Delete => {
 7335                        let start = buffer.anchor_after(offset);
 7336                        let end = buffer.anchor_before(offset + value.len());
 7337
 7338                        if moved_since_edit {
 7339                            edits.push((start..end, String::new()));
 7340                        } else {
 7341                            edits.last_mut().unwrap().0.end = end;
 7342                        }
 7343
 7344                        offset += value.len();
 7345                        moved_since_edit = false;
 7346                    }
 7347                    ChangeTag::Insert => {
 7348                        if moved_since_edit {
 7349                            let anchor = buffer.anchor_after(offset);
 7350                            edits.push((anchor..anchor, value.to_string()));
 7351                        } else {
 7352                            edits.last_mut().unwrap().1.push_str(value);
 7353                        }
 7354
 7355                        moved_since_edit = false;
 7356                    }
 7357                }
 7358            }
 7359
 7360            rewrapped_row_ranges.push(start_row..=end_row);
 7361        }
 7362
 7363        self.buffer
 7364            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7365    }
 7366
 7367    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 7368        let mut text = String::new();
 7369        let buffer = self.buffer.read(cx).snapshot(cx);
 7370        let mut selections = self.selections.all::<Point>(cx);
 7371        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7372        {
 7373            let max_point = buffer.max_point();
 7374            let mut is_first = true;
 7375            for selection in &mut selections {
 7376                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7377                if is_entire_line {
 7378                    selection.start = Point::new(selection.start.row, 0);
 7379                    if !selection.is_empty() && selection.end.column == 0 {
 7380                        selection.end = cmp::min(max_point, selection.end);
 7381                    } else {
 7382                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7383                    }
 7384                    selection.goal = SelectionGoal::None;
 7385                }
 7386                if is_first {
 7387                    is_first = false;
 7388                } else {
 7389                    text += "\n";
 7390                }
 7391                let mut len = 0;
 7392                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7393                    text.push_str(chunk);
 7394                    len += chunk.len();
 7395                }
 7396                clipboard_selections.push(ClipboardSelection {
 7397                    len,
 7398                    is_entire_line,
 7399                    first_line_indent: buffer
 7400                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7401                        .len,
 7402                });
 7403            }
 7404        }
 7405
 7406        self.transact(cx, |this, cx| {
 7407            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7408                s.select(selections);
 7409            });
 7410            this.insert("", cx);
 7411        });
 7412        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7413    }
 7414
 7415    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7416        let item = self.cut_common(cx);
 7417        cx.write_to_clipboard(item);
 7418    }
 7419
 7420    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 7421        self.change_selections(None, cx, |s| {
 7422            s.move_with(|snapshot, sel| {
 7423                if sel.is_empty() {
 7424                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7425                }
 7426            });
 7427        });
 7428        let item = self.cut_common(cx);
 7429        cx.set_global(KillRing(item))
 7430    }
 7431
 7432    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 7433        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7434            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7435                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7436            } else {
 7437                return;
 7438            }
 7439        } else {
 7440            return;
 7441        };
 7442        self.do_paste(&text, metadata, false, cx);
 7443    }
 7444
 7445    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7446        let selections = self.selections.all::<Point>(cx);
 7447        let buffer = self.buffer.read(cx).read(cx);
 7448        let mut text = String::new();
 7449
 7450        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7451        {
 7452            let max_point = buffer.max_point();
 7453            let mut is_first = true;
 7454            for selection in selections.iter() {
 7455                let mut start = selection.start;
 7456                let mut end = selection.end;
 7457                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7458                if is_entire_line {
 7459                    start = Point::new(start.row, 0);
 7460                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7461                }
 7462                if is_first {
 7463                    is_first = false;
 7464                } else {
 7465                    text += "\n";
 7466                }
 7467                let mut len = 0;
 7468                for chunk in buffer.text_for_range(start..end) {
 7469                    text.push_str(chunk);
 7470                    len += chunk.len();
 7471                }
 7472                clipboard_selections.push(ClipboardSelection {
 7473                    len,
 7474                    is_entire_line,
 7475                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7476                });
 7477            }
 7478        }
 7479
 7480        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7481            text,
 7482            clipboard_selections,
 7483        ));
 7484    }
 7485
 7486    pub fn do_paste(
 7487        &mut self,
 7488        text: &String,
 7489        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7490        handle_entire_lines: bool,
 7491        cx: &mut ViewContext<Self>,
 7492    ) {
 7493        if self.read_only(cx) {
 7494            return;
 7495        }
 7496
 7497        let clipboard_text = Cow::Borrowed(text);
 7498
 7499        self.transact(cx, |this, cx| {
 7500            if let Some(mut clipboard_selections) = clipboard_selections {
 7501                let old_selections = this.selections.all::<usize>(cx);
 7502                let all_selections_were_entire_line =
 7503                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7504                let first_selection_indent_column =
 7505                    clipboard_selections.first().map(|s| s.first_line_indent);
 7506                if clipboard_selections.len() != old_selections.len() {
 7507                    clipboard_selections.drain(..);
 7508                }
 7509                let cursor_offset = this.selections.last::<usize>(cx).head();
 7510                let mut auto_indent_on_paste = true;
 7511
 7512                this.buffer.update(cx, |buffer, cx| {
 7513                    let snapshot = buffer.read(cx);
 7514                    auto_indent_on_paste =
 7515                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7516
 7517                    let mut start_offset = 0;
 7518                    let mut edits = Vec::new();
 7519                    let mut original_indent_columns = Vec::new();
 7520                    for (ix, selection) in old_selections.iter().enumerate() {
 7521                        let to_insert;
 7522                        let entire_line;
 7523                        let original_indent_column;
 7524                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7525                            let end_offset = start_offset + clipboard_selection.len;
 7526                            to_insert = &clipboard_text[start_offset..end_offset];
 7527                            entire_line = clipboard_selection.is_entire_line;
 7528                            start_offset = end_offset + 1;
 7529                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7530                        } else {
 7531                            to_insert = clipboard_text.as_str();
 7532                            entire_line = all_selections_were_entire_line;
 7533                            original_indent_column = first_selection_indent_column
 7534                        }
 7535
 7536                        // If the corresponding selection was empty when this slice of the
 7537                        // clipboard text was written, then the entire line containing the
 7538                        // selection was copied. If this selection is also currently empty,
 7539                        // then paste the line before the current line of the buffer.
 7540                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7541                            let column = selection.start.to_point(&snapshot).column as usize;
 7542                            let line_start = selection.start - column;
 7543                            line_start..line_start
 7544                        } else {
 7545                            selection.range()
 7546                        };
 7547
 7548                        edits.push((range, to_insert));
 7549                        original_indent_columns.extend(original_indent_column);
 7550                    }
 7551                    drop(snapshot);
 7552
 7553                    buffer.edit(
 7554                        edits,
 7555                        if auto_indent_on_paste {
 7556                            Some(AutoindentMode::Block {
 7557                                original_indent_columns,
 7558                            })
 7559                        } else {
 7560                            None
 7561                        },
 7562                        cx,
 7563                    );
 7564                });
 7565
 7566                let selections = this.selections.all::<usize>(cx);
 7567                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7568            } else {
 7569                this.insert(&clipboard_text, cx);
 7570            }
 7571        });
 7572    }
 7573
 7574    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7575        if let Some(item) = cx.read_from_clipboard() {
 7576            let entries = item.entries();
 7577
 7578            match entries.first() {
 7579                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7580                // of all the pasted entries.
 7581                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7582                    .do_paste(
 7583                        clipboard_string.text(),
 7584                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7585                        true,
 7586                        cx,
 7587                    ),
 7588                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7589            }
 7590        }
 7591    }
 7592
 7593    pub fn undo(&mut self, _: &Undo, 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.undo(cx)) {
 7599            if let 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            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7611        }
 7612    }
 7613
 7614    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7615        if self.read_only(cx) {
 7616            return;
 7617        }
 7618
 7619        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7620            if let Some((_, Some(selections))) =
 7621                self.selection_history.transaction(transaction_id).cloned()
 7622            {
 7623                self.change_selections(None, cx, |s| {
 7624                    s.select_anchors(selections.to_vec());
 7625                });
 7626            }
 7627            self.request_autoscroll(Autoscroll::fit(), cx);
 7628            self.unmark_text(cx);
 7629            self.refresh_inline_completion(true, false, cx);
 7630            cx.emit(EditorEvent::Edited { transaction_id });
 7631        }
 7632    }
 7633
 7634    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7635        self.buffer
 7636            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7637    }
 7638
 7639    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7640        self.buffer
 7641            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7642    }
 7643
 7644    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7645        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7646            let line_mode = s.line_mode;
 7647            s.move_with(|map, selection| {
 7648                let cursor = if selection.is_empty() && !line_mode {
 7649                    movement::left(map, selection.start)
 7650                } else {
 7651                    selection.start
 7652                };
 7653                selection.collapse_to(cursor, SelectionGoal::None);
 7654            });
 7655        })
 7656    }
 7657
 7658    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7659        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7660            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7661        })
 7662    }
 7663
 7664    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7665        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7666            let line_mode = s.line_mode;
 7667            s.move_with(|map, selection| {
 7668                let cursor = if selection.is_empty() && !line_mode {
 7669                    movement::right(map, selection.end)
 7670                } else {
 7671                    selection.end
 7672                };
 7673                selection.collapse_to(cursor, SelectionGoal::None)
 7674            });
 7675        })
 7676    }
 7677
 7678    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7679        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7680            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7681        })
 7682    }
 7683
 7684    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7685        if self.take_rename(true, cx).is_some() {
 7686            return;
 7687        }
 7688
 7689        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7690            cx.propagate();
 7691            return;
 7692        }
 7693
 7694        let text_layout_details = &self.text_layout_details(cx);
 7695        let selection_count = self.selections.count();
 7696        let first_selection = self.selections.first_anchor();
 7697
 7698        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7699            let line_mode = s.line_mode;
 7700            s.move_with(|map, selection| {
 7701                if !selection.is_empty() && !line_mode {
 7702                    selection.goal = SelectionGoal::None;
 7703                }
 7704                let (cursor, goal) = movement::up(
 7705                    map,
 7706                    selection.start,
 7707                    selection.goal,
 7708                    false,
 7709                    text_layout_details,
 7710                );
 7711                selection.collapse_to(cursor, goal);
 7712            });
 7713        });
 7714
 7715        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7716        {
 7717            cx.propagate();
 7718        }
 7719    }
 7720
 7721    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7722        if self.take_rename(true, cx).is_some() {
 7723            return;
 7724        }
 7725
 7726        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7727            cx.propagate();
 7728            return;
 7729        }
 7730
 7731        let text_layout_details = &self.text_layout_details(cx);
 7732
 7733        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7734            let line_mode = s.line_mode;
 7735            s.move_with(|map, selection| {
 7736                if !selection.is_empty() && !line_mode {
 7737                    selection.goal = SelectionGoal::None;
 7738                }
 7739                let (cursor, goal) = movement::up_by_rows(
 7740                    map,
 7741                    selection.start,
 7742                    action.lines,
 7743                    selection.goal,
 7744                    false,
 7745                    text_layout_details,
 7746                );
 7747                selection.collapse_to(cursor, goal);
 7748            });
 7749        })
 7750    }
 7751
 7752    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7753        if self.take_rename(true, cx).is_some() {
 7754            return;
 7755        }
 7756
 7757        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7758            cx.propagate();
 7759            return;
 7760        }
 7761
 7762        let text_layout_details = &self.text_layout_details(cx);
 7763
 7764        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7765            let line_mode = s.line_mode;
 7766            s.move_with(|map, selection| {
 7767                if !selection.is_empty() && !line_mode {
 7768                    selection.goal = SelectionGoal::None;
 7769                }
 7770                let (cursor, goal) = movement::down_by_rows(
 7771                    map,
 7772                    selection.start,
 7773                    action.lines,
 7774                    selection.goal,
 7775                    false,
 7776                    text_layout_details,
 7777                );
 7778                selection.collapse_to(cursor, goal);
 7779            });
 7780        })
 7781    }
 7782
 7783    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7784        let text_layout_details = &self.text_layout_details(cx);
 7785        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7786            s.move_heads_with(|map, head, goal| {
 7787                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7788            })
 7789        })
 7790    }
 7791
 7792    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7793        let text_layout_details = &self.text_layout_details(cx);
 7794        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7795            s.move_heads_with(|map, head, goal| {
 7796                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7797            })
 7798        })
 7799    }
 7800
 7801    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7802        let Some(row_count) = self.visible_row_count() else {
 7803            return;
 7804        };
 7805
 7806        let text_layout_details = &self.text_layout_details(cx);
 7807
 7808        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7809            s.move_heads_with(|map, head, goal| {
 7810                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7811            })
 7812        })
 7813    }
 7814
 7815    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7816        if self.take_rename(true, cx).is_some() {
 7817            return;
 7818        }
 7819
 7820        if self
 7821            .context_menu
 7822            .write()
 7823            .as_mut()
 7824            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7825            .unwrap_or(false)
 7826        {
 7827            return;
 7828        }
 7829
 7830        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7831            cx.propagate();
 7832            return;
 7833        }
 7834
 7835        let Some(row_count) = self.visible_row_count() else {
 7836            return;
 7837        };
 7838
 7839        let autoscroll = if action.center_cursor {
 7840            Autoscroll::center()
 7841        } else {
 7842            Autoscroll::fit()
 7843        };
 7844
 7845        let text_layout_details = &self.text_layout_details(cx);
 7846
 7847        self.change_selections(Some(autoscroll), cx, |s| {
 7848            let line_mode = s.line_mode;
 7849            s.move_with(|map, selection| {
 7850                if !selection.is_empty() && !line_mode {
 7851                    selection.goal = SelectionGoal::None;
 7852                }
 7853                let (cursor, goal) = movement::up_by_rows(
 7854                    map,
 7855                    selection.end,
 7856                    row_count,
 7857                    selection.goal,
 7858                    false,
 7859                    text_layout_details,
 7860                );
 7861                selection.collapse_to(cursor, goal);
 7862            });
 7863        });
 7864    }
 7865
 7866    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7867        let text_layout_details = &self.text_layout_details(cx);
 7868        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7869            s.move_heads_with(|map, head, goal| {
 7870                movement::up(map, head, goal, false, text_layout_details)
 7871            })
 7872        })
 7873    }
 7874
 7875    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7876        self.take_rename(true, cx);
 7877
 7878        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7879            cx.propagate();
 7880            return;
 7881        }
 7882
 7883        let text_layout_details = &self.text_layout_details(cx);
 7884        let selection_count = self.selections.count();
 7885        let first_selection = self.selections.first_anchor();
 7886
 7887        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7888            let line_mode = s.line_mode;
 7889            s.move_with(|map, selection| {
 7890                if !selection.is_empty() && !line_mode {
 7891                    selection.goal = SelectionGoal::None;
 7892                }
 7893                let (cursor, goal) = movement::down(
 7894                    map,
 7895                    selection.end,
 7896                    selection.goal,
 7897                    false,
 7898                    text_layout_details,
 7899                );
 7900                selection.collapse_to(cursor, goal);
 7901            });
 7902        });
 7903
 7904        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7905        {
 7906            cx.propagate();
 7907        }
 7908    }
 7909
 7910    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7911        let Some(row_count) = self.visible_row_count() else {
 7912            return;
 7913        };
 7914
 7915        let text_layout_details = &self.text_layout_details(cx);
 7916
 7917        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7918            s.move_heads_with(|map, head, goal| {
 7919                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7920            })
 7921        })
 7922    }
 7923
 7924    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7925        if self.take_rename(true, cx).is_some() {
 7926            return;
 7927        }
 7928
 7929        if self
 7930            .context_menu
 7931            .write()
 7932            .as_mut()
 7933            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7934            .unwrap_or(false)
 7935        {
 7936            return;
 7937        }
 7938
 7939        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7940            cx.propagate();
 7941            return;
 7942        }
 7943
 7944        let Some(row_count) = self.visible_row_count() else {
 7945            return;
 7946        };
 7947
 7948        let autoscroll = if action.center_cursor {
 7949            Autoscroll::center()
 7950        } else {
 7951            Autoscroll::fit()
 7952        };
 7953
 7954        let text_layout_details = &self.text_layout_details(cx);
 7955        self.change_selections(Some(autoscroll), cx, |s| {
 7956            let line_mode = s.line_mode;
 7957            s.move_with(|map, selection| {
 7958                if !selection.is_empty() && !line_mode {
 7959                    selection.goal = SelectionGoal::None;
 7960                }
 7961                let (cursor, goal) = movement::down_by_rows(
 7962                    map,
 7963                    selection.end,
 7964                    row_count,
 7965                    selection.goal,
 7966                    false,
 7967                    text_layout_details,
 7968                );
 7969                selection.collapse_to(cursor, goal);
 7970            });
 7971        });
 7972    }
 7973
 7974    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7975        let text_layout_details = &self.text_layout_details(cx);
 7976        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7977            s.move_heads_with(|map, head, goal| {
 7978                movement::down(map, head, goal, false, text_layout_details)
 7979            })
 7980        });
 7981    }
 7982
 7983    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7984        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7985            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7986        }
 7987    }
 7988
 7989    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7990        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7991            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7992        }
 7993    }
 7994
 7995    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7996        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7997            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7998        }
 7999    }
 8000
 8001    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 8002        if let Some(context_menu) = self.context_menu.write().as_mut() {
 8003            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8004        }
 8005    }
 8006
 8007    pub fn move_to_previous_word_start(
 8008        &mut self,
 8009        _: &MoveToPreviousWordStart,
 8010        cx: &mut ViewContext<Self>,
 8011    ) {
 8012        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8013            s.move_cursors_with(|map, head, _| {
 8014                (
 8015                    movement::previous_word_start(map, head),
 8016                    SelectionGoal::None,
 8017                )
 8018            });
 8019        })
 8020    }
 8021
 8022    pub fn move_to_previous_subword_start(
 8023        &mut self,
 8024        _: &MoveToPreviousSubwordStart,
 8025        cx: &mut ViewContext<Self>,
 8026    ) {
 8027        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8028            s.move_cursors_with(|map, head, _| {
 8029                (
 8030                    movement::previous_subword_start(map, head),
 8031                    SelectionGoal::None,
 8032                )
 8033            });
 8034        })
 8035    }
 8036
 8037    pub fn select_to_previous_word_start(
 8038        &mut self,
 8039        _: &SelectToPreviousWordStart,
 8040        cx: &mut ViewContext<Self>,
 8041    ) {
 8042        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8043            s.move_heads_with(|map, head, _| {
 8044                (
 8045                    movement::previous_word_start(map, head),
 8046                    SelectionGoal::None,
 8047                )
 8048            });
 8049        })
 8050    }
 8051
 8052    pub fn select_to_previous_subword_start(
 8053        &mut self,
 8054        _: &SelectToPreviousSubwordStart,
 8055        cx: &mut ViewContext<Self>,
 8056    ) {
 8057        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8058            s.move_heads_with(|map, head, _| {
 8059                (
 8060                    movement::previous_subword_start(map, head),
 8061                    SelectionGoal::None,
 8062                )
 8063            });
 8064        })
 8065    }
 8066
 8067    pub fn delete_to_previous_word_start(
 8068        &mut self,
 8069        action: &DeleteToPreviousWordStart,
 8070        cx: &mut ViewContext<Self>,
 8071    ) {
 8072        self.transact(cx, |this, cx| {
 8073            this.select_autoclose_pair(cx);
 8074            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8075                let line_mode = s.line_mode;
 8076                s.move_with(|map, selection| {
 8077                    if selection.is_empty() && !line_mode {
 8078                        let cursor = if action.ignore_newlines {
 8079                            movement::previous_word_start(map, selection.head())
 8080                        } else {
 8081                            movement::previous_word_start_or_newline(map, selection.head())
 8082                        };
 8083                        selection.set_head(cursor, SelectionGoal::None);
 8084                    }
 8085                });
 8086            });
 8087            this.insert("", cx);
 8088        });
 8089    }
 8090
 8091    pub fn delete_to_previous_subword_start(
 8092        &mut self,
 8093        _: &DeleteToPreviousSubwordStart,
 8094        cx: &mut ViewContext<Self>,
 8095    ) {
 8096        self.transact(cx, |this, cx| {
 8097            this.select_autoclose_pair(cx);
 8098            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8099                let line_mode = s.line_mode;
 8100                s.move_with(|map, selection| {
 8101                    if selection.is_empty() && !line_mode {
 8102                        let cursor = movement::previous_subword_start(map, selection.head());
 8103                        selection.set_head(cursor, SelectionGoal::None);
 8104                    }
 8105                });
 8106            });
 8107            this.insert("", cx);
 8108        });
 8109    }
 8110
 8111    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8112        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8113            s.move_cursors_with(|map, head, _| {
 8114                (movement::next_word_end(map, head), SelectionGoal::None)
 8115            });
 8116        })
 8117    }
 8118
 8119    pub fn move_to_next_subword_end(
 8120        &mut self,
 8121        _: &MoveToNextSubwordEnd,
 8122        cx: &mut ViewContext<Self>,
 8123    ) {
 8124        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8125            s.move_cursors_with(|map, head, _| {
 8126                (movement::next_subword_end(map, head), SelectionGoal::None)
 8127            });
 8128        })
 8129    }
 8130
 8131    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8132        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8133            s.move_heads_with(|map, head, _| {
 8134                (movement::next_word_end(map, head), SelectionGoal::None)
 8135            });
 8136        })
 8137    }
 8138
 8139    pub fn select_to_next_subword_end(
 8140        &mut self,
 8141        _: &SelectToNextSubwordEnd,
 8142        cx: &mut ViewContext<Self>,
 8143    ) {
 8144        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8145            s.move_heads_with(|map, head, _| {
 8146                (movement::next_subword_end(map, head), SelectionGoal::None)
 8147            });
 8148        })
 8149    }
 8150
 8151    pub fn delete_to_next_word_end(
 8152        &mut self,
 8153        action: &DeleteToNextWordEnd,
 8154        cx: &mut ViewContext<Self>,
 8155    ) {
 8156        self.transact(cx, |this, cx| {
 8157            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8158                let line_mode = s.line_mode;
 8159                s.move_with(|map, selection| {
 8160                    if selection.is_empty() && !line_mode {
 8161                        let cursor = if action.ignore_newlines {
 8162                            movement::next_word_end(map, selection.head())
 8163                        } else {
 8164                            movement::next_word_end_or_newline(map, selection.head())
 8165                        };
 8166                        selection.set_head(cursor, SelectionGoal::None);
 8167                    }
 8168                });
 8169            });
 8170            this.insert("", cx);
 8171        });
 8172    }
 8173
 8174    pub fn delete_to_next_subword_end(
 8175        &mut self,
 8176        _: &DeleteToNextSubwordEnd,
 8177        cx: &mut ViewContext<Self>,
 8178    ) {
 8179        self.transact(cx, |this, cx| {
 8180            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8181                s.move_with(|map, selection| {
 8182                    if selection.is_empty() {
 8183                        let cursor = movement::next_subword_end(map, selection.head());
 8184                        selection.set_head(cursor, SelectionGoal::None);
 8185                    }
 8186                });
 8187            });
 8188            this.insert("", cx);
 8189        });
 8190    }
 8191
 8192    pub fn move_to_beginning_of_line(
 8193        &mut self,
 8194        action: &MoveToBeginningOfLine,
 8195        cx: &mut ViewContext<Self>,
 8196    ) {
 8197        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8198            s.move_cursors_with(|map, head, _| {
 8199                (
 8200                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8201                    SelectionGoal::None,
 8202                )
 8203            });
 8204        })
 8205    }
 8206
 8207    pub fn select_to_beginning_of_line(
 8208        &mut self,
 8209        action: &SelectToBeginningOfLine,
 8210        cx: &mut ViewContext<Self>,
 8211    ) {
 8212        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8213            s.move_heads_with(|map, head, _| {
 8214                (
 8215                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8216                    SelectionGoal::None,
 8217                )
 8218            });
 8219        });
 8220    }
 8221
 8222    pub fn delete_to_beginning_of_line(
 8223        &mut self,
 8224        _: &DeleteToBeginningOfLine,
 8225        cx: &mut ViewContext<Self>,
 8226    ) {
 8227        self.transact(cx, |this, cx| {
 8228            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8229                s.move_with(|_, selection| {
 8230                    selection.reversed = true;
 8231                });
 8232            });
 8233
 8234            this.select_to_beginning_of_line(
 8235                &SelectToBeginningOfLine {
 8236                    stop_at_soft_wraps: false,
 8237                },
 8238                cx,
 8239            );
 8240            this.backspace(&Backspace, cx);
 8241        });
 8242    }
 8243
 8244    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8245        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8246            s.move_cursors_with(|map, head, _| {
 8247                (
 8248                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8249                    SelectionGoal::None,
 8250                )
 8251            });
 8252        })
 8253    }
 8254
 8255    pub fn select_to_end_of_line(
 8256        &mut self,
 8257        action: &SelectToEndOfLine,
 8258        cx: &mut ViewContext<Self>,
 8259    ) {
 8260        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8261            s.move_heads_with(|map, head, _| {
 8262                (
 8263                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8264                    SelectionGoal::None,
 8265                )
 8266            });
 8267        })
 8268    }
 8269
 8270    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8271        self.transact(cx, |this, cx| {
 8272            this.select_to_end_of_line(
 8273                &SelectToEndOfLine {
 8274                    stop_at_soft_wraps: false,
 8275                },
 8276                cx,
 8277            );
 8278            this.delete(&Delete, cx);
 8279        });
 8280    }
 8281
 8282    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8283        self.transact(cx, |this, cx| {
 8284            this.select_to_end_of_line(
 8285                &SelectToEndOfLine {
 8286                    stop_at_soft_wraps: false,
 8287                },
 8288                cx,
 8289            );
 8290            this.cut(&Cut, cx);
 8291        });
 8292    }
 8293
 8294    pub fn move_to_start_of_paragraph(
 8295        &mut self,
 8296        _: &MoveToStartOfParagraph,
 8297        cx: &mut ViewContext<Self>,
 8298    ) {
 8299        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8300            cx.propagate();
 8301            return;
 8302        }
 8303
 8304        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8305            s.move_with(|map, selection| {
 8306                selection.collapse_to(
 8307                    movement::start_of_paragraph(map, selection.head(), 1),
 8308                    SelectionGoal::None,
 8309                )
 8310            });
 8311        })
 8312    }
 8313
 8314    pub fn move_to_end_of_paragraph(
 8315        &mut self,
 8316        _: &MoveToEndOfParagraph,
 8317        cx: &mut ViewContext<Self>,
 8318    ) {
 8319        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8320            cx.propagate();
 8321            return;
 8322        }
 8323
 8324        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8325            s.move_with(|map, selection| {
 8326                selection.collapse_to(
 8327                    movement::end_of_paragraph(map, selection.head(), 1),
 8328                    SelectionGoal::None,
 8329                )
 8330            });
 8331        })
 8332    }
 8333
 8334    pub fn select_to_start_of_paragraph(
 8335        &mut self,
 8336        _: &SelectToStartOfParagraph,
 8337        cx: &mut ViewContext<Self>,
 8338    ) {
 8339        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8340            cx.propagate();
 8341            return;
 8342        }
 8343
 8344        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8345            s.move_heads_with(|map, head, _| {
 8346                (
 8347                    movement::start_of_paragraph(map, head, 1),
 8348                    SelectionGoal::None,
 8349                )
 8350            });
 8351        })
 8352    }
 8353
 8354    pub fn select_to_end_of_paragraph(
 8355        &mut self,
 8356        _: &SelectToEndOfParagraph,
 8357        cx: &mut ViewContext<Self>,
 8358    ) {
 8359        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8360            cx.propagate();
 8361            return;
 8362        }
 8363
 8364        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8365            s.move_heads_with(|map, head, _| {
 8366                (
 8367                    movement::end_of_paragraph(map, head, 1),
 8368                    SelectionGoal::None,
 8369                )
 8370            });
 8371        })
 8372    }
 8373
 8374    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8375        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8376            cx.propagate();
 8377            return;
 8378        }
 8379
 8380        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8381            s.select_ranges(vec![0..0]);
 8382        });
 8383    }
 8384
 8385    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8386        let mut selection = self.selections.last::<Point>(cx);
 8387        selection.set_head(Point::zero(), SelectionGoal::None);
 8388
 8389        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8390            s.select(vec![selection]);
 8391        });
 8392    }
 8393
 8394    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8395        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8396            cx.propagate();
 8397            return;
 8398        }
 8399
 8400        let cursor = self.buffer.read(cx).read(cx).len();
 8401        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8402            s.select_ranges(vec![cursor..cursor])
 8403        });
 8404    }
 8405
 8406    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8407        self.nav_history = nav_history;
 8408    }
 8409
 8410    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8411        self.nav_history.as_ref()
 8412    }
 8413
 8414    fn push_to_nav_history(
 8415        &mut self,
 8416        cursor_anchor: Anchor,
 8417        new_position: Option<Point>,
 8418        cx: &mut ViewContext<Self>,
 8419    ) {
 8420        if let Some(nav_history) = self.nav_history.as_mut() {
 8421            let buffer = self.buffer.read(cx).read(cx);
 8422            let cursor_position = cursor_anchor.to_point(&buffer);
 8423            let scroll_state = self.scroll_manager.anchor();
 8424            let scroll_top_row = scroll_state.top_row(&buffer);
 8425            drop(buffer);
 8426
 8427            if let Some(new_position) = new_position {
 8428                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8429                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8430                    return;
 8431                }
 8432            }
 8433
 8434            nav_history.push(
 8435                Some(NavigationData {
 8436                    cursor_anchor,
 8437                    cursor_position,
 8438                    scroll_anchor: scroll_state,
 8439                    scroll_top_row,
 8440                }),
 8441                cx,
 8442            );
 8443        }
 8444    }
 8445
 8446    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8447        let buffer = self.buffer.read(cx).snapshot(cx);
 8448        let mut selection = self.selections.first::<usize>(cx);
 8449        selection.set_head(buffer.len(), SelectionGoal::None);
 8450        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8451            s.select(vec![selection]);
 8452        });
 8453    }
 8454
 8455    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8456        let end = self.buffer.read(cx).read(cx).len();
 8457        self.change_selections(None, cx, |s| {
 8458            s.select_ranges(vec![0..end]);
 8459        });
 8460    }
 8461
 8462    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8463        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8464        let mut selections = self.selections.all::<Point>(cx);
 8465        let max_point = display_map.buffer_snapshot.max_point();
 8466        for selection in &mut selections {
 8467            let rows = selection.spanned_rows(true, &display_map);
 8468            selection.start = Point::new(rows.start.0, 0);
 8469            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8470            selection.reversed = false;
 8471        }
 8472        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8473            s.select(selections);
 8474        });
 8475    }
 8476
 8477    pub fn split_selection_into_lines(
 8478        &mut self,
 8479        _: &SplitSelectionIntoLines,
 8480        cx: &mut ViewContext<Self>,
 8481    ) {
 8482        let mut to_unfold = Vec::new();
 8483        let mut new_selection_ranges = Vec::new();
 8484        {
 8485            let selections = self.selections.all::<Point>(cx);
 8486            let buffer = self.buffer.read(cx).read(cx);
 8487            for selection in selections {
 8488                for row in selection.start.row..selection.end.row {
 8489                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8490                    new_selection_ranges.push(cursor..cursor);
 8491                }
 8492                new_selection_ranges.push(selection.end..selection.end);
 8493                to_unfold.push(selection.start..selection.end);
 8494            }
 8495        }
 8496        self.unfold_ranges(&to_unfold, true, true, cx);
 8497        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8498            s.select_ranges(new_selection_ranges);
 8499        });
 8500    }
 8501
 8502    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8503        self.add_selection(true, cx);
 8504    }
 8505
 8506    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8507        self.add_selection(false, cx);
 8508    }
 8509
 8510    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8511        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8512        let mut selections = self.selections.all::<Point>(cx);
 8513        let text_layout_details = self.text_layout_details(cx);
 8514        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8515            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8516            let range = oldest_selection.display_range(&display_map).sorted();
 8517
 8518            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8519            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8520            let positions = start_x.min(end_x)..start_x.max(end_x);
 8521
 8522            selections.clear();
 8523            let mut stack = Vec::new();
 8524            for row in range.start.row().0..=range.end.row().0 {
 8525                if let Some(selection) = self.selections.build_columnar_selection(
 8526                    &display_map,
 8527                    DisplayRow(row),
 8528                    &positions,
 8529                    oldest_selection.reversed,
 8530                    &text_layout_details,
 8531                ) {
 8532                    stack.push(selection.id);
 8533                    selections.push(selection);
 8534                }
 8535            }
 8536
 8537            if above {
 8538                stack.reverse();
 8539            }
 8540
 8541            AddSelectionsState { above, stack }
 8542        });
 8543
 8544        let last_added_selection = *state.stack.last().unwrap();
 8545        let mut new_selections = Vec::new();
 8546        if above == state.above {
 8547            let end_row = if above {
 8548                DisplayRow(0)
 8549            } else {
 8550                display_map.max_point().row()
 8551            };
 8552
 8553            'outer: for selection in selections {
 8554                if selection.id == last_added_selection {
 8555                    let range = selection.display_range(&display_map).sorted();
 8556                    debug_assert_eq!(range.start.row(), range.end.row());
 8557                    let mut row = range.start.row();
 8558                    let positions =
 8559                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8560                            px(start)..px(end)
 8561                        } else {
 8562                            let start_x =
 8563                                display_map.x_for_display_point(range.start, &text_layout_details);
 8564                            let end_x =
 8565                                display_map.x_for_display_point(range.end, &text_layout_details);
 8566                            start_x.min(end_x)..start_x.max(end_x)
 8567                        };
 8568
 8569                    while row != end_row {
 8570                        if above {
 8571                            row.0 -= 1;
 8572                        } else {
 8573                            row.0 += 1;
 8574                        }
 8575
 8576                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8577                            &display_map,
 8578                            row,
 8579                            &positions,
 8580                            selection.reversed,
 8581                            &text_layout_details,
 8582                        ) {
 8583                            state.stack.push(new_selection.id);
 8584                            if above {
 8585                                new_selections.push(new_selection);
 8586                                new_selections.push(selection);
 8587                            } else {
 8588                                new_selections.push(selection);
 8589                                new_selections.push(new_selection);
 8590                            }
 8591
 8592                            continue 'outer;
 8593                        }
 8594                    }
 8595                }
 8596
 8597                new_selections.push(selection);
 8598            }
 8599        } else {
 8600            new_selections = selections;
 8601            new_selections.retain(|s| s.id != last_added_selection);
 8602            state.stack.pop();
 8603        }
 8604
 8605        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8606            s.select(new_selections);
 8607        });
 8608        if state.stack.len() > 1 {
 8609            self.add_selections_state = Some(state);
 8610        }
 8611    }
 8612
 8613    pub fn select_next_match_internal(
 8614        &mut self,
 8615        display_map: &DisplaySnapshot,
 8616        replace_newest: bool,
 8617        autoscroll: Option<Autoscroll>,
 8618        cx: &mut ViewContext<Self>,
 8619    ) -> Result<()> {
 8620        fn select_next_match_ranges(
 8621            this: &mut Editor,
 8622            range: Range<usize>,
 8623            replace_newest: bool,
 8624            auto_scroll: Option<Autoscroll>,
 8625            cx: &mut ViewContext<Editor>,
 8626        ) {
 8627            this.unfold_ranges(&[range.clone()], false, true, cx);
 8628            this.change_selections(auto_scroll, cx, |s| {
 8629                if replace_newest {
 8630                    s.delete(s.newest_anchor().id);
 8631                }
 8632                s.insert_range(range.clone());
 8633            });
 8634        }
 8635
 8636        let buffer = &display_map.buffer_snapshot;
 8637        let mut selections = self.selections.all::<usize>(cx);
 8638        if let Some(mut select_next_state) = self.select_next_state.take() {
 8639            let query = &select_next_state.query;
 8640            if !select_next_state.done {
 8641                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8642                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8643                let mut next_selected_range = None;
 8644
 8645                let bytes_after_last_selection =
 8646                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8647                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8648                let query_matches = query
 8649                    .stream_find_iter(bytes_after_last_selection)
 8650                    .map(|result| (last_selection.end, result))
 8651                    .chain(
 8652                        query
 8653                            .stream_find_iter(bytes_before_first_selection)
 8654                            .map(|result| (0, result)),
 8655                    );
 8656
 8657                for (start_offset, query_match) in query_matches {
 8658                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8659                    let offset_range =
 8660                        start_offset + query_match.start()..start_offset + query_match.end();
 8661                    let display_range = offset_range.start.to_display_point(display_map)
 8662                        ..offset_range.end.to_display_point(display_map);
 8663
 8664                    if !select_next_state.wordwise
 8665                        || (!movement::is_inside_word(display_map, display_range.start)
 8666                            && !movement::is_inside_word(display_map, display_range.end))
 8667                    {
 8668                        // TODO: This is n^2, because we might check all the selections
 8669                        if !selections
 8670                            .iter()
 8671                            .any(|selection| selection.range().overlaps(&offset_range))
 8672                        {
 8673                            next_selected_range = Some(offset_range);
 8674                            break;
 8675                        }
 8676                    }
 8677                }
 8678
 8679                if let Some(next_selected_range) = next_selected_range {
 8680                    select_next_match_ranges(
 8681                        self,
 8682                        next_selected_range,
 8683                        replace_newest,
 8684                        autoscroll,
 8685                        cx,
 8686                    );
 8687                } else {
 8688                    select_next_state.done = true;
 8689                }
 8690            }
 8691
 8692            self.select_next_state = Some(select_next_state);
 8693        } else {
 8694            let mut only_carets = true;
 8695            let mut same_text_selected = true;
 8696            let mut selected_text = None;
 8697
 8698            let mut selections_iter = selections.iter().peekable();
 8699            while let Some(selection) = selections_iter.next() {
 8700                if selection.start != selection.end {
 8701                    only_carets = false;
 8702                }
 8703
 8704                if same_text_selected {
 8705                    if selected_text.is_none() {
 8706                        selected_text =
 8707                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8708                    }
 8709
 8710                    if let Some(next_selection) = selections_iter.peek() {
 8711                        if next_selection.range().len() == selection.range().len() {
 8712                            let next_selected_text = buffer
 8713                                .text_for_range(next_selection.range())
 8714                                .collect::<String>();
 8715                            if Some(next_selected_text) != selected_text {
 8716                                same_text_selected = false;
 8717                                selected_text = None;
 8718                            }
 8719                        } else {
 8720                            same_text_selected = false;
 8721                            selected_text = None;
 8722                        }
 8723                    }
 8724                }
 8725            }
 8726
 8727            if only_carets {
 8728                for selection in &mut selections {
 8729                    let word_range = movement::surrounding_word(
 8730                        display_map,
 8731                        selection.start.to_display_point(display_map),
 8732                    );
 8733                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8734                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8735                    selection.goal = SelectionGoal::None;
 8736                    selection.reversed = false;
 8737                    select_next_match_ranges(
 8738                        self,
 8739                        selection.start..selection.end,
 8740                        replace_newest,
 8741                        autoscroll,
 8742                        cx,
 8743                    );
 8744                }
 8745
 8746                if selections.len() == 1 {
 8747                    let selection = selections
 8748                        .last()
 8749                        .expect("ensured that there's only one selection");
 8750                    let query = buffer
 8751                        .text_for_range(selection.start..selection.end)
 8752                        .collect::<String>();
 8753                    let is_empty = query.is_empty();
 8754                    let select_state = SelectNextState {
 8755                        query: AhoCorasick::new(&[query])?,
 8756                        wordwise: true,
 8757                        done: is_empty,
 8758                    };
 8759                    self.select_next_state = Some(select_state);
 8760                } else {
 8761                    self.select_next_state = None;
 8762                }
 8763            } else if let Some(selected_text) = selected_text {
 8764                self.select_next_state = Some(SelectNextState {
 8765                    query: AhoCorasick::new(&[selected_text])?,
 8766                    wordwise: false,
 8767                    done: false,
 8768                });
 8769                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8770            }
 8771        }
 8772        Ok(())
 8773    }
 8774
 8775    pub fn select_all_matches(
 8776        &mut self,
 8777        _action: &SelectAllMatches,
 8778        cx: &mut ViewContext<Self>,
 8779    ) -> Result<()> {
 8780        self.push_to_selection_history();
 8781        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8782
 8783        self.select_next_match_internal(&display_map, false, None, cx)?;
 8784        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8785            return Ok(());
 8786        };
 8787        if select_next_state.done {
 8788            return Ok(());
 8789        }
 8790
 8791        let mut new_selections = self.selections.all::<usize>(cx);
 8792
 8793        let buffer = &display_map.buffer_snapshot;
 8794        let query_matches = select_next_state
 8795            .query
 8796            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8797
 8798        for query_match in query_matches {
 8799            let query_match = query_match.unwrap(); // can only fail due to I/O
 8800            let offset_range = query_match.start()..query_match.end();
 8801            let display_range = offset_range.start.to_display_point(&display_map)
 8802                ..offset_range.end.to_display_point(&display_map);
 8803
 8804            if !select_next_state.wordwise
 8805                || (!movement::is_inside_word(&display_map, display_range.start)
 8806                    && !movement::is_inside_word(&display_map, display_range.end))
 8807            {
 8808                self.selections.change_with(cx, |selections| {
 8809                    new_selections.push(Selection {
 8810                        id: selections.new_selection_id(),
 8811                        start: offset_range.start,
 8812                        end: offset_range.end,
 8813                        reversed: false,
 8814                        goal: SelectionGoal::None,
 8815                    });
 8816                });
 8817            }
 8818        }
 8819
 8820        new_selections.sort_by_key(|selection| selection.start);
 8821        let mut ix = 0;
 8822        while ix + 1 < new_selections.len() {
 8823            let current_selection = &new_selections[ix];
 8824            let next_selection = &new_selections[ix + 1];
 8825            if current_selection.range().overlaps(&next_selection.range()) {
 8826                if current_selection.id < next_selection.id {
 8827                    new_selections.remove(ix + 1);
 8828                } else {
 8829                    new_selections.remove(ix);
 8830                }
 8831            } else {
 8832                ix += 1;
 8833            }
 8834        }
 8835
 8836        select_next_state.done = true;
 8837        self.unfold_ranges(
 8838            &new_selections
 8839                .iter()
 8840                .map(|selection| selection.range())
 8841                .collect::<Vec<_>>(),
 8842            false,
 8843            false,
 8844            cx,
 8845        );
 8846        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8847            selections.select(new_selections)
 8848        });
 8849
 8850        Ok(())
 8851    }
 8852
 8853    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8854        self.push_to_selection_history();
 8855        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8856        self.select_next_match_internal(
 8857            &display_map,
 8858            action.replace_newest,
 8859            Some(Autoscroll::newest()),
 8860            cx,
 8861        )?;
 8862        Ok(())
 8863    }
 8864
 8865    pub fn select_previous(
 8866        &mut self,
 8867        action: &SelectPrevious,
 8868        cx: &mut ViewContext<Self>,
 8869    ) -> Result<()> {
 8870        self.push_to_selection_history();
 8871        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8872        let buffer = &display_map.buffer_snapshot;
 8873        let mut selections = self.selections.all::<usize>(cx);
 8874        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8875            let query = &select_prev_state.query;
 8876            if !select_prev_state.done {
 8877                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8878                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8879                let mut next_selected_range = None;
 8880                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8881                let bytes_before_last_selection =
 8882                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8883                let bytes_after_first_selection =
 8884                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8885                let query_matches = query
 8886                    .stream_find_iter(bytes_before_last_selection)
 8887                    .map(|result| (last_selection.start, result))
 8888                    .chain(
 8889                        query
 8890                            .stream_find_iter(bytes_after_first_selection)
 8891                            .map(|result| (buffer.len(), result)),
 8892                    );
 8893                for (end_offset, query_match) in query_matches {
 8894                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8895                    let offset_range =
 8896                        end_offset - query_match.end()..end_offset - query_match.start();
 8897                    let display_range = offset_range.start.to_display_point(&display_map)
 8898                        ..offset_range.end.to_display_point(&display_map);
 8899
 8900                    if !select_prev_state.wordwise
 8901                        || (!movement::is_inside_word(&display_map, display_range.start)
 8902                            && !movement::is_inside_word(&display_map, display_range.end))
 8903                    {
 8904                        next_selected_range = Some(offset_range);
 8905                        break;
 8906                    }
 8907                }
 8908
 8909                if let Some(next_selected_range) = next_selected_range {
 8910                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8911                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8912                        if action.replace_newest {
 8913                            s.delete(s.newest_anchor().id);
 8914                        }
 8915                        s.insert_range(next_selected_range);
 8916                    });
 8917                } else {
 8918                    select_prev_state.done = true;
 8919                }
 8920            }
 8921
 8922            self.select_prev_state = Some(select_prev_state);
 8923        } else {
 8924            let mut only_carets = true;
 8925            let mut same_text_selected = true;
 8926            let mut selected_text = None;
 8927
 8928            let mut selections_iter = selections.iter().peekable();
 8929            while let Some(selection) = selections_iter.next() {
 8930                if selection.start != selection.end {
 8931                    only_carets = false;
 8932                }
 8933
 8934                if same_text_selected {
 8935                    if selected_text.is_none() {
 8936                        selected_text =
 8937                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8938                    }
 8939
 8940                    if let Some(next_selection) = selections_iter.peek() {
 8941                        if next_selection.range().len() == selection.range().len() {
 8942                            let next_selected_text = buffer
 8943                                .text_for_range(next_selection.range())
 8944                                .collect::<String>();
 8945                            if Some(next_selected_text) != selected_text {
 8946                                same_text_selected = false;
 8947                                selected_text = None;
 8948                            }
 8949                        } else {
 8950                            same_text_selected = false;
 8951                            selected_text = None;
 8952                        }
 8953                    }
 8954                }
 8955            }
 8956
 8957            if only_carets {
 8958                for selection in &mut selections {
 8959                    let word_range = movement::surrounding_word(
 8960                        &display_map,
 8961                        selection.start.to_display_point(&display_map),
 8962                    );
 8963                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8964                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8965                    selection.goal = SelectionGoal::None;
 8966                    selection.reversed = false;
 8967                }
 8968                if selections.len() == 1 {
 8969                    let selection = selections
 8970                        .last()
 8971                        .expect("ensured that there's only one selection");
 8972                    let query = buffer
 8973                        .text_for_range(selection.start..selection.end)
 8974                        .collect::<String>();
 8975                    let is_empty = query.is_empty();
 8976                    let select_state = SelectNextState {
 8977                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8978                        wordwise: true,
 8979                        done: is_empty,
 8980                    };
 8981                    self.select_prev_state = Some(select_state);
 8982                } else {
 8983                    self.select_prev_state = None;
 8984                }
 8985
 8986                self.unfold_ranges(
 8987                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8988                    false,
 8989                    true,
 8990                    cx,
 8991                );
 8992                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8993                    s.select(selections);
 8994                });
 8995            } else if let Some(selected_text) = selected_text {
 8996                self.select_prev_state = Some(SelectNextState {
 8997                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8998                    wordwise: false,
 8999                    done: false,
 9000                });
 9001                self.select_previous(action, cx)?;
 9002            }
 9003        }
 9004        Ok(())
 9005    }
 9006
 9007    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 9008        if self.read_only(cx) {
 9009            return;
 9010        }
 9011        let text_layout_details = &self.text_layout_details(cx);
 9012        self.transact(cx, |this, cx| {
 9013            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9014            let mut edits = Vec::new();
 9015            let mut selection_edit_ranges = Vec::new();
 9016            let mut last_toggled_row = None;
 9017            let snapshot = this.buffer.read(cx).read(cx);
 9018            let empty_str: Arc<str> = Arc::default();
 9019            let mut suffixes_inserted = Vec::new();
 9020            let ignore_indent = action.ignore_indent;
 9021
 9022            fn comment_prefix_range(
 9023                snapshot: &MultiBufferSnapshot,
 9024                row: MultiBufferRow,
 9025                comment_prefix: &str,
 9026                comment_prefix_whitespace: &str,
 9027                ignore_indent: bool,
 9028            ) -> Range<Point> {
 9029                let indent_size = if ignore_indent {
 9030                    0
 9031                } else {
 9032                    snapshot.indent_size_for_line(row).len
 9033                };
 9034
 9035                let start = Point::new(row.0, indent_size);
 9036
 9037                let mut line_bytes = snapshot
 9038                    .bytes_in_range(start..snapshot.max_point())
 9039                    .flatten()
 9040                    .copied();
 9041
 9042                // If this line currently begins with the line comment prefix, then record
 9043                // the range containing the prefix.
 9044                if line_bytes
 9045                    .by_ref()
 9046                    .take(comment_prefix.len())
 9047                    .eq(comment_prefix.bytes())
 9048                {
 9049                    // Include any whitespace that matches the comment prefix.
 9050                    let matching_whitespace_len = line_bytes
 9051                        .zip(comment_prefix_whitespace.bytes())
 9052                        .take_while(|(a, b)| a == b)
 9053                        .count() as u32;
 9054                    let end = Point::new(
 9055                        start.row,
 9056                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9057                    );
 9058                    start..end
 9059                } else {
 9060                    start..start
 9061                }
 9062            }
 9063
 9064            fn comment_suffix_range(
 9065                snapshot: &MultiBufferSnapshot,
 9066                row: MultiBufferRow,
 9067                comment_suffix: &str,
 9068                comment_suffix_has_leading_space: bool,
 9069            ) -> Range<Point> {
 9070                let end = Point::new(row.0, snapshot.line_len(row));
 9071                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9072
 9073                let mut line_end_bytes = snapshot
 9074                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9075                    .flatten()
 9076                    .copied();
 9077
 9078                let leading_space_len = if suffix_start_column > 0
 9079                    && line_end_bytes.next() == Some(b' ')
 9080                    && comment_suffix_has_leading_space
 9081                {
 9082                    1
 9083                } else {
 9084                    0
 9085                };
 9086
 9087                // If this line currently begins with the line comment prefix, then record
 9088                // the range containing the prefix.
 9089                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9090                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9091                    start..end
 9092                } else {
 9093                    end..end
 9094                }
 9095            }
 9096
 9097            // TODO: Handle selections that cross excerpts
 9098            for selection in &mut selections {
 9099                let start_column = snapshot
 9100                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9101                    .len;
 9102                let language = if let Some(language) =
 9103                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9104                {
 9105                    language
 9106                } else {
 9107                    continue;
 9108                };
 9109
 9110                selection_edit_ranges.clear();
 9111
 9112                // If multiple selections contain a given row, avoid processing that
 9113                // row more than once.
 9114                let mut start_row = MultiBufferRow(selection.start.row);
 9115                if last_toggled_row == Some(start_row) {
 9116                    start_row = start_row.next_row();
 9117                }
 9118                let end_row =
 9119                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9120                        MultiBufferRow(selection.end.row - 1)
 9121                    } else {
 9122                        MultiBufferRow(selection.end.row)
 9123                    };
 9124                last_toggled_row = Some(end_row);
 9125
 9126                if start_row > end_row {
 9127                    continue;
 9128                }
 9129
 9130                // If the language has line comments, toggle those.
 9131                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9132
 9133                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9134                if ignore_indent {
 9135                    full_comment_prefixes = full_comment_prefixes
 9136                        .into_iter()
 9137                        .map(|s| Arc::from(s.trim_end()))
 9138                        .collect();
 9139                }
 9140
 9141                if !full_comment_prefixes.is_empty() {
 9142                    let first_prefix = full_comment_prefixes
 9143                        .first()
 9144                        .expect("prefixes is non-empty");
 9145                    let prefix_trimmed_lengths = full_comment_prefixes
 9146                        .iter()
 9147                        .map(|p| p.trim_end_matches(' ').len())
 9148                        .collect::<SmallVec<[usize; 4]>>();
 9149
 9150                    let mut all_selection_lines_are_comments = true;
 9151
 9152                    for row in start_row.0..=end_row.0 {
 9153                        let row = MultiBufferRow(row);
 9154                        if start_row < end_row && snapshot.is_line_blank(row) {
 9155                            continue;
 9156                        }
 9157
 9158                        let prefix_range = full_comment_prefixes
 9159                            .iter()
 9160                            .zip(prefix_trimmed_lengths.iter().copied())
 9161                            .map(|(prefix, trimmed_prefix_len)| {
 9162                                comment_prefix_range(
 9163                                    snapshot.deref(),
 9164                                    row,
 9165                                    &prefix[..trimmed_prefix_len],
 9166                                    &prefix[trimmed_prefix_len..],
 9167                                    ignore_indent,
 9168                                )
 9169                            })
 9170                            .max_by_key(|range| range.end.column - range.start.column)
 9171                            .expect("prefixes is non-empty");
 9172
 9173                        if prefix_range.is_empty() {
 9174                            all_selection_lines_are_comments = false;
 9175                        }
 9176
 9177                        selection_edit_ranges.push(prefix_range);
 9178                    }
 9179
 9180                    if all_selection_lines_are_comments {
 9181                        edits.extend(
 9182                            selection_edit_ranges
 9183                                .iter()
 9184                                .cloned()
 9185                                .map(|range| (range, empty_str.clone())),
 9186                        );
 9187                    } else {
 9188                        let min_column = selection_edit_ranges
 9189                            .iter()
 9190                            .map(|range| range.start.column)
 9191                            .min()
 9192                            .unwrap_or(0);
 9193                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9194                            let position = Point::new(range.start.row, min_column);
 9195                            (position..position, first_prefix.clone())
 9196                        }));
 9197                    }
 9198                } else if let Some((full_comment_prefix, comment_suffix)) =
 9199                    language.block_comment_delimiters()
 9200                {
 9201                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9202                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9203                    let prefix_range = comment_prefix_range(
 9204                        snapshot.deref(),
 9205                        start_row,
 9206                        comment_prefix,
 9207                        comment_prefix_whitespace,
 9208                        ignore_indent,
 9209                    );
 9210                    let suffix_range = comment_suffix_range(
 9211                        snapshot.deref(),
 9212                        end_row,
 9213                        comment_suffix.trim_start_matches(' '),
 9214                        comment_suffix.starts_with(' '),
 9215                    );
 9216
 9217                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9218                        edits.push((
 9219                            prefix_range.start..prefix_range.start,
 9220                            full_comment_prefix.clone(),
 9221                        ));
 9222                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9223                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9224                    } else {
 9225                        edits.push((prefix_range, empty_str.clone()));
 9226                        edits.push((suffix_range, empty_str.clone()));
 9227                    }
 9228                } else {
 9229                    continue;
 9230                }
 9231            }
 9232
 9233            drop(snapshot);
 9234            this.buffer.update(cx, |buffer, cx| {
 9235                buffer.edit(edits, None, cx);
 9236            });
 9237
 9238            // Adjust selections so that they end before any comment suffixes that
 9239            // were inserted.
 9240            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9241            let mut selections = this.selections.all::<Point>(cx);
 9242            let snapshot = this.buffer.read(cx).read(cx);
 9243            for selection in &mut selections {
 9244                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9245                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9246                        Ordering::Less => {
 9247                            suffixes_inserted.next();
 9248                            continue;
 9249                        }
 9250                        Ordering::Greater => break,
 9251                        Ordering::Equal => {
 9252                            if selection.end.column == snapshot.line_len(row) {
 9253                                if selection.is_empty() {
 9254                                    selection.start.column -= suffix_len as u32;
 9255                                }
 9256                                selection.end.column -= suffix_len as u32;
 9257                            }
 9258                            break;
 9259                        }
 9260                    }
 9261                }
 9262            }
 9263
 9264            drop(snapshot);
 9265            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9266
 9267            let selections = this.selections.all::<Point>(cx);
 9268            let selections_on_single_row = selections.windows(2).all(|selections| {
 9269                selections[0].start.row == selections[1].start.row
 9270                    && selections[0].end.row == selections[1].end.row
 9271                    && selections[0].start.row == selections[0].end.row
 9272            });
 9273            let selections_selecting = selections
 9274                .iter()
 9275                .any(|selection| selection.start != selection.end);
 9276            let advance_downwards = action.advance_downwards
 9277                && selections_on_single_row
 9278                && !selections_selecting
 9279                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9280
 9281            if advance_downwards {
 9282                let snapshot = this.buffer.read(cx).snapshot(cx);
 9283
 9284                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9285                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9286                        let mut point = display_point.to_point(display_snapshot);
 9287                        point.row += 1;
 9288                        point = snapshot.clip_point(point, Bias::Left);
 9289                        let display_point = point.to_display_point(display_snapshot);
 9290                        let goal = SelectionGoal::HorizontalPosition(
 9291                            display_snapshot
 9292                                .x_for_display_point(display_point, text_layout_details)
 9293                                .into(),
 9294                        );
 9295                        (display_point, goal)
 9296                    })
 9297                });
 9298            }
 9299        });
 9300    }
 9301
 9302    pub fn select_enclosing_symbol(
 9303        &mut self,
 9304        _: &SelectEnclosingSymbol,
 9305        cx: &mut ViewContext<Self>,
 9306    ) {
 9307        let buffer = self.buffer.read(cx).snapshot(cx);
 9308        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9309
 9310        fn update_selection(
 9311            selection: &Selection<usize>,
 9312            buffer_snap: &MultiBufferSnapshot,
 9313        ) -> Option<Selection<usize>> {
 9314            let cursor = selection.head();
 9315            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9316            for symbol in symbols.iter().rev() {
 9317                let start = symbol.range.start.to_offset(buffer_snap);
 9318                let end = symbol.range.end.to_offset(buffer_snap);
 9319                let new_range = start..end;
 9320                if start < selection.start || end > selection.end {
 9321                    return Some(Selection {
 9322                        id: selection.id,
 9323                        start: new_range.start,
 9324                        end: new_range.end,
 9325                        goal: SelectionGoal::None,
 9326                        reversed: selection.reversed,
 9327                    });
 9328                }
 9329            }
 9330            None
 9331        }
 9332
 9333        let mut selected_larger_symbol = false;
 9334        let new_selections = old_selections
 9335            .iter()
 9336            .map(|selection| match update_selection(selection, &buffer) {
 9337                Some(new_selection) => {
 9338                    if new_selection.range() != selection.range() {
 9339                        selected_larger_symbol = true;
 9340                    }
 9341                    new_selection
 9342                }
 9343                None => selection.clone(),
 9344            })
 9345            .collect::<Vec<_>>();
 9346
 9347        if selected_larger_symbol {
 9348            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9349                s.select(new_selections);
 9350            });
 9351        }
 9352    }
 9353
 9354    pub fn select_larger_syntax_node(
 9355        &mut self,
 9356        _: &SelectLargerSyntaxNode,
 9357        cx: &mut ViewContext<Self>,
 9358    ) {
 9359        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9360        let buffer = self.buffer.read(cx).snapshot(cx);
 9361        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9362
 9363        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9364        let mut selected_larger_node = false;
 9365        let new_selections = old_selections
 9366            .iter()
 9367            .map(|selection| {
 9368                let old_range = selection.start..selection.end;
 9369                let mut new_range = old_range.clone();
 9370                while let Some(containing_range) =
 9371                    buffer.range_for_syntax_ancestor(new_range.clone())
 9372                {
 9373                    new_range = containing_range;
 9374                    if !display_map.intersects_fold(new_range.start)
 9375                        && !display_map.intersects_fold(new_range.end)
 9376                    {
 9377                        break;
 9378                    }
 9379                }
 9380
 9381                selected_larger_node |= new_range != old_range;
 9382                Selection {
 9383                    id: selection.id,
 9384                    start: new_range.start,
 9385                    end: new_range.end,
 9386                    goal: SelectionGoal::None,
 9387                    reversed: selection.reversed,
 9388                }
 9389            })
 9390            .collect::<Vec<_>>();
 9391
 9392        if selected_larger_node {
 9393            stack.push(old_selections);
 9394            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9395                s.select(new_selections);
 9396            });
 9397        }
 9398        self.select_larger_syntax_node_stack = stack;
 9399    }
 9400
 9401    pub fn select_smaller_syntax_node(
 9402        &mut self,
 9403        _: &SelectSmallerSyntaxNode,
 9404        cx: &mut ViewContext<Self>,
 9405    ) {
 9406        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9407        if let Some(selections) = stack.pop() {
 9408            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9409                s.select(selections.to_vec());
 9410            });
 9411        }
 9412        self.select_larger_syntax_node_stack = stack;
 9413    }
 9414
 9415    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9416        if !EditorSettings::get_global(cx).gutter.runnables {
 9417            self.clear_tasks();
 9418            return Task::ready(());
 9419        }
 9420        let project = self.project.as_ref().map(Model::downgrade);
 9421        cx.spawn(|this, mut cx| async move {
 9422            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9423            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9424                return;
 9425            };
 9426            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9427                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9428            }) else {
 9429                return;
 9430            };
 9431
 9432            let hide_runnables = project
 9433                .update(&mut cx, |project, cx| {
 9434                    // Do not display any test indicators in non-dev server remote projects.
 9435                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9436                })
 9437                .unwrap_or(true);
 9438            if hide_runnables {
 9439                return;
 9440            }
 9441            let new_rows =
 9442                cx.background_executor()
 9443                    .spawn({
 9444                        let snapshot = display_snapshot.clone();
 9445                        async move {
 9446                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9447                        }
 9448                    })
 9449                    .await;
 9450            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9451
 9452            this.update(&mut cx, |this, _| {
 9453                this.clear_tasks();
 9454                for (key, value) in rows {
 9455                    this.insert_tasks(key, value);
 9456                }
 9457            })
 9458            .ok();
 9459        })
 9460    }
 9461    fn fetch_runnable_ranges(
 9462        snapshot: &DisplaySnapshot,
 9463        range: Range<Anchor>,
 9464    ) -> Vec<language::RunnableRange> {
 9465        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9466    }
 9467
 9468    fn runnable_rows(
 9469        project: Model<Project>,
 9470        snapshot: DisplaySnapshot,
 9471        runnable_ranges: Vec<RunnableRange>,
 9472        mut cx: AsyncWindowContext,
 9473    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9474        runnable_ranges
 9475            .into_iter()
 9476            .filter_map(|mut runnable| {
 9477                let tasks = cx
 9478                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9479                    .ok()?;
 9480                if tasks.is_empty() {
 9481                    return None;
 9482                }
 9483
 9484                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9485
 9486                let row = snapshot
 9487                    .buffer_snapshot
 9488                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9489                    .1
 9490                    .start
 9491                    .row;
 9492
 9493                let context_range =
 9494                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9495                Some((
 9496                    (runnable.buffer_id, row),
 9497                    RunnableTasks {
 9498                        templates: tasks,
 9499                        offset: MultiBufferOffset(runnable.run_range.start),
 9500                        context_range,
 9501                        column: point.column,
 9502                        extra_variables: runnable.extra_captures,
 9503                    },
 9504                ))
 9505            })
 9506            .collect()
 9507    }
 9508
 9509    fn templates_with_tags(
 9510        project: &Model<Project>,
 9511        runnable: &mut Runnable,
 9512        cx: &WindowContext<'_>,
 9513    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9514        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9515            let (worktree_id, file) = project
 9516                .buffer_for_id(runnable.buffer, cx)
 9517                .and_then(|buffer| buffer.read(cx).file())
 9518                .map(|file| (file.worktree_id(cx), file.clone()))
 9519                .unzip();
 9520
 9521            (
 9522                project.task_store().read(cx).task_inventory().cloned(),
 9523                worktree_id,
 9524                file,
 9525            )
 9526        });
 9527
 9528        let tags = mem::take(&mut runnable.tags);
 9529        let mut tags: Vec<_> = tags
 9530            .into_iter()
 9531            .flat_map(|tag| {
 9532                let tag = tag.0.clone();
 9533                inventory
 9534                    .as_ref()
 9535                    .into_iter()
 9536                    .flat_map(|inventory| {
 9537                        inventory.read(cx).list_tasks(
 9538                            file.clone(),
 9539                            Some(runnable.language.clone()),
 9540                            worktree_id,
 9541                            cx,
 9542                        )
 9543                    })
 9544                    .filter(move |(_, template)| {
 9545                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9546                    })
 9547            })
 9548            .sorted_by_key(|(kind, _)| kind.to_owned())
 9549            .collect();
 9550        if let Some((leading_tag_source, _)) = tags.first() {
 9551            // Strongest source wins; if we have worktree tag binding, prefer that to
 9552            // global and language bindings;
 9553            // if we have a global binding, prefer that to language binding.
 9554            let first_mismatch = tags
 9555                .iter()
 9556                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9557            if let Some(index) = first_mismatch {
 9558                tags.truncate(index);
 9559            }
 9560        }
 9561
 9562        tags
 9563    }
 9564
 9565    pub fn move_to_enclosing_bracket(
 9566        &mut self,
 9567        _: &MoveToEnclosingBracket,
 9568        cx: &mut ViewContext<Self>,
 9569    ) {
 9570        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9571            s.move_offsets_with(|snapshot, selection| {
 9572                let Some(enclosing_bracket_ranges) =
 9573                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9574                else {
 9575                    return;
 9576                };
 9577
 9578                let mut best_length = usize::MAX;
 9579                let mut best_inside = false;
 9580                let mut best_in_bracket_range = false;
 9581                let mut best_destination = None;
 9582                for (open, close) in enclosing_bracket_ranges {
 9583                    let close = close.to_inclusive();
 9584                    let length = close.end() - open.start;
 9585                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9586                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9587                        || close.contains(&selection.head());
 9588
 9589                    // If best is next to a bracket and current isn't, skip
 9590                    if !in_bracket_range && best_in_bracket_range {
 9591                        continue;
 9592                    }
 9593
 9594                    // Prefer smaller lengths unless best is inside and current isn't
 9595                    if length > best_length && (best_inside || !inside) {
 9596                        continue;
 9597                    }
 9598
 9599                    best_length = length;
 9600                    best_inside = inside;
 9601                    best_in_bracket_range = in_bracket_range;
 9602                    best_destination = Some(
 9603                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9604                            if inside {
 9605                                open.end
 9606                            } else {
 9607                                open.start
 9608                            }
 9609                        } else if inside {
 9610                            *close.start()
 9611                        } else {
 9612                            *close.end()
 9613                        },
 9614                    );
 9615                }
 9616
 9617                if let Some(destination) = best_destination {
 9618                    selection.collapse_to(destination, SelectionGoal::None);
 9619                }
 9620            })
 9621        });
 9622    }
 9623
 9624    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9625        self.end_selection(cx);
 9626        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9627        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9628            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9629            self.select_next_state = entry.select_next_state;
 9630            self.select_prev_state = entry.select_prev_state;
 9631            self.add_selections_state = entry.add_selections_state;
 9632            self.request_autoscroll(Autoscroll::newest(), cx);
 9633        }
 9634        self.selection_history.mode = SelectionHistoryMode::Normal;
 9635    }
 9636
 9637    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9638        self.end_selection(cx);
 9639        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9640        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9641            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9642            self.select_next_state = entry.select_next_state;
 9643            self.select_prev_state = entry.select_prev_state;
 9644            self.add_selections_state = entry.add_selections_state;
 9645            self.request_autoscroll(Autoscroll::newest(), cx);
 9646        }
 9647        self.selection_history.mode = SelectionHistoryMode::Normal;
 9648    }
 9649
 9650    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9651        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9652    }
 9653
 9654    pub fn expand_excerpts_down(
 9655        &mut self,
 9656        action: &ExpandExcerptsDown,
 9657        cx: &mut ViewContext<Self>,
 9658    ) {
 9659        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9660    }
 9661
 9662    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9663        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9664    }
 9665
 9666    pub fn expand_excerpts_for_direction(
 9667        &mut self,
 9668        lines: u32,
 9669        direction: ExpandExcerptDirection,
 9670        cx: &mut ViewContext<Self>,
 9671    ) {
 9672        let selections = self.selections.disjoint_anchors();
 9673
 9674        let lines = if lines == 0 {
 9675            EditorSettings::get_global(cx).expand_excerpt_lines
 9676        } else {
 9677            lines
 9678        };
 9679
 9680        self.buffer.update(cx, |buffer, cx| {
 9681            buffer.expand_excerpts(
 9682                selections
 9683                    .iter()
 9684                    .map(|selection| selection.head().excerpt_id)
 9685                    .dedup(),
 9686                lines,
 9687                direction,
 9688                cx,
 9689            )
 9690        })
 9691    }
 9692
 9693    pub fn expand_excerpt(
 9694        &mut self,
 9695        excerpt: ExcerptId,
 9696        direction: ExpandExcerptDirection,
 9697        cx: &mut ViewContext<Self>,
 9698    ) {
 9699        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9700        self.buffer.update(cx, |buffer, cx| {
 9701            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9702        })
 9703    }
 9704
 9705    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9706        self.go_to_diagnostic_impl(Direction::Next, cx)
 9707    }
 9708
 9709    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9710        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9711    }
 9712
 9713    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9714        let buffer = self.buffer.read(cx).snapshot(cx);
 9715        let selection = self.selections.newest::<usize>(cx);
 9716
 9717        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9718        if direction == Direction::Next {
 9719            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9720                let (group_id, jump_to) = popover.activation_info();
 9721                if self.activate_diagnostics(group_id, cx) {
 9722                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9723                        let mut new_selection = s.newest_anchor().clone();
 9724                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9725                        s.select_anchors(vec![new_selection.clone()]);
 9726                    });
 9727                }
 9728                return;
 9729            }
 9730        }
 9731
 9732        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9733            active_diagnostics
 9734                .primary_range
 9735                .to_offset(&buffer)
 9736                .to_inclusive()
 9737        });
 9738        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9739            if active_primary_range.contains(&selection.head()) {
 9740                *active_primary_range.start()
 9741            } else {
 9742                selection.head()
 9743            }
 9744        } else {
 9745            selection.head()
 9746        };
 9747        let snapshot = self.snapshot(cx);
 9748        loop {
 9749            let diagnostics = if direction == Direction::Prev {
 9750                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9751            } else {
 9752                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9753            }
 9754            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9755            let group = diagnostics
 9756                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9757                // be sorted in a stable way
 9758                // skip until we are at current active diagnostic, if it exists
 9759                .skip_while(|entry| {
 9760                    (match direction {
 9761                        Direction::Prev => entry.range.start >= search_start,
 9762                        Direction::Next => entry.range.start <= search_start,
 9763                    }) && self
 9764                        .active_diagnostics
 9765                        .as_ref()
 9766                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9767                })
 9768                .find_map(|entry| {
 9769                    if entry.diagnostic.is_primary
 9770                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9771                        && !entry.range.is_empty()
 9772                        // if we match with the active diagnostic, skip it
 9773                        && Some(entry.diagnostic.group_id)
 9774                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9775                    {
 9776                        Some((entry.range, entry.diagnostic.group_id))
 9777                    } else {
 9778                        None
 9779                    }
 9780                });
 9781
 9782            if let Some((primary_range, group_id)) = group {
 9783                if self.activate_diagnostics(group_id, cx) {
 9784                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9785                        s.select(vec![Selection {
 9786                            id: selection.id,
 9787                            start: primary_range.start,
 9788                            end: primary_range.start,
 9789                            reversed: false,
 9790                            goal: SelectionGoal::None,
 9791                        }]);
 9792                    });
 9793                }
 9794                break;
 9795            } else {
 9796                // Cycle around to the start of the buffer, potentially moving back to the start of
 9797                // the currently active diagnostic.
 9798                active_primary_range.take();
 9799                if direction == Direction::Prev {
 9800                    if search_start == buffer.len() {
 9801                        break;
 9802                    } else {
 9803                        search_start = buffer.len();
 9804                    }
 9805                } else if search_start == 0 {
 9806                    break;
 9807                } else {
 9808                    search_start = 0;
 9809                }
 9810            }
 9811        }
 9812    }
 9813
 9814    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9815        let snapshot = self
 9816            .display_map
 9817            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9818        let selection = self.selections.newest::<Point>(cx);
 9819        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9820    }
 9821
 9822    fn go_to_hunk_after_position(
 9823        &mut self,
 9824        snapshot: &DisplaySnapshot,
 9825        position: Point,
 9826        cx: &mut ViewContext<'_, Editor>,
 9827    ) -> Option<MultiBufferDiffHunk> {
 9828        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9829            snapshot,
 9830            position,
 9831            false,
 9832            snapshot
 9833                .buffer_snapshot
 9834                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9835            cx,
 9836        ) {
 9837            return Some(hunk);
 9838        }
 9839
 9840        let wrapped_point = Point::zero();
 9841        self.go_to_next_hunk_in_direction(
 9842            snapshot,
 9843            wrapped_point,
 9844            true,
 9845            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9846                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9847            ),
 9848            cx,
 9849        )
 9850    }
 9851
 9852    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9853        let snapshot = self
 9854            .display_map
 9855            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9856        let selection = self.selections.newest::<Point>(cx);
 9857
 9858        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9859    }
 9860
 9861    fn go_to_hunk_before_position(
 9862        &mut self,
 9863        snapshot: &DisplaySnapshot,
 9864        position: Point,
 9865        cx: &mut ViewContext<'_, Editor>,
 9866    ) -> Option<MultiBufferDiffHunk> {
 9867        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9868            snapshot,
 9869            position,
 9870            false,
 9871            snapshot
 9872                .buffer_snapshot
 9873                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9874            cx,
 9875        ) {
 9876            return Some(hunk);
 9877        }
 9878
 9879        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9880        self.go_to_next_hunk_in_direction(
 9881            snapshot,
 9882            wrapped_point,
 9883            true,
 9884            snapshot
 9885                .buffer_snapshot
 9886                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9887            cx,
 9888        )
 9889    }
 9890
 9891    fn go_to_next_hunk_in_direction(
 9892        &mut self,
 9893        snapshot: &DisplaySnapshot,
 9894        initial_point: Point,
 9895        is_wrapped: bool,
 9896        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9897        cx: &mut ViewContext<Editor>,
 9898    ) -> Option<MultiBufferDiffHunk> {
 9899        let display_point = initial_point.to_display_point(snapshot);
 9900        let mut hunks = hunks
 9901            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9902            .filter(|(display_hunk, _)| {
 9903                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9904            })
 9905            .dedup();
 9906
 9907        if let Some((display_hunk, hunk)) = hunks.next() {
 9908            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9909                let row = display_hunk.start_display_row();
 9910                let point = DisplayPoint::new(row, 0);
 9911                s.select_display_ranges([point..point]);
 9912            });
 9913
 9914            Some(hunk)
 9915        } else {
 9916            None
 9917        }
 9918    }
 9919
 9920    pub fn go_to_definition(
 9921        &mut self,
 9922        _: &GoToDefinition,
 9923        cx: &mut ViewContext<Self>,
 9924    ) -> Task<Result<Navigated>> {
 9925        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9926        cx.spawn(|editor, mut cx| async move {
 9927            if definition.await? == Navigated::Yes {
 9928                return Ok(Navigated::Yes);
 9929            }
 9930            match editor.update(&mut cx, |editor, cx| {
 9931                editor.find_all_references(&FindAllReferences, cx)
 9932            })? {
 9933                Some(references) => references.await,
 9934                None => Ok(Navigated::No),
 9935            }
 9936        })
 9937    }
 9938
 9939    pub fn go_to_declaration(
 9940        &mut self,
 9941        _: &GoToDeclaration,
 9942        cx: &mut ViewContext<Self>,
 9943    ) -> Task<Result<Navigated>> {
 9944        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9945    }
 9946
 9947    pub fn go_to_declaration_split(
 9948        &mut self,
 9949        _: &GoToDeclaration,
 9950        cx: &mut ViewContext<Self>,
 9951    ) -> Task<Result<Navigated>> {
 9952        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9953    }
 9954
 9955    pub fn go_to_implementation(
 9956        &mut self,
 9957        _: &GoToImplementation,
 9958        cx: &mut ViewContext<Self>,
 9959    ) -> Task<Result<Navigated>> {
 9960        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9961    }
 9962
 9963    pub fn go_to_implementation_split(
 9964        &mut self,
 9965        _: &GoToImplementationSplit,
 9966        cx: &mut ViewContext<Self>,
 9967    ) -> Task<Result<Navigated>> {
 9968        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9969    }
 9970
 9971    pub fn go_to_type_definition(
 9972        &mut self,
 9973        _: &GoToTypeDefinition,
 9974        cx: &mut ViewContext<Self>,
 9975    ) -> Task<Result<Navigated>> {
 9976        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9977    }
 9978
 9979    pub fn go_to_definition_split(
 9980        &mut self,
 9981        _: &GoToDefinitionSplit,
 9982        cx: &mut ViewContext<Self>,
 9983    ) -> Task<Result<Navigated>> {
 9984        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9985    }
 9986
 9987    pub fn go_to_type_definition_split(
 9988        &mut self,
 9989        _: &GoToTypeDefinitionSplit,
 9990        cx: &mut ViewContext<Self>,
 9991    ) -> Task<Result<Navigated>> {
 9992        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9993    }
 9994
 9995    fn go_to_definition_of_kind(
 9996        &mut self,
 9997        kind: GotoDefinitionKind,
 9998        split: bool,
 9999        cx: &mut ViewContext<Self>,
10000    ) -> Task<Result<Navigated>> {
10001        let Some(provider) = self.semantics_provider.clone() else {
10002            return Task::ready(Ok(Navigated::No));
10003        };
10004        let head = self.selections.newest::<usize>(cx).head();
10005        let buffer = self.buffer.read(cx);
10006        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10007            text_anchor
10008        } else {
10009            return Task::ready(Ok(Navigated::No));
10010        };
10011
10012        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10013            return Task::ready(Ok(Navigated::No));
10014        };
10015
10016        cx.spawn(|editor, mut cx| async move {
10017            let definitions = definitions.await?;
10018            let navigated = editor
10019                .update(&mut cx, |editor, cx| {
10020                    editor.navigate_to_hover_links(
10021                        Some(kind),
10022                        definitions
10023                            .into_iter()
10024                            .filter(|location| {
10025                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10026                            })
10027                            .map(HoverLink::Text)
10028                            .collect::<Vec<_>>(),
10029                        split,
10030                        cx,
10031                    )
10032                })?
10033                .await?;
10034            anyhow::Ok(navigated)
10035        })
10036    }
10037
10038    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
10039        let position = self.selections.newest_anchor().head();
10040        let Some((buffer, buffer_position)) =
10041            self.buffer.read(cx).text_anchor_for_position(position, cx)
10042        else {
10043            return;
10044        };
10045
10046        cx.spawn(|editor, mut cx| async move {
10047            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10048                editor.update(&mut cx, |_, cx| {
10049                    cx.open_url(&url);
10050                })
10051            } else {
10052                Ok(())
10053            }
10054        })
10055        .detach();
10056    }
10057
10058    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10059        let Some(workspace) = self.workspace() else {
10060            return;
10061        };
10062
10063        let position = self.selections.newest_anchor().head();
10064
10065        let Some((buffer, buffer_position)) =
10066            self.buffer.read(cx).text_anchor_for_position(position, cx)
10067        else {
10068            return;
10069        };
10070
10071        let project = self.project.clone();
10072
10073        cx.spawn(|_, mut cx| async move {
10074            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10075
10076            if let Some((_, path)) = result {
10077                workspace
10078                    .update(&mut cx, |workspace, cx| {
10079                        workspace.open_resolved_path(path, cx)
10080                    })?
10081                    .await?;
10082            }
10083            anyhow::Ok(())
10084        })
10085        .detach();
10086    }
10087
10088    pub(crate) fn navigate_to_hover_links(
10089        &mut self,
10090        kind: Option<GotoDefinitionKind>,
10091        mut definitions: Vec<HoverLink>,
10092        split: bool,
10093        cx: &mut ViewContext<Editor>,
10094    ) -> Task<Result<Navigated>> {
10095        // If there is one definition, just open it directly
10096        if definitions.len() == 1 {
10097            let definition = definitions.pop().unwrap();
10098
10099            enum TargetTaskResult {
10100                Location(Option<Location>),
10101                AlreadyNavigated,
10102            }
10103
10104            let target_task = match definition {
10105                HoverLink::Text(link) => {
10106                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10107                }
10108                HoverLink::InlayHint(lsp_location, server_id) => {
10109                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10110                    cx.background_executor().spawn(async move {
10111                        let location = computation.await?;
10112                        Ok(TargetTaskResult::Location(location))
10113                    })
10114                }
10115                HoverLink::Url(url) => {
10116                    cx.open_url(&url);
10117                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10118                }
10119                HoverLink::File(path) => {
10120                    if let Some(workspace) = self.workspace() {
10121                        cx.spawn(|_, mut cx| async move {
10122                            workspace
10123                                .update(&mut cx, |workspace, cx| {
10124                                    workspace.open_resolved_path(path, cx)
10125                                })?
10126                                .await
10127                                .map(|_| TargetTaskResult::AlreadyNavigated)
10128                        })
10129                    } else {
10130                        Task::ready(Ok(TargetTaskResult::Location(None)))
10131                    }
10132                }
10133            };
10134            cx.spawn(|editor, mut cx| async move {
10135                let target = match target_task.await.context("target resolution task")? {
10136                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10137                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10138                    TargetTaskResult::Location(Some(target)) => target,
10139                };
10140
10141                editor.update(&mut cx, |editor, cx| {
10142                    let Some(workspace) = editor.workspace() else {
10143                        return Navigated::No;
10144                    };
10145                    let pane = workspace.read(cx).active_pane().clone();
10146
10147                    let range = target.range.to_offset(target.buffer.read(cx));
10148                    let range = editor.range_for_match(&range);
10149
10150                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10151                        let buffer = target.buffer.read(cx);
10152                        let range = check_multiline_range(buffer, range);
10153                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10154                            s.select_ranges([range]);
10155                        });
10156                    } else {
10157                        cx.window_context().defer(move |cx| {
10158                            let target_editor: View<Self> =
10159                                workspace.update(cx, |workspace, cx| {
10160                                    let pane = if split {
10161                                        workspace.adjacent_pane(cx)
10162                                    } else {
10163                                        workspace.active_pane().clone()
10164                                    };
10165
10166                                    workspace.open_project_item(
10167                                        pane,
10168                                        target.buffer.clone(),
10169                                        true,
10170                                        true,
10171                                        cx,
10172                                    )
10173                                });
10174                            target_editor.update(cx, |target_editor, cx| {
10175                                // When selecting a definition in a different buffer, disable the nav history
10176                                // to avoid creating a history entry at the previous cursor location.
10177                                pane.update(cx, |pane, _| pane.disable_history());
10178                                let buffer = target.buffer.read(cx);
10179                                let range = check_multiline_range(buffer, range);
10180                                target_editor.change_selections(
10181                                    Some(Autoscroll::focused()),
10182                                    cx,
10183                                    |s| {
10184                                        s.select_ranges([range]);
10185                                    },
10186                                );
10187                                pane.update(cx, |pane, _| pane.enable_history());
10188                            });
10189                        });
10190                    }
10191                    Navigated::Yes
10192                })
10193            })
10194        } else if !definitions.is_empty() {
10195            cx.spawn(|editor, mut cx| async move {
10196                let (title, location_tasks, workspace) = editor
10197                    .update(&mut cx, |editor, cx| {
10198                        let tab_kind = match kind {
10199                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10200                            _ => "Definitions",
10201                        };
10202                        let title = definitions
10203                            .iter()
10204                            .find_map(|definition| match definition {
10205                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10206                                    let buffer = origin.buffer.read(cx);
10207                                    format!(
10208                                        "{} for {}",
10209                                        tab_kind,
10210                                        buffer
10211                                            .text_for_range(origin.range.clone())
10212                                            .collect::<String>()
10213                                    )
10214                                }),
10215                                HoverLink::InlayHint(_, _) => None,
10216                                HoverLink::Url(_) => None,
10217                                HoverLink::File(_) => None,
10218                            })
10219                            .unwrap_or(tab_kind.to_string());
10220                        let location_tasks = definitions
10221                            .into_iter()
10222                            .map(|definition| match definition {
10223                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10224                                HoverLink::InlayHint(lsp_location, server_id) => {
10225                                    editor.compute_target_location(lsp_location, server_id, cx)
10226                                }
10227                                HoverLink::Url(_) => Task::ready(Ok(None)),
10228                                HoverLink::File(_) => Task::ready(Ok(None)),
10229                            })
10230                            .collect::<Vec<_>>();
10231                        (title, location_tasks, editor.workspace().clone())
10232                    })
10233                    .context("location tasks preparation")?;
10234
10235                let locations = future::join_all(location_tasks)
10236                    .await
10237                    .into_iter()
10238                    .filter_map(|location| location.transpose())
10239                    .collect::<Result<_>>()
10240                    .context("location tasks")?;
10241
10242                let Some(workspace) = workspace else {
10243                    return Ok(Navigated::No);
10244                };
10245                let opened = workspace
10246                    .update(&mut cx, |workspace, cx| {
10247                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10248                    })
10249                    .ok();
10250
10251                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10252            })
10253        } else {
10254            Task::ready(Ok(Navigated::No))
10255        }
10256    }
10257
10258    fn compute_target_location(
10259        &self,
10260        lsp_location: lsp::Location,
10261        server_id: LanguageServerId,
10262        cx: &mut ViewContext<Self>,
10263    ) -> Task<anyhow::Result<Option<Location>>> {
10264        let Some(project) = self.project.clone() else {
10265            return Task::Ready(Some(Ok(None)));
10266        };
10267
10268        cx.spawn(move |editor, mut cx| async move {
10269            let location_task = editor.update(&mut cx, |_, cx| {
10270                project.update(cx, |project, cx| {
10271                    let language_server_name = project
10272                        .language_server_statuses(cx)
10273                        .find(|(id, _)| server_id == *id)
10274                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10275                    language_server_name.map(|language_server_name| {
10276                        project.open_local_buffer_via_lsp(
10277                            lsp_location.uri.clone(),
10278                            server_id,
10279                            language_server_name,
10280                            cx,
10281                        )
10282                    })
10283                })
10284            })?;
10285            let location = match location_task {
10286                Some(task) => Some({
10287                    let target_buffer_handle = task.await.context("open local buffer")?;
10288                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10289                        let target_start = target_buffer
10290                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10291                        let target_end = target_buffer
10292                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10293                        target_buffer.anchor_after(target_start)
10294                            ..target_buffer.anchor_before(target_end)
10295                    })?;
10296                    Location {
10297                        buffer: target_buffer_handle,
10298                        range,
10299                    }
10300                }),
10301                None => None,
10302            };
10303            Ok(location)
10304        })
10305    }
10306
10307    pub fn find_all_references(
10308        &mut self,
10309        _: &FindAllReferences,
10310        cx: &mut ViewContext<Self>,
10311    ) -> Option<Task<Result<Navigated>>> {
10312        let selection = self.selections.newest::<usize>(cx);
10313        let multi_buffer = self.buffer.read(cx);
10314        let head = selection.head();
10315
10316        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10317        let head_anchor = multi_buffer_snapshot.anchor_at(
10318            head,
10319            if head < selection.tail() {
10320                Bias::Right
10321            } else {
10322                Bias::Left
10323            },
10324        );
10325
10326        match self
10327            .find_all_references_task_sources
10328            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10329        {
10330            Ok(_) => {
10331                log::info!(
10332                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10333                );
10334                return None;
10335            }
10336            Err(i) => {
10337                self.find_all_references_task_sources.insert(i, head_anchor);
10338            }
10339        }
10340
10341        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10342        let workspace = self.workspace()?;
10343        let project = workspace.read(cx).project().clone();
10344        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10345        Some(cx.spawn(|editor, mut cx| async move {
10346            let _cleanup = defer({
10347                let mut cx = cx.clone();
10348                move || {
10349                    let _ = editor.update(&mut cx, |editor, _| {
10350                        if let Ok(i) =
10351                            editor
10352                                .find_all_references_task_sources
10353                                .binary_search_by(|anchor| {
10354                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10355                                })
10356                        {
10357                            editor.find_all_references_task_sources.remove(i);
10358                        }
10359                    });
10360                }
10361            });
10362
10363            let locations = references.await?;
10364            if locations.is_empty() {
10365                return anyhow::Ok(Navigated::No);
10366            }
10367
10368            workspace.update(&mut cx, |workspace, cx| {
10369                let title = locations
10370                    .first()
10371                    .as_ref()
10372                    .map(|location| {
10373                        let buffer = location.buffer.read(cx);
10374                        format!(
10375                            "References to `{}`",
10376                            buffer
10377                                .text_for_range(location.range.clone())
10378                                .collect::<String>()
10379                        )
10380                    })
10381                    .unwrap();
10382                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10383                Navigated::Yes
10384            })
10385        }))
10386    }
10387
10388    /// Opens a multibuffer with the given project locations in it
10389    pub fn open_locations_in_multibuffer(
10390        workspace: &mut Workspace,
10391        mut locations: Vec<Location>,
10392        title: String,
10393        split: bool,
10394        cx: &mut ViewContext<Workspace>,
10395    ) {
10396        // If there are multiple definitions, open them in a multibuffer
10397        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10398        let mut locations = locations.into_iter().peekable();
10399        let mut ranges_to_highlight = Vec::new();
10400        let capability = workspace.project().read(cx).capability();
10401
10402        let excerpt_buffer = cx.new_model(|cx| {
10403            let mut multibuffer = MultiBuffer::new(capability);
10404            while let Some(location) = locations.next() {
10405                let buffer = location.buffer.read(cx);
10406                let mut ranges_for_buffer = Vec::new();
10407                let range = location.range.to_offset(buffer);
10408                ranges_for_buffer.push(range.clone());
10409
10410                while let Some(next_location) = locations.peek() {
10411                    if next_location.buffer == location.buffer {
10412                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10413                        locations.next();
10414                    } else {
10415                        break;
10416                    }
10417                }
10418
10419                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10420                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10421                    location.buffer.clone(),
10422                    ranges_for_buffer,
10423                    DEFAULT_MULTIBUFFER_CONTEXT,
10424                    cx,
10425                ))
10426            }
10427
10428            multibuffer.with_title(title)
10429        });
10430
10431        let editor = cx.new_view(|cx| {
10432            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10433        });
10434        editor.update(cx, |editor, cx| {
10435            if let Some(first_range) = ranges_to_highlight.first() {
10436                editor.change_selections(None, cx, |selections| {
10437                    selections.clear_disjoint();
10438                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10439                });
10440            }
10441            editor.highlight_background::<Self>(
10442                &ranges_to_highlight,
10443                |theme| theme.editor_highlighted_line_background,
10444                cx,
10445            );
10446        });
10447
10448        let item = Box::new(editor);
10449        let item_id = item.item_id();
10450
10451        if split {
10452            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10453        } else {
10454            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10455                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10456                    pane.close_current_preview_item(cx)
10457                } else {
10458                    None
10459                }
10460            });
10461            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10462        }
10463        workspace.active_pane().update(cx, |pane, cx| {
10464            pane.set_preview_item_id(Some(item_id), cx);
10465        });
10466    }
10467
10468    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10469        use language::ToOffset as _;
10470
10471        let provider = self.semantics_provider.clone()?;
10472        let selection = self.selections.newest_anchor().clone();
10473        let (cursor_buffer, cursor_buffer_position) = self
10474            .buffer
10475            .read(cx)
10476            .text_anchor_for_position(selection.head(), cx)?;
10477        let (tail_buffer, cursor_buffer_position_end) = self
10478            .buffer
10479            .read(cx)
10480            .text_anchor_for_position(selection.tail(), cx)?;
10481        if tail_buffer != cursor_buffer {
10482            return None;
10483        }
10484
10485        let snapshot = cursor_buffer.read(cx).snapshot();
10486        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10487        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10488        let prepare_rename = provider
10489            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10490            .unwrap_or_else(|| Task::ready(Ok(None)));
10491        drop(snapshot);
10492
10493        Some(cx.spawn(|this, mut cx| async move {
10494            let rename_range = if let Some(range) = prepare_rename.await? {
10495                Some(range)
10496            } else {
10497                this.update(&mut cx, |this, cx| {
10498                    let buffer = this.buffer.read(cx).snapshot(cx);
10499                    let mut buffer_highlights = this
10500                        .document_highlights_for_position(selection.head(), &buffer)
10501                        .filter(|highlight| {
10502                            highlight.start.excerpt_id == selection.head().excerpt_id
10503                                && highlight.end.excerpt_id == selection.head().excerpt_id
10504                        });
10505                    buffer_highlights
10506                        .next()
10507                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10508                })?
10509            };
10510            if let Some(rename_range) = rename_range {
10511                this.update(&mut cx, |this, cx| {
10512                    let snapshot = cursor_buffer.read(cx).snapshot();
10513                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10514                    let cursor_offset_in_rename_range =
10515                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10516                    let cursor_offset_in_rename_range_end =
10517                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10518
10519                    this.take_rename(false, cx);
10520                    let buffer = this.buffer.read(cx).read(cx);
10521                    let cursor_offset = selection.head().to_offset(&buffer);
10522                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10523                    let rename_end = rename_start + rename_buffer_range.len();
10524                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10525                    let mut old_highlight_id = None;
10526                    let old_name: Arc<str> = buffer
10527                        .chunks(rename_start..rename_end, true)
10528                        .map(|chunk| {
10529                            if old_highlight_id.is_none() {
10530                                old_highlight_id = chunk.syntax_highlight_id;
10531                            }
10532                            chunk.text
10533                        })
10534                        .collect::<String>()
10535                        .into();
10536
10537                    drop(buffer);
10538
10539                    // Position the selection in the rename editor so that it matches the current selection.
10540                    this.show_local_selections = false;
10541                    let rename_editor = cx.new_view(|cx| {
10542                        let mut editor = Editor::single_line(cx);
10543                        editor.buffer.update(cx, |buffer, cx| {
10544                            buffer.edit([(0..0, old_name.clone())], None, cx)
10545                        });
10546                        let rename_selection_range = match cursor_offset_in_rename_range
10547                            .cmp(&cursor_offset_in_rename_range_end)
10548                        {
10549                            Ordering::Equal => {
10550                                editor.select_all(&SelectAll, cx);
10551                                return editor;
10552                            }
10553                            Ordering::Less => {
10554                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10555                            }
10556                            Ordering::Greater => {
10557                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10558                            }
10559                        };
10560                        if rename_selection_range.end > old_name.len() {
10561                            editor.select_all(&SelectAll, cx);
10562                        } else {
10563                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10564                                s.select_ranges([rename_selection_range]);
10565                            });
10566                        }
10567                        editor
10568                    });
10569                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10570                        if e == &EditorEvent::Focused {
10571                            cx.emit(EditorEvent::FocusedIn)
10572                        }
10573                    })
10574                    .detach();
10575
10576                    let write_highlights =
10577                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10578                    let read_highlights =
10579                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10580                    let ranges = write_highlights
10581                        .iter()
10582                        .flat_map(|(_, ranges)| ranges.iter())
10583                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10584                        .cloned()
10585                        .collect();
10586
10587                    this.highlight_text::<Rename>(
10588                        ranges,
10589                        HighlightStyle {
10590                            fade_out: Some(0.6),
10591                            ..Default::default()
10592                        },
10593                        cx,
10594                    );
10595                    let rename_focus_handle = rename_editor.focus_handle(cx);
10596                    cx.focus(&rename_focus_handle);
10597                    let block_id = this.insert_blocks(
10598                        [BlockProperties {
10599                            style: BlockStyle::Flex,
10600                            placement: BlockPlacement::Below(range.start),
10601                            height: 1,
10602                            render: Arc::new({
10603                                let rename_editor = rename_editor.clone();
10604                                move |cx: &mut BlockContext| {
10605                                    let mut text_style = cx.editor_style.text.clone();
10606                                    if let Some(highlight_style) = old_highlight_id
10607                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10608                                    {
10609                                        text_style = text_style.highlight(highlight_style);
10610                                    }
10611                                    div()
10612                                        .block_mouse_down()
10613                                        .pl(cx.anchor_x)
10614                                        .child(EditorElement::new(
10615                                            &rename_editor,
10616                                            EditorStyle {
10617                                                background: cx.theme().system().transparent,
10618                                                local_player: cx.editor_style.local_player,
10619                                                text: text_style,
10620                                                scrollbar_width: cx.editor_style.scrollbar_width,
10621                                                syntax: cx.editor_style.syntax.clone(),
10622                                                status: cx.editor_style.status.clone(),
10623                                                inlay_hints_style: HighlightStyle {
10624                                                    font_weight: Some(FontWeight::BOLD),
10625                                                    ..make_inlay_hints_style(cx)
10626                                                },
10627                                                suggestions_style: HighlightStyle {
10628                                                    color: Some(cx.theme().status().predictive),
10629                                                    ..HighlightStyle::default()
10630                                                },
10631                                                ..EditorStyle::default()
10632                                            },
10633                                        ))
10634                                        .into_any_element()
10635                                }
10636                            }),
10637                            priority: 0,
10638                        }],
10639                        Some(Autoscroll::fit()),
10640                        cx,
10641                    )[0];
10642                    this.pending_rename = Some(RenameState {
10643                        range,
10644                        old_name,
10645                        editor: rename_editor,
10646                        block_id,
10647                    });
10648                })?;
10649            }
10650
10651            Ok(())
10652        }))
10653    }
10654
10655    pub fn confirm_rename(
10656        &mut self,
10657        _: &ConfirmRename,
10658        cx: &mut ViewContext<Self>,
10659    ) -> Option<Task<Result<()>>> {
10660        let rename = self.take_rename(false, cx)?;
10661        let workspace = self.workspace()?.downgrade();
10662        let (buffer, start) = self
10663            .buffer
10664            .read(cx)
10665            .text_anchor_for_position(rename.range.start, cx)?;
10666        let (end_buffer, _) = self
10667            .buffer
10668            .read(cx)
10669            .text_anchor_for_position(rename.range.end, cx)?;
10670        if buffer != end_buffer {
10671            return None;
10672        }
10673
10674        let old_name = rename.old_name;
10675        let new_name = rename.editor.read(cx).text(cx);
10676
10677        let rename = self.semantics_provider.as_ref()?.perform_rename(
10678            &buffer,
10679            start,
10680            new_name.clone(),
10681            cx,
10682        )?;
10683
10684        Some(cx.spawn(|editor, mut cx| async move {
10685            let project_transaction = rename.await?;
10686            Self::open_project_transaction(
10687                &editor,
10688                workspace,
10689                project_transaction,
10690                format!("Rename: {}{}", old_name, new_name),
10691                cx.clone(),
10692            )
10693            .await?;
10694
10695            editor.update(&mut cx, |editor, cx| {
10696                editor.refresh_document_highlights(cx);
10697            })?;
10698            Ok(())
10699        }))
10700    }
10701
10702    fn take_rename(
10703        &mut self,
10704        moving_cursor: bool,
10705        cx: &mut ViewContext<Self>,
10706    ) -> Option<RenameState> {
10707        let rename = self.pending_rename.take()?;
10708        if rename.editor.focus_handle(cx).is_focused(cx) {
10709            cx.focus(&self.focus_handle);
10710        }
10711
10712        self.remove_blocks(
10713            [rename.block_id].into_iter().collect(),
10714            Some(Autoscroll::fit()),
10715            cx,
10716        );
10717        self.clear_highlights::<Rename>(cx);
10718        self.show_local_selections = true;
10719
10720        if moving_cursor {
10721            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10722                editor.selections.newest::<usize>(cx).head()
10723            });
10724
10725            // Update the selection to match the position of the selection inside
10726            // the rename editor.
10727            let snapshot = self.buffer.read(cx).read(cx);
10728            let rename_range = rename.range.to_offset(&snapshot);
10729            let cursor_in_editor = snapshot
10730                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10731                .min(rename_range.end);
10732            drop(snapshot);
10733
10734            self.change_selections(None, cx, |s| {
10735                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10736            });
10737        } else {
10738            self.refresh_document_highlights(cx);
10739        }
10740
10741        Some(rename)
10742    }
10743
10744    pub fn pending_rename(&self) -> Option<&RenameState> {
10745        self.pending_rename.as_ref()
10746    }
10747
10748    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10749        let project = match &self.project {
10750            Some(project) => project.clone(),
10751            None => return None,
10752        };
10753
10754        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10755    }
10756
10757    fn format_selections(
10758        &mut self,
10759        _: &FormatSelections,
10760        cx: &mut ViewContext<Self>,
10761    ) -> Option<Task<Result<()>>> {
10762        let project = match &self.project {
10763            Some(project) => project.clone(),
10764            None => return None,
10765        };
10766
10767        let selections = self
10768            .selections
10769            .all_adjusted(cx)
10770            .into_iter()
10771            .filter(|s| !s.is_empty())
10772            .collect_vec();
10773
10774        Some(self.perform_format(
10775            project,
10776            FormatTrigger::Manual,
10777            FormatTarget::Ranges(selections),
10778            cx,
10779        ))
10780    }
10781
10782    fn perform_format(
10783        &mut self,
10784        project: Model<Project>,
10785        trigger: FormatTrigger,
10786        target: FormatTarget,
10787        cx: &mut ViewContext<Self>,
10788    ) -> Task<Result<()>> {
10789        let buffer = self.buffer().clone();
10790        let mut buffers = buffer.read(cx).all_buffers();
10791        if trigger == FormatTrigger::Save {
10792            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10793        }
10794
10795        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10796        let format = project.update(cx, |project, cx| {
10797            project.format(buffers, true, trigger, target, cx)
10798        });
10799
10800        cx.spawn(|_, mut cx| async move {
10801            let transaction = futures::select_biased! {
10802                () = timeout => {
10803                    log::warn!("timed out waiting for formatting");
10804                    None
10805                }
10806                transaction = format.log_err().fuse() => transaction,
10807            };
10808
10809            buffer
10810                .update(&mut cx, |buffer, cx| {
10811                    if let Some(transaction) = transaction {
10812                        if !buffer.is_singleton() {
10813                            buffer.push_transaction(&transaction.0, cx);
10814                        }
10815                    }
10816
10817                    cx.notify();
10818                })
10819                .ok();
10820
10821            Ok(())
10822        })
10823    }
10824
10825    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10826        if let Some(project) = self.project.clone() {
10827            self.buffer.update(cx, |multi_buffer, cx| {
10828                project.update(cx, |project, cx| {
10829                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10830                });
10831            })
10832        }
10833    }
10834
10835    fn cancel_language_server_work(
10836        &mut self,
10837        _: &actions::CancelLanguageServerWork,
10838        cx: &mut ViewContext<Self>,
10839    ) {
10840        if let Some(project) = self.project.clone() {
10841            self.buffer.update(cx, |multi_buffer, cx| {
10842                project.update(cx, |project, cx| {
10843                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10844                });
10845            })
10846        }
10847    }
10848
10849    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10850        cx.show_character_palette();
10851    }
10852
10853    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10854        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10855            let buffer = self.buffer.read(cx).snapshot(cx);
10856            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10857            let is_valid = buffer
10858                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10859                .any(|entry| {
10860                    entry.diagnostic.is_primary
10861                        && !entry.range.is_empty()
10862                        && entry.range.start == primary_range_start
10863                        && entry.diagnostic.message == active_diagnostics.primary_message
10864                });
10865
10866            if is_valid != active_diagnostics.is_valid {
10867                active_diagnostics.is_valid = is_valid;
10868                let mut new_styles = HashMap::default();
10869                for (block_id, diagnostic) in &active_diagnostics.blocks {
10870                    new_styles.insert(
10871                        *block_id,
10872                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10873                    );
10874                }
10875                self.display_map.update(cx, |display_map, _cx| {
10876                    display_map.replace_blocks(new_styles)
10877                });
10878            }
10879        }
10880    }
10881
10882    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10883        self.dismiss_diagnostics(cx);
10884        let snapshot = self.snapshot(cx);
10885        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10886            let buffer = self.buffer.read(cx).snapshot(cx);
10887
10888            let mut primary_range = None;
10889            let mut primary_message = None;
10890            let mut group_end = Point::zero();
10891            let diagnostic_group = buffer
10892                .diagnostic_group::<MultiBufferPoint>(group_id)
10893                .filter_map(|entry| {
10894                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10895                        && (entry.range.start.row == entry.range.end.row
10896                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10897                    {
10898                        return None;
10899                    }
10900                    if entry.range.end > group_end {
10901                        group_end = entry.range.end;
10902                    }
10903                    if entry.diagnostic.is_primary {
10904                        primary_range = Some(entry.range.clone());
10905                        primary_message = Some(entry.diagnostic.message.clone());
10906                    }
10907                    Some(entry)
10908                })
10909                .collect::<Vec<_>>();
10910            let primary_range = primary_range?;
10911            let primary_message = primary_message?;
10912            let primary_range =
10913                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10914
10915            let blocks = display_map
10916                .insert_blocks(
10917                    diagnostic_group.iter().map(|entry| {
10918                        let diagnostic = entry.diagnostic.clone();
10919                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10920                        BlockProperties {
10921                            style: BlockStyle::Fixed,
10922                            placement: BlockPlacement::Below(
10923                                buffer.anchor_after(entry.range.start),
10924                            ),
10925                            height: message_height,
10926                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10927                            priority: 0,
10928                        }
10929                    }),
10930                    cx,
10931                )
10932                .into_iter()
10933                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10934                .collect();
10935
10936            Some(ActiveDiagnosticGroup {
10937                primary_range,
10938                primary_message,
10939                group_id,
10940                blocks,
10941                is_valid: true,
10942            })
10943        });
10944        self.active_diagnostics.is_some()
10945    }
10946
10947    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10948        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10949            self.display_map.update(cx, |display_map, cx| {
10950                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10951            });
10952            cx.notify();
10953        }
10954    }
10955
10956    pub fn set_selections_from_remote(
10957        &mut self,
10958        selections: Vec<Selection<Anchor>>,
10959        pending_selection: Option<Selection<Anchor>>,
10960        cx: &mut ViewContext<Self>,
10961    ) {
10962        let old_cursor_position = self.selections.newest_anchor().head();
10963        self.selections.change_with(cx, |s| {
10964            s.select_anchors(selections);
10965            if let Some(pending_selection) = pending_selection {
10966                s.set_pending(pending_selection, SelectMode::Character);
10967            } else {
10968                s.clear_pending();
10969            }
10970        });
10971        self.selections_did_change(false, &old_cursor_position, true, cx);
10972    }
10973
10974    fn push_to_selection_history(&mut self) {
10975        self.selection_history.push(SelectionHistoryEntry {
10976            selections: self.selections.disjoint_anchors(),
10977            select_next_state: self.select_next_state.clone(),
10978            select_prev_state: self.select_prev_state.clone(),
10979            add_selections_state: self.add_selections_state.clone(),
10980        });
10981    }
10982
10983    pub fn transact(
10984        &mut self,
10985        cx: &mut ViewContext<Self>,
10986        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10987    ) -> Option<TransactionId> {
10988        self.start_transaction_at(Instant::now(), cx);
10989        update(self, cx);
10990        self.end_transaction_at(Instant::now(), cx)
10991    }
10992
10993    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10994        self.end_selection(cx);
10995        if let Some(tx_id) = self
10996            .buffer
10997            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10998        {
10999            self.selection_history
11000                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11001            cx.emit(EditorEvent::TransactionBegun {
11002                transaction_id: tx_id,
11003            })
11004        }
11005    }
11006
11007    fn end_transaction_at(
11008        &mut self,
11009        now: Instant,
11010        cx: &mut ViewContext<Self>,
11011    ) -> Option<TransactionId> {
11012        if let Some(transaction_id) = self
11013            .buffer
11014            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11015        {
11016            if let Some((_, end_selections)) =
11017                self.selection_history.transaction_mut(transaction_id)
11018            {
11019                *end_selections = Some(self.selections.disjoint_anchors());
11020            } else {
11021                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11022            }
11023
11024            cx.emit(EditorEvent::Edited { transaction_id });
11025            Some(transaction_id)
11026        } else {
11027            None
11028        }
11029    }
11030
11031    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
11032        let selection = self.selections.newest::<Point>(cx);
11033
11034        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11035        let range = if selection.is_empty() {
11036            let point = selection.head().to_display_point(&display_map);
11037            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11038            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11039                .to_point(&display_map);
11040            start..end
11041        } else {
11042            selection.range()
11043        };
11044        if display_map.folds_in_range(range).next().is_some() {
11045            self.unfold_lines(&Default::default(), cx)
11046        } else {
11047            self.fold(&Default::default(), cx)
11048        }
11049    }
11050
11051    pub fn toggle_fold_recursive(
11052        &mut self,
11053        _: &actions::ToggleFoldRecursive,
11054        cx: &mut ViewContext<Self>,
11055    ) {
11056        let selection = self.selections.newest::<Point>(cx);
11057
11058        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11059        let range = if selection.is_empty() {
11060            let point = selection.head().to_display_point(&display_map);
11061            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11062            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11063                .to_point(&display_map);
11064            start..end
11065        } else {
11066            selection.range()
11067        };
11068        if display_map.folds_in_range(range).next().is_some() {
11069            self.unfold_recursive(&Default::default(), cx)
11070        } else {
11071            self.fold_recursive(&Default::default(), cx)
11072        }
11073    }
11074
11075    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11076        let mut to_fold = Vec::new();
11077        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11078        let selections = self.selections.all_adjusted(cx);
11079
11080        for selection in selections {
11081            let range = selection.range().sorted();
11082            let buffer_start_row = range.start.row;
11083
11084            if range.start.row != range.end.row {
11085                let mut found = false;
11086                let mut row = range.start.row;
11087                while row <= range.end.row {
11088                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11089                        found = true;
11090                        row = crease.range().end.row + 1;
11091                        to_fold.push(crease);
11092                    } else {
11093                        row += 1
11094                    }
11095                }
11096                if found {
11097                    continue;
11098                }
11099            }
11100
11101            for row in (0..=range.start.row).rev() {
11102                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11103                    if crease.range().end.row >= buffer_start_row {
11104                        to_fold.push(crease);
11105                        if row <= range.start.row {
11106                            break;
11107                        }
11108                    }
11109                }
11110            }
11111        }
11112
11113        self.fold_creases(to_fold, true, cx);
11114    }
11115
11116    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11117        let fold_at_level = fold_at.level;
11118        let snapshot = self.buffer.read(cx).snapshot(cx);
11119        let mut to_fold = Vec::new();
11120        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11121
11122        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11123            while start_row < end_row {
11124                match self
11125                    .snapshot(cx)
11126                    .crease_for_buffer_row(MultiBufferRow(start_row))
11127                {
11128                    Some(crease) => {
11129                        let nested_start_row = crease.range().start.row + 1;
11130                        let nested_end_row = crease.range().end.row;
11131
11132                        if current_level < fold_at_level {
11133                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11134                        } else if current_level == fold_at_level {
11135                            to_fold.push(crease);
11136                        }
11137
11138                        start_row = nested_end_row + 1;
11139                    }
11140                    None => start_row += 1,
11141                }
11142            }
11143        }
11144
11145        self.fold_creases(to_fold, true, cx);
11146    }
11147
11148    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11149        let mut fold_ranges = Vec::new();
11150        let snapshot = self.buffer.read(cx).snapshot(cx);
11151
11152        for row in 0..snapshot.max_buffer_row().0 {
11153            if let Some(foldable_range) =
11154                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11155            {
11156                fold_ranges.push(foldable_range);
11157            }
11158        }
11159
11160        self.fold_creases(fold_ranges, true, cx);
11161    }
11162
11163    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11164        let mut to_fold = Vec::new();
11165        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11166        let selections = self.selections.all_adjusted(cx);
11167
11168        for selection in selections {
11169            let range = selection.range().sorted();
11170            let buffer_start_row = range.start.row;
11171
11172            if range.start.row != range.end.row {
11173                let mut found = false;
11174                for row in range.start.row..=range.end.row {
11175                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11176                        found = true;
11177                        to_fold.push(crease);
11178                    }
11179                }
11180                if found {
11181                    continue;
11182                }
11183            }
11184
11185            for row in (0..=range.start.row).rev() {
11186                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11187                    if crease.range().end.row >= buffer_start_row {
11188                        to_fold.push(crease);
11189                    } else {
11190                        break;
11191                    }
11192                }
11193            }
11194        }
11195
11196        self.fold_creases(to_fold, true, cx);
11197    }
11198
11199    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11200        let buffer_row = fold_at.buffer_row;
11201        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11202
11203        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11204            let autoscroll = self
11205                .selections
11206                .all::<Point>(cx)
11207                .iter()
11208                .any(|selection| crease.range().overlaps(&selection.range()));
11209
11210            self.fold_creases(vec![crease], autoscroll, cx);
11211        }
11212    }
11213
11214    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11215        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11216        let buffer = &display_map.buffer_snapshot;
11217        let selections = self.selections.all::<Point>(cx);
11218        let ranges = selections
11219            .iter()
11220            .map(|s| {
11221                let range = s.display_range(&display_map).sorted();
11222                let mut start = range.start.to_point(&display_map);
11223                let mut end = range.end.to_point(&display_map);
11224                start.column = 0;
11225                end.column = buffer.line_len(MultiBufferRow(end.row));
11226                start..end
11227            })
11228            .collect::<Vec<_>>();
11229
11230        self.unfold_ranges(&ranges, true, true, cx);
11231    }
11232
11233    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11234        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11235        let selections = self.selections.all::<Point>(cx);
11236        let ranges = selections
11237            .iter()
11238            .map(|s| {
11239                let mut range = s.display_range(&display_map).sorted();
11240                *range.start.column_mut() = 0;
11241                *range.end.column_mut() = display_map.line_len(range.end.row());
11242                let start = range.start.to_point(&display_map);
11243                let end = range.end.to_point(&display_map);
11244                start..end
11245            })
11246            .collect::<Vec<_>>();
11247
11248        self.unfold_ranges(&ranges, true, true, cx);
11249    }
11250
11251    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11252        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11253
11254        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11255            ..Point::new(
11256                unfold_at.buffer_row.0,
11257                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11258            );
11259
11260        let autoscroll = self
11261            .selections
11262            .all::<Point>(cx)
11263            .iter()
11264            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11265
11266        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11267    }
11268
11269    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11270        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11271        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11272    }
11273
11274    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11275        let selections = self.selections.all::<Point>(cx);
11276        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11277        let line_mode = self.selections.line_mode;
11278        let ranges = selections
11279            .into_iter()
11280            .map(|s| {
11281                if line_mode {
11282                    let start = Point::new(s.start.row, 0);
11283                    let end = Point::new(
11284                        s.end.row,
11285                        display_map
11286                            .buffer_snapshot
11287                            .line_len(MultiBufferRow(s.end.row)),
11288                    );
11289                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11290                } else {
11291                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11292                }
11293            })
11294            .collect::<Vec<_>>();
11295        self.fold_creases(ranges, true, cx);
11296    }
11297
11298    pub fn fold_creases<T: ToOffset + Clone>(
11299        &mut self,
11300        creases: Vec<Crease<T>>,
11301        auto_scroll: bool,
11302        cx: &mut ViewContext<Self>,
11303    ) {
11304        if creases.is_empty() {
11305            return;
11306        }
11307
11308        let mut buffers_affected = HashMap::default();
11309        let multi_buffer = self.buffer().read(cx);
11310        for crease in &creases {
11311            if let Some((_, buffer, _)) =
11312                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11313            {
11314                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11315            };
11316        }
11317
11318        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11319
11320        if auto_scroll {
11321            self.request_autoscroll(Autoscroll::fit(), cx);
11322        }
11323
11324        for buffer in buffers_affected.into_values() {
11325            self.sync_expanded_diff_hunks(buffer, cx);
11326        }
11327
11328        cx.notify();
11329
11330        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11331            // Clear diagnostics block when folding a range that contains it.
11332            let snapshot = self.snapshot(cx);
11333            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11334                drop(snapshot);
11335                self.active_diagnostics = Some(active_diagnostics);
11336                self.dismiss_diagnostics(cx);
11337            } else {
11338                self.active_diagnostics = Some(active_diagnostics);
11339            }
11340        }
11341
11342        self.scrollbar_marker_state.dirty = true;
11343    }
11344
11345    /// Removes any folds whose ranges intersect any of the given ranges.
11346    pub fn unfold_ranges<T: ToOffset + Clone>(
11347        &mut self,
11348        ranges: &[Range<T>],
11349        inclusive: bool,
11350        auto_scroll: bool,
11351        cx: &mut ViewContext<Self>,
11352    ) {
11353        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11354            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11355        });
11356    }
11357
11358    /// Removes any folds with the given ranges.
11359    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11360        &mut self,
11361        ranges: &[Range<T>],
11362        type_id: TypeId,
11363        auto_scroll: bool,
11364        cx: &mut ViewContext<Self>,
11365    ) {
11366        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11367            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11368        });
11369    }
11370
11371    fn remove_folds_with<T: ToOffset + Clone>(
11372        &mut self,
11373        ranges: &[Range<T>],
11374        auto_scroll: bool,
11375        cx: &mut ViewContext<Self>,
11376        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11377    ) {
11378        if ranges.is_empty() {
11379            return;
11380        }
11381
11382        let mut buffers_affected = HashMap::default();
11383        let multi_buffer = self.buffer().read(cx);
11384        for range in ranges {
11385            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11386                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11387            };
11388        }
11389
11390        self.display_map.update(cx, update);
11391
11392        if auto_scroll {
11393            self.request_autoscroll(Autoscroll::fit(), cx);
11394        }
11395
11396        for buffer in buffers_affected.into_values() {
11397            self.sync_expanded_diff_hunks(buffer, cx);
11398        }
11399
11400        cx.notify();
11401        self.scrollbar_marker_state.dirty = true;
11402        self.active_indent_guides_state.dirty = true;
11403    }
11404
11405    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11406        self.display_map.read(cx).fold_placeholder.clone()
11407    }
11408
11409    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11410        if hovered != self.gutter_hovered {
11411            self.gutter_hovered = hovered;
11412            cx.notify();
11413        }
11414    }
11415
11416    pub fn insert_blocks(
11417        &mut self,
11418        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11419        autoscroll: Option<Autoscroll>,
11420        cx: &mut ViewContext<Self>,
11421    ) -> Vec<CustomBlockId> {
11422        let blocks = self
11423            .display_map
11424            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11425        if let Some(autoscroll) = autoscroll {
11426            self.request_autoscroll(autoscroll, cx);
11427        }
11428        cx.notify();
11429        blocks
11430    }
11431
11432    pub fn resize_blocks(
11433        &mut self,
11434        heights: HashMap<CustomBlockId, u32>,
11435        autoscroll: Option<Autoscroll>,
11436        cx: &mut ViewContext<Self>,
11437    ) {
11438        self.display_map
11439            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11440        if let Some(autoscroll) = autoscroll {
11441            self.request_autoscroll(autoscroll, cx);
11442        }
11443        cx.notify();
11444    }
11445
11446    pub fn replace_blocks(
11447        &mut self,
11448        renderers: HashMap<CustomBlockId, RenderBlock>,
11449        autoscroll: Option<Autoscroll>,
11450        cx: &mut ViewContext<Self>,
11451    ) {
11452        self.display_map
11453            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11454        if let Some(autoscroll) = autoscroll {
11455            self.request_autoscroll(autoscroll, cx);
11456        }
11457        cx.notify();
11458    }
11459
11460    pub fn remove_blocks(
11461        &mut self,
11462        block_ids: HashSet<CustomBlockId>,
11463        autoscroll: Option<Autoscroll>,
11464        cx: &mut ViewContext<Self>,
11465    ) {
11466        self.display_map.update(cx, |display_map, cx| {
11467            display_map.remove_blocks(block_ids, cx)
11468        });
11469        if let Some(autoscroll) = autoscroll {
11470            self.request_autoscroll(autoscroll, cx);
11471        }
11472        cx.notify();
11473    }
11474
11475    pub fn row_for_block(
11476        &self,
11477        block_id: CustomBlockId,
11478        cx: &mut ViewContext<Self>,
11479    ) -> Option<DisplayRow> {
11480        self.display_map
11481            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11482    }
11483
11484    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11485        self.focused_block = Some(focused_block);
11486    }
11487
11488    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11489        self.focused_block.take()
11490    }
11491
11492    pub fn insert_creases(
11493        &mut self,
11494        creases: impl IntoIterator<Item = Crease<Anchor>>,
11495        cx: &mut ViewContext<Self>,
11496    ) -> Vec<CreaseId> {
11497        self.display_map
11498            .update(cx, |map, cx| map.insert_creases(creases, cx))
11499    }
11500
11501    pub fn remove_creases(
11502        &mut self,
11503        ids: impl IntoIterator<Item = CreaseId>,
11504        cx: &mut ViewContext<Self>,
11505    ) {
11506        self.display_map
11507            .update(cx, |map, cx| map.remove_creases(ids, cx));
11508    }
11509
11510    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11511        self.display_map
11512            .update(cx, |map, cx| map.snapshot(cx))
11513            .longest_row()
11514    }
11515
11516    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11517        self.display_map
11518            .update(cx, |map, cx| map.snapshot(cx))
11519            .max_point()
11520    }
11521
11522    pub fn text(&self, cx: &AppContext) -> String {
11523        self.buffer.read(cx).read(cx).text()
11524    }
11525
11526    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11527        let text = self.text(cx);
11528        let text = text.trim();
11529
11530        if text.is_empty() {
11531            return None;
11532        }
11533
11534        Some(text.to_string())
11535    }
11536
11537    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11538        self.transact(cx, |this, cx| {
11539            this.buffer
11540                .read(cx)
11541                .as_singleton()
11542                .expect("you can only call set_text on editors for singleton buffers")
11543                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11544        });
11545    }
11546
11547    pub fn display_text(&self, cx: &mut AppContext) -> String {
11548        self.display_map
11549            .update(cx, |map, cx| map.snapshot(cx))
11550            .text()
11551    }
11552
11553    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11554        let mut wrap_guides = smallvec::smallvec![];
11555
11556        if self.show_wrap_guides == Some(false) {
11557            return wrap_guides;
11558        }
11559
11560        let settings = self.buffer.read(cx).settings_at(0, cx);
11561        if settings.show_wrap_guides {
11562            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11563                wrap_guides.push((soft_wrap as usize, true));
11564            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11565                wrap_guides.push((soft_wrap as usize, true));
11566            }
11567            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11568        }
11569
11570        wrap_guides
11571    }
11572
11573    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11574        let settings = self.buffer.read(cx).settings_at(0, cx);
11575        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11576        match mode {
11577            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11578                SoftWrap::None
11579            }
11580            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11581            language_settings::SoftWrap::PreferredLineLength => {
11582                SoftWrap::Column(settings.preferred_line_length)
11583            }
11584            language_settings::SoftWrap::Bounded => {
11585                SoftWrap::Bounded(settings.preferred_line_length)
11586            }
11587        }
11588    }
11589
11590    pub fn set_soft_wrap_mode(
11591        &mut self,
11592        mode: language_settings::SoftWrap,
11593        cx: &mut ViewContext<Self>,
11594    ) {
11595        self.soft_wrap_mode_override = Some(mode);
11596        cx.notify();
11597    }
11598
11599    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11600        self.text_style_refinement = Some(style);
11601    }
11602
11603    /// called by the Element so we know what style we were most recently rendered with.
11604    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11605        let rem_size = cx.rem_size();
11606        self.display_map.update(cx, |map, cx| {
11607            map.set_font(
11608                style.text.font(),
11609                style.text.font_size.to_pixels(rem_size),
11610                cx,
11611            )
11612        });
11613        self.style = Some(style);
11614    }
11615
11616    pub fn style(&self) -> Option<&EditorStyle> {
11617        self.style.as_ref()
11618    }
11619
11620    // Called by the element. This method is not designed to be called outside of the editor
11621    // element's layout code because it does not notify when rewrapping is computed synchronously.
11622    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11623        self.display_map
11624            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11625    }
11626
11627    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11628        if self.soft_wrap_mode_override.is_some() {
11629            self.soft_wrap_mode_override.take();
11630        } else {
11631            let soft_wrap = match self.soft_wrap_mode(cx) {
11632                SoftWrap::GitDiff => return,
11633                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11634                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11635                    language_settings::SoftWrap::None
11636                }
11637            };
11638            self.soft_wrap_mode_override = Some(soft_wrap);
11639        }
11640        cx.notify();
11641    }
11642
11643    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11644        let Some(workspace) = self.workspace() else {
11645            return;
11646        };
11647        let fs = workspace.read(cx).app_state().fs.clone();
11648        let current_show = TabBarSettings::get_global(cx).show;
11649        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11650            setting.show = Some(!current_show);
11651        });
11652    }
11653
11654    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11655        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11656            self.buffer
11657                .read(cx)
11658                .settings_at(0, cx)
11659                .indent_guides
11660                .enabled
11661        });
11662        self.show_indent_guides = Some(!currently_enabled);
11663        cx.notify();
11664    }
11665
11666    fn should_show_indent_guides(&self) -> Option<bool> {
11667        self.show_indent_guides
11668    }
11669
11670    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11671        let mut editor_settings = EditorSettings::get_global(cx).clone();
11672        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11673        EditorSettings::override_global(editor_settings, cx);
11674    }
11675
11676    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11677        self.use_relative_line_numbers
11678            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11679    }
11680
11681    pub fn toggle_relative_line_numbers(
11682        &mut self,
11683        _: &ToggleRelativeLineNumbers,
11684        cx: &mut ViewContext<Self>,
11685    ) {
11686        let is_relative = self.should_use_relative_line_numbers(cx);
11687        self.set_relative_line_number(Some(!is_relative), cx)
11688    }
11689
11690    pub fn set_relative_line_number(
11691        &mut self,
11692        is_relative: Option<bool>,
11693        cx: &mut ViewContext<Self>,
11694    ) {
11695        self.use_relative_line_numbers = is_relative;
11696        cx.notify();
11697    }
11698
11699    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11700        self.show_gutter = show_gutter;
11701        cx.notify();
11702    }
11703
11704    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11705        self.show_line_numbers = Some(show_line_numbers);
11706        cx.notify();
11707    }
11708
11709    pub fn set_show_git_diff_gutter(
11710        &mut self,
11711        show_git_diff_gutter: bool,
11712        cx: &mut ViewContext<Self>,
11713    ) {
11714        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11715        cx.notify();
11716    }
11717
11718    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11719        self.show_code_actions = Some(show_code_actions);
11720        cx.notify();
11721    }
11722
11723    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11724        self.show_runnables = Some(show_runnables);
11725        cx.notify();
11726    }
11727
11728    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11729        if self.display_map.read(cx).masked != masked {
11730            self.display_map.update(cx, |map, _| map.masked = masked);
11731        }
11732        cx.notify()
11733    }
11734
11735    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11736        self.show_wrap_guides = Some(show_wrap_guides);
11737        cx.notify();
11738    }
11739
11740    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11741        self.show_indent_guides = Some(show_indent_guides);
11742        cx.notify();
11743    }
11744
11745    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11746        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11747            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11748                if let Some(dir) = file.abs_path(cx).parent() {
11749                    return Some(dir.to_owned());
11750                }
11751            }
11752
11753            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11754                return Some(project_path.path.to_path_buf());
11755            }
11756        }
11757
11758        None
11759    }
11760
11761    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11762        self.active_excerpt(cx)?
11763            .1
11764            .read(cx)
11765            .file()
11766            .and_then(|f| f.as_local())
11767    }
11768
11769    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11770        if let Some(target) = self.target_file(cx) {
11771            cx.reveal_path(&target.abs_path(cx));
11772        }
11773    }
11774
11775    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11776        if let Some(file) = self.target_file(cx) {
11777            if let Some(path) = file.abs_path(cx).to_str() {
11778                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11779            }
11780        }
11781    }
11782
11783    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11784        if let Some(file) = self.target_file(cx) {
11785            if let Some(path) = file.path().to_str() {
11786                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11787            }
11788        }
11789    }
11790
11791    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11792        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11793
11794        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11795            self.start_git_blame(true, cx);
11796        }
11797
11798        cx.notify();
11799    }
11800
11801    pub fn toggle_git_blame_inline(
11802        &mut self,
11803        _: &ToggleGitBlameInline,
11804        cx: &mut ViewContext<Self>,
11805    ) {
11806        self.toggle_git_blame_inline_internal(true, cx);
11807        cx.notify();
11808    }
11809
11810    pub fn git_blame_inline_enabled(&self) -> bool {
11811        self.git_blame_inline_enabled
11812    }
11813
11814    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11815        self.show_selection_menu = self
11816            .show_selection_menu
11817            .map(|show_selections_menu| !show_selections_menu)
11818            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11819
11820        cx.notify();
11821    }
11822
11823    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11824        self.show_selection_menu
11825            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11826    }
11827
11828    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11829        if let Some(project) = self.project.as_ref() {
11830            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11831                return;
11832            };
11833
11834            if buffer.read(cx).file().is_none() {
11835                return;
11836            }
11837
11838            let focused = self.focus_handle(cx).contains_focused(cx);
11839
11840            let project = project.clone();
11841            let blame =
11842                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11843            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11844            self.blame = Some(blame);
11845        }
11846    }
11847
11848    fn toggle_git_blame_inline_internal(
11849        &mut self,
11850        user_triggered: bool,
11851        cx: &mut ViewContext<Self>,
11852    ) {
11853        if self.git_blame_inline_enabled {
11854            self.git_blame_inline_enabled = false;
11855            self.show_git_blame_inline = false;
11856            self.show_git_blame_inline_delay_task.take();
11857        } else {
11858            self.git_blame_inline_enabled = true;
11859            self.start_git_blame_inline(user_triggered, cx);
11860        }
11861
11862        cx.notify();
11863    }
11864
11865    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11866        self.start_git_blame(user_triggered, cx);
11867
11868        if ProjectSettings::get_global(cx)
11869            .git
11870            .inline_blame_delay()
11871            .is_some()
11872        {
11873            self.start_inline_blame_timer(cx);
11874        } else {
11875            self.show_git_blame_inline = true
11876        }
11877    }
11878
11879    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11880        self.blame.as_ref()
11881    }
11882
11883    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11884        self.show_git_blame_gutter && self.has_blame_entries(cx)
11885    }
11886
11887    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11888        self.show_git_blame_inline
11889            && self.focus_handle.is_focused(cx)
11890            && !self.newest_selection_head_on_empty_line(cx)
11891            && self.has_blame_entries(cx)
11892    }
11893
11894    pub fn render_active_line_trailer(
11895        &mut self,
11896        style: &EditorStyle,
11897        cx: &mut WindowContext,
11898    ) -> Option<AnyElement> {
11899        let selection = self.selections.newest::<Point>(cx);
11900        if !selection.is_empty() {
11901            return None;
11902        };
11903
11904        let snapshot = self.buffer.read(cx).snapshot(cx);
11905        let buffer_row = MultiBufferRow(selection.head().row);
11906
11907        if snapshot.line_len(buffer_row) != 0 || self.has_active_inline_completion(cx) {
11908            return None;
11909        }
11910
11911        let focus_handle = self.focus_handle.clone();
11912        self.active_line_trailer_provider
11913            .as_mut()?
11914            .render_active_line_trailer(style, &focus_handle, cx)
11915    }
11916
11917    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11918        self.blame()
11919            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11920    }
11921
11922    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11923        let cursor_anchor = self.selections.newest_anchor().head();
11924
11925        let snapshot = self.buffer.read(cx).snapshot(cx);
11926        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11927
11928        snapshot.line_len(buffer_row) == 0
11929    }
11930
11931    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11932        let buffer_and_selection = maybe!({
11933            let selection = self.selections.newest::<Point>(cx);
11934            let selection_range = selection.range();
11935
11936            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11937                (buffer, selection_range.start.row..selection_range.end.row)
11938            } else {
11939                let buffer_ranges = self
11940                    .buffer()
11941                    .read(cx)
11942                    .range_to_buffer_ranges(selection_range, cx);
11943
11944                let (buffer, range, _) = if selection.reversed {
11945                    buffer_ranges.first()
11946                } else {
11947                    buffer_ranges.last()
11948                }?;
11949
11950                let snapshot = buffer.read(cx).snapshot();
11951                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11952                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11953                (buffer.clone(), selection)
11954            };
11955
11956            Some((buffer, selection))
11957        });
11958
11959        let Some((buffer, selection)) = buffer_and_selection else {
11960            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11961        };
11962
11963        let Some(project) = self.project.as_ref() else {
11964            return Task::ready(Err(anyhow!("editor does not have project")));
11965        };
11966
11967        project.update(cx, |project, cx| {
11968            project.get_permalink_to_line(&buffer, selection, cx)
11969        })
11970    }
11971
11972    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11973        let permalink_task = self.get_permalink_to_line(cx);
11974        let workspace = self.workspace();
11975
11976        cx.spawn(|_, mut cx| async move {
11977            match permalink_task.await {
11978                Ok(permalink) => {
11979                    cx.update(|cx| {
11980                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11981                    })
11982                    .ok();
11983                }
11984                Err(err) => {
11985                    let message = format!("Failed to copy permalink: {err}");
11986
11987                    Err::<(), anyhow::Error>(err).log_err();
11988
11989                    if let Some(workspace) = workspace {
11990                        workspace
11991                            .update(&mut cx, |workspace, cx| {
11992                                struct CopyPermalinkToLine;
11993
11994                                workspace.show_toast(
11995                                    Toast::new(
11996                                        NotificationId::unique::<CopyPermalinkToLine>(),
11997                                        message,
11998                                    ),
11999                                    cx,
12000                                )
12001                            })
12002                            .ok();
12003                    }
12004                }
12005            }
12006        })
12007        .detach();
12008    }
12009
12010    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
12011        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12012        if let Some(file) = self.target_file(cx) {
12013            if let Some(path) = file.path().to_str() {
12014                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12015            }
12016        }
12017    }
12018
12019    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
12020        let permalink_task = self.get_permalink_to_line(cx);
12021        let workspace = self.workspace();
12022
12023        cx.spawn(|_, mut cx| async move {
12024            match permalink_task.await {
12025                Ok(permalink) => {
12026                    cx.update(|cx| {
12027                        cx.open_url(permalink.as_ref());
12028                    })
12029                    .ok();
12030                }
12031                Err(err) => {
12032                    let message = format!("Failed to open permalink: {err}");
12033
12034                    Err::<(), anyhow::Error>(err).log_err();
12035
12036                    if let Some(workspace) = workspace {
12037                        workspace
12038                            .update(&mut cx, |workspace, cx| {
12039                                struct OpenPermalinkToLine;
12040
12041                                workspace.show_toast(
12042                                    Toast::new(
12043                                        NotificationId::unique::<OpenPermalinkToLine>(),
12044                                        message,
12045                                    ),
12046                                    cx,
12047                                )
12048                            })
12049                            .ok();
12050                    }
12051                }
12052            }
12053        })
12054        .detach();
12055    }
12056
12057    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12058    /// last highlight added will be used.
12059    ///
12060    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12061    pub fn highlight_rows<T: 'static>(
12062        &mut self,
12063        range: Range<Anchor>,
12064        color: Hsla,
12065        should_autoscroll: bool,
12066        cx: &mut ViewContext<Self>,
12067    ) {
12068        let snapshot = self.buffer().read(cx).snapshot(cx);
12069        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12070        let ix = row_highlights.binary_search_by(|highlight| {
12071            Ordering::Equal
12072                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12073                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12074        });
12075
12076        if let Err(mut ix) = ix {
12077            let index = post_inc(&mut self.highlight_order);
12078
12079            // If this range intersects with the preceding highlight, then merge it with
12080            // the preceding highlight. Otherwise insert a new highlight.
12081            let mut merged = false;
12082            if ix > 0 {
12083                let prev_highlight = &mut row_highlights[ix - 1];
12084                if prev_highlight
12085                    .range
12086                    .end
12087                    .cmp(&range.start, &snapshot)
12088                    .is_ge()
12089                {
12090                    ix -= 1;
12091                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12092                        prev_highlight.range.end = range.end;
12093                    }
12094                    merged = true;
12095                    prev_highlight.index = index;
12096                    prev_highlight.color = color;
12097                    prev_highlight.should_autoscroll = should_autoscroll;
12098                }
12099            }
12100
12101            if !merged {
12102                row_highlights.insert(
12103                    ix,
12104                    RowHighlight {
12105                        range: range.clone(),
12106                        index,
12107                        color,
12108                        should_autoscroll,
12109                    },
12110                );
12111            }
12112
12113            // If any of the following highlights intersect with this one, merge them.
12114            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12115                let highlight = &row_highlights[ix];
12116                if next_highlight
12117                    .range
12118                    .start
12119                    .cmp(&highlight.range.end, &snapshot)
12120                    .is_le()
12121                {
12122                    if next_highlight
12123                        .range
12124                        .end
12125                        .cmp(&highlight.range.end, &snapshot)
12126                        .is_gt()
12127                    {
12128                        row_highlights[ix].range.end = next_highlight.range.end;
12129                    }
12130                    row_highlights.remove(ix + 1);
12131                } else {
12132                    break;
12133                }
12134            }
12135        }
12136    }
12137
12138    /// Remove any highlighted row ranges of the given type that intersect the
12139    /// given ranges.
12140    pub fn remove_highlighted_rows<T: 'static>(
12141        &mut self,
12142        ranges_to_remove: Vec<Range<Anchor>>,
12143        cx: &mut ViewContext<Self>,
12144    ) {
12145        let snapshot = self.buffer().read(cx).snapshot(cx);
12146        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12147        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12148        row_highlights.retain(|highlight| {
12149            while let Some(range_to_remove) = ranges_to_remove.peek() {
12150                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12151                    Ordering::Less | Ordering::Equal => {
12152                        ranges_to_remove.next();
12153                    }
12154                    Ordering::Greater => {
12155                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12156                            Ordering::Less | Ordering::Equal => {
12157                                return false;
12158                            }
12159                            Ordering::Greater => break,
12160                        }
12161                    }
12162                }
12163            }
12164
12165            true
12166        })
12167    }
12168
12169    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12170    pub fn clear_row_highlights<T: 'static>(&mut self) {
12171        self.highlighted_rows.remove(&TypeId::of::<T>());
12172    }
12173
12174    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12175    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12176        self.highlighted_rows
12177            .get(&TypeId::of::<T>())
12178            .map_or(&[] as &[_], |vec| vec.as_slice())
12179            .iter()
12180            .map(|highlight| (highlight.range.clone(), highlight.color))
12181    }
12182
12183    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12184    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12185    /// Allows to ignore certain kinds of highlights.
12186    pub fn highlighted_display_rows(
12187        &mut self,
12188        cx: &mut WindowContext,
12189    ) -> BTreeMap<DisplayRow, Hsla> {
12190        let snapshot = self.snapshot(cx);
12191        let mut used_highlight_orders = HashMap::default();
12192        self.highlighted_rows
12193            .iter()
12194            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12195            .fold(
12196                BTreeMap::<DisplayRow, Hsla>::new(),
12197                |mut unique_rows, highlight| {
12198                    let start = highlight.range.start.to_display_point(&snapshot);
12199                    let end = highlight.range.end.to_display_point(&snapshot);
12200                    let start_row = start.row().0;
12201                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12202                        && end.column() == 0
12203                    {
12204                        end.row().0.saturating_sub(1)
12205                    } else {
12206                        end.row().0
12207                    };
12208                    for row in start_row..=end_row {
12209                        let used_index =
12210                            used_highlight_orders.entry(row).or_insert(highlight.index);
12211                        if highlight.index >= *used_index {
12212                            *used_index = highlight.index;
12213                            unique_rows.insert(DisplayRow(row), highlight.color);
12214                        }
12215                    }
12216                    unique_rows
12217                },
12218            )
12219    }
12220
12221    pub fn highlighted_display_row_for_autoscroll(
12222        &self,
12223        snapshot: &DisplaySnapshot,
12224    ) -> Option<DisplayRow> {
12225        self.highlighted_rows
12226            .values()
12227            .flat_map(|highlighted_rows| highlighted_rows.iter())
12228            .filter_map(|highlight| {
12229                if highlight.should_autoscroll {
12230                    Some(highlight.range.start.to_display_point(snapshot).row())
12231                } else {
12232                    None
12233                }
12234            })
12235            .min()
12236    }
12237
12238    pub fn set_search_within_ranges(
12239        &mut self,
12240        ranges: &[Range<Anchor>],
12241        cx: &mut ViewContext<Self>,
12242    ) {
12243        self.highlight_background::<SearchWithinRange>(
12244            ranges,
12245            |colors| colors.editor_document_highlight_read_background,
12246            cx,
12247        )
12248    }
12249
12250    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12251        self.breadcrumb_header = Some(new_header);
12252    }
12253
12254    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12255        self.clear_background_highlights::<SearchWithinRange>(cx);
12256    }
12257
12258    pub fn highlight_background<T: 'static>(
12259        &mut self,
12260        ranges: &[Range<Anchor>],
12261        color_fetcher: fn(&ThemeColors) -> Hsla,
12262        cx: &mut ViewContext<Self>,
12263    ) {
12264        self.background_highlights
12265            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12266        self.scrollbar_marker_state.dirty = true;
12267        cx.notify();
12268    }
12269
12270    pub fn clear_background_highlights<T: 'static>(
12271        &mut self,
12272        cx: &mut ViewContext<Self>,
12273    ) -> Option<BackgroundHighlight> {
12274        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12275        if !text_highlights.1.is_empty() {
12276            self.scrollbar_marker_state.dirty = true;
12277            cx.notify();
12278        }
12279        Some(text_highlights)
12280    }
12281
12282    pub fn highlight_gutter<T: 'static>(
12283        &mut self,
12284        ranges: &[Range<Anchor>],
12285        color_fetcher: fn(&AppContext) -> Hsla,
12286        cx: &mut ViewContext<Self>,
12287    ) {
12288        self.gutter_highlights
12289            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12290        cx.notify();
12291    }
12292
12293    pub fn clear_gutter_highlights<T: 'static>(
12294        &mut self,
12295        cx: &mut ViewContext<Self>,
12296    ) -> Option<GutterHighlight> {
12297        cx.notify();
12298        self.gutter_highlights.remove(&TypeId::of::<T>())
12299    }
12300
12301    #[cfg(feature = "test-support")]
12302    pub fn all_text_background_highlights(
12303        &mut self,
12304        cx: &mut ViewContext<Self>,
12305    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12306        let snapshot = self.snapshot(cx);
12307        let buffer = &snapshot.buffer_snapshot;
12308        let start = buffer.anchor_before(0);
12309        let end = buffer.anchor_after(buffer.len());
12310        let theme = cx.theme().colors();
12311        self.background_highlights_in_range(start..end, &snapshot, theme)
12312    }
12313
12314    #[cfg(feature = "test-support")]
12315    pub fn search_background_highlights(
12316        &mut self,
12317        cx: &mut ViewContext<Self>,
12318    ) -> Vec<Range<Point>> {
12319        let snapshot = self.buffer().read(cx).snapshot(cx);
12320
12321        let highlights = self
12322            .background_highlights
12323            .get(&TypeId::of::<items::BufferSearchHighlights>());
12324
12325        if let Some((_color, ranges)) = highlights {
12326            ranges
12327                .iter()
12328                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12329                .collect_vec()
12330        } else {
12331            vec![]
12332        }
12333    }
12334
12335    fn document_highlights_for_position<'a>(
12336        &'a self,
12337        position: Anchor,
12338        buffer: &'a MultiBufferSnapshot,
12339    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12340        let read_highlights = self
12341            .background_highlights
12342            .get(&TypeId::of::<DocumentHighlightRead>())
12343            .map(|h| &h.1);
12344        let write_highlights = self
12345            .background_highlights
12346            .get(&TypeId::of::<DocumentHighlightWrite>())
12347            .map(|h| &h.1);
12348        let left_position = position.bias_left(buffer);
12349        let right_position = position.bias_right(buffer);
12350        read_highlights
12351            .into_iter()
12352            .chain(write_highlights)
12353            .flat_map(move |ranges| {
12354                let start_ix = match ranges.binary_search_by(|probe| {
12355                    let cmp = probe.end.cmp(&left_position, buffer);
12356                    if cmp.is_ge() {
12357                        Ordering::Greater
12358                    } else {
12359                        Ordering::Less
12360                    }
12361                }) {
12362                    Ok(i) | Err(i) => i,
12363                };
12364
12365                ranges[start_ix..]
12366                    .iter()
12367                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12368            })
12369    }
12370
12371    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12372        self.background_highlights
12373            .get(&TypeId::of::<T>())
12374            .map_or(false, |(_, highlights)| !highlights.is_empty())
12375    }
12376
12377    pub fn background_highlights_in_range(
12378        &self,
12379        search_range: Range<Anchor>,
12380        display_snapshot: &DisplaySnapshot,
12381        theme: &ThemeColors,
12382    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12383        let mut results = Vec::new();
12384        for (color_fetcher, ranges) in self.background_highlights.values() {
12385            let color = color_fetcher(theme);
12386            let start_ix = match ranges.binary_search_by(|probe| {
12387                let cmp = probe
12388                    .end
12389                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12390                if cmp.is_gt() {
12391                    Ordering::Greater
12392                } else {
12393                    Ordering::Less
12394                }
12395            }) {
12396                Ok(i) | Err(i) => i,
12397            };
12398            for range in &ranges[start_ix..] {
12399                if range
12400                    .start
12401                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12402                    .is_ge()
12403                {
12404                    break;
12405                }
12406
12407                let start = range.start.to_display_point(display_snapshot);
12408                let end = range.end.to_display_point(display_snapshot);
12409                results.push((start..end, color))
12410            }
12411        }
12412        results
12413    }
12414
12415    pub fn background_highlight_row_ranges<T: 'static>(
12416        &self,
12417        search_range: Range<Anchor>,
12418        display_snapshot: &DisplaySnapshot,
12419        count: usize,
12420    ) -> Vec<RangeInclusive<DisplayPoint>> {
12421        let mut results = Vec::new();
12422        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12423            return vec![];
12424        };
12425
12426        let start_ix = match ranges.binary_search_by(|probe| {
12427            let cmp = probe
12428                .end
12429                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12430            if cmp.is_gt() {
12431                Ordering::Greater
12432            } else {
12433                Ordering::Less
12434            }
12435        }) {
12436            Ok(i) | Err(i) => i,
12437        };
12438        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12439            if let (Some(start_display), Some(end_display)) = (start, end) {
12440                results.push(
12441                    start_display.to_display_point(display_snapshot)
12442                        ..=end_display.to_display_point(display_snapshot),
12443                );
12444            }
12445        };
12446        let mut start_row: Option<Point> = None;
12447        let mut end_row: Option<Point> = None;
12448        if ranges.len() > count {
12449            return Vec::new();
12450        }
12451        for range in &ranges[start_ix..] {
12452            if range
12453                .start
12454                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12455                .is_ge()
12456            {
12457                break;
12458            }
12459            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12460            if let Some(current_row) = &end_row {
12461                if end.row == current_row.row {
12462                    continue;
12463                }
12464            }
12465            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12466            if start_row.is_none() {
12467                assert_eq!(end_row, None);
12468                start_row = Some(start);
12469                end_row = Some(end);
12470                continue;
12471            }
12472            if let Some(current_end) = end_row.as_mut() {
12473                if start.row > current_end.row + 1 {
12474                    push_region(start_row, end_row);
12475                    start_row = Some(start);
12476                    end_row = Some(end);
12477                } else {
12478                    // Merge two hunks.
12479                    *current_end = end;
12480                }
12481            } else {
12482                unreachable!();
12483            }
12484        }
12485        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12486        push_region(start_row, end_row);
12487        results
12488    }
12489
12490    pub fn gutter_highlights_in_range(
12491        &self,
12492        search_range: Range<Anchor>,
12493        display_snapshot: &DisplaySnapshot,
12494        cx: &AppContext,
12495    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12496        let mut results = Vec::new();
12497        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12498            let color = color_fetcher(cx);
12499            let start_ix = match ranges.binary_search_by(|probe| {
12500                let cmp = probe
12501                    .end
12502                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12503                if cmp.is_gt() {
12504                    Ordering::Greater
12505                } else {
12506                    Ordering::Less
12507                }
12508            }) {
12509                Ok(i) | Err(i) => i,
12510            };
12511            for range in &ranges[start_ix..] {
12512                if range
12513                    .start
12514                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12515                    .is_ge()
12516                {
12517                    break;
12518                }
12519
12520                let start = range.start.to_display_point(display_snapshot);
12521                let end = range.end.to_display_point(display_snapshot);
12522                results.push((start..end, color))
12523            }
12524        }
12525        results
12526    }
12527
12528    /// Get the text ranges corresponding to the redaction query
12529    pub fn redacted_ranges(
12530        &self,
12531        search_range: Range<Anchor>,
12532        display_snapshot: &DisplaySnapshot,
12533        cx: &WindowContext,
12534    ) -> Vec<Range<DisplayPoint>> {
12535        display_snapshot
12536            .buffer_snapshot
12537            .redacted_ranges(search_range, |file| {
12538                if let Some(file) = file {
12539                    file.is_private()
12540                        && EditorSettings::get(
12541                            Some(SettingsLocation {
12542                                worktree_id: file.worktree_id(cx),
12543                                path: file.path().as_ref(),
12544                            }),
12545                            cx,
12546                        )
12547                        .redact_private_values
12548                } else {
12549                    false
12550                }
12551            })
12552            .map(|range| {
12553                range.start.to_display_point(display_snapshot)
12554                    ..range.end.to_display_point(display_snapshot)
12555            })
12556            .collect()
12557    }
12558
12559    pub fn highlight_text<T: 'static>(
12560        &mut self,
12561        ranges: Vec<Range<Anchor>>,
12562        style: HighlightStyle,
12563        cx: &mut ViewContext<Self>,
12564    ) {
12565        self.display_map.update(cx, |map, _| {
12566            map.highlight_text(TypeId::of::<T>(), ranges, style)
12567        });
12568        cx.notify();
12569    }
12570
12571    pub(crate) fn highlight_inlays<T: 'static>(
12572        &mut self,
12573        highlights: Vec<InlayHighlight>,
12574        style: HighlightStyle,
12575        cx: &mut ViewContext<Self>,
12576    ) {
12577        self.display_map.update(cx, |map, _| {
12578            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12579        });
12580        cx.notify();
12581    }
12582
12583    pub fn text_highlights<'a, T: 'static>(
12584        &'a self,
12585        cx: &'a AppContext,
12586    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12587        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12588    }
12589
12590    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12591        let cleared = self
12592            .display_map
12593            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12594        if cleared {
12595            cx.notify();
12596        }
12597    }
12598
12599    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12600        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12601            && self.focus_handle.is_focused(cx)
12602    }
12603
12604    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12605        self.show_cursor_when_unfocused = is_enabled;
12606        cx.notify();
12607    }
12608
12609    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12610        cx.notify();
12611    }
12612
12613    fn on_buffer_event(
12614        &mut self,
12615        multibuffer: Model<MultiBuffer>,
12616        event: &multi_buffer::Event,
12617        cx: &mut ViewContext<Self>,
12618    ) {
12619        match event {
12620            multi_buffer::Event::Edited {
12621                singleton_buffer_edited,
12622            } => {
12623                self.scrollbar_marker_state.dirty = true;
12624                self.active_indent_guides_state.dirty = true;
12625                self.refresh_active_diagnostics(cx);
12626                self.refresh_code_actions(cx);
12627                if self.has_active_inline_completion(cx) {
12628                    self.update_visible_inline_completion(cx);
12629                }
12630                cx.emit(EditorEvent::BufferEdited);
12631                cx.emit(SearchEvent::MatchesInvalidated);
12632                if *singleton_buffer_edited {
12633                    if let Some(project) = &self.project {
12634                        let project = project.read(cx);
12635                        #[allow(clippy::mutable_key_type)]
12636                        let languages_affected = multibuffer
12637                            .read(cx)
12638                            .all_buffers()
12639                            .into_iter()
12640                            .filter_map(|buffer| {
12641                                let buffer = buffer.read(cx);
12642                                let language = buffer.language()?;
12643                                if project.is_local()
12644                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12645                                {
12646                                    None
12647                                } else {
12648                                    Some(language)
12649                                }
12650                            })
12651                            .cloned()
12652                            .collect::<HashSet<_>>();
12653                        if !languages_affected.is_empty() {
12654                            self.refresh_inlay_hints(
12655                                InlayHintRefreshReason::BufferEdited(languages_affected),
12656                                cx,
12657                            );
12658                        }
12659                    }
12660                }
12661
12662                let Some(project) = &self.project else { return };
12663                let (telemetry, is_via_ssh) = {
12664                    let project = project.read(cx);
12665                    let telemetry = project.client().telemetry().clone();
12666                    let is_via_ssh = project.is_via_ssh();
12667                    (telemetry, is_via_ssh)
12668                };
12669                refresh_linked_ranges(self, cx);
12670                telemetry.log_edit_event("editor", is_via_ssh);
12671            }
12672            multi_buffer::Event::ExcerptsAdded {
12673                buffer,
12674                predecessor,
12675                excerpts,
12676            } => {
12677                self.tasks_update_task = Some(self.refresh_runnables(cx));
12678                cx.emit(EditorEvent::ExcerptsAdded {
12679                    buffer: buffer.clone(),
12680                    predecessor: *predecessor,
12681                    excerpts: excerpts.clone(),
12682                });
12683                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12684            }
12685            multi_buffer::Event::ExcerptsRemoved { ids } => {
12686                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12687                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12688            }
12689            multi_buffer::Event::ExcerptsEdited { ids } => {
12690                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12691            }
12692            multi_buffer::Event::ExcerptsExpanded { ids } => {
12693                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12694            }
12695            multi_buffer::Event::Reparsed(buffer_id) => {
12696                self.tasks_update_task = Some(self.refresh_runnables(cx));
12697
12698                cx.emit(EditorEvent::Reparsed(*buffer_id));
12699            }
12700            multi_buffer::Event::LanguageChanged(buffer_id) => {
12701                linked_editing_ranges::refresh_linked_ranges(self, cx);
12702                cx.emit(EditorEvent::Reparsed(*buffer_id));
12703                cx.notify();
12704            }
12705            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12706            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12707            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12708                cx.emit(EditorEvent::TitleChanged)
12709            }
12710            multi_buffer::Event::DiffBaseChanged => {
12711                self.scrollbar_marker_state.dirty = true;
12712                cx.emit(EditorEvent::DiffBaseChanged);
12713                cx.notify();
12714            }
12715            multi_buffer::Event::DiffUpdated { buffer } => {
12716                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12717                cx.notify();
12718            }
12719            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12720            multi_buffer::Event::DiagnosticsUpdated => {
12721                self.refresh_active_diagnostics(cx);
12722                self.scrollbar_marker_state.dirty = true;
12723                cx.notify();
12724            }
12725            _ => {}
12726        };
12727    }
12728
12729    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12730        cx.notify();
12731    }
12732
12733    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12734        self.tasks_update_task = Some(self.refresh_runnables(cx));
12735        self.refresh_inline_completion(true, false, cx);
12736        self.refresh_inlay_hints(
12737            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12738                self.selections.newest_anchor().head(),
12739                &self.buffer.read(cx).snapshot(cx),
12740                cx,
12741            )),
12742            cx,
12743        );
12744
12745        let old_cursor_shape = self.cursor_shape;
12746
12747        {
12748            let editor_settings = EditorSettings::get_global(cx);
12749            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12750            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12751            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12752        }
12753
12754        if old_cursor_shape != self.cursor_shape {
12755            cx.emit(EditorEvent::CursorShapeChanged);
12756        }
12757
12758        let project_settings = ProjectSettings::get_global(cx);
12759        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12760
12761        if self.mode == EditorMode::Full {
12762            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12763            if self.git_blame_inline_enabled != inline_blame_enabled {
12764                self.toggle_git_blame_inline_internal(false, cx);
12765            }
12766        }
12767
12768        cx.notify();
12769    }
12770
12771    pub fn set_searchable(&mut self, searchable: bool) {
12772        self.searchable = searchable;
12773    }
12774
12775    pub fn searchable(&self) -> bool {
12776        self.searchable
12777    }
12778
12779    fn open_proposed_changes_editor(
12780        &mut self,
12781        _: &OpenProposedChangesEditor,
12782        cx: &mut ViewContext<Self>,
12783    ) {
12784        let Some(workspace) = self.workspace() else {
12785            cx.propagate();
12786            return;
12787        };
12788
12789        let selections = self.selections.all::<usize>(cx);
12790        let buffer = self.buffer.read(cx);
12791        let mut new_selections_by_buffer = HashMap::default();
12792        for selection in selections {
12793            for (buffer, range, _) in
12794                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12795            {
12796                let mut range = range.to_point(buffer.read(cx));
12797                range.start.column = 0;
12798                range.end.column = buffer.read(cx).line_len(range.end.row);
12799                new_selections_by_buffer
12800                    .entry(buffer)
12801                    .or_insert(Vec::new())
12802                    .push(range)
12803            }
12804        }
12805
12806        let proposed_changes_buffers = new_selections_by_buffer
12807            .into_iter()
12808            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12809            .collect::<Vec<_>>();
12810        let proposed_changes_editor = cx.new_view(|cx| {
12811            ProposedChangesEditor::new(
12812                "Proposed changes",
12813                proposed_changes_buffers,
12814                self.project.clone(),
12815                cx,
12816            )
12817        });
12818
12819        cx.window_context().defer(move |cx| {
12820            workspace.update(cx, |workspace, cx| {
12821                workspace.active_pane().update(cx, |pane, cx| {
12822                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12823                });
12824            });
12825        });
12826    }
12827
12828    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12829        self.open_excerpts_common(None, true, cx)
12830    }
12831
12832    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12833        self.open_excerpts_common(None, false, cx)
12834    }
12835
12836    fn open_excerpts_common(
12837        &mut self,
12838        jump_data: Option<JumpData>,
12839        split: bool,
12840        cx: &mut ViewContext<Self>,
12841    ) {
12842        let Some(workspace) = self.workspace() else {
12843            cx.propagate();
12844            return;
12845        };
12846
12847        if self.buffer.read(cx).is_singleton() {
12848            cx.propagate();
12849            return;
12850        }
12851
12852        let mut new_selections_by_buffer = HashMap::default();
12853        match &jump_data {
12854            Some(jump_data) => {
12855                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12856                if let Some(buffer) = multi_buffer_snapshot
12857                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12858                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12859                {
12860                    let buffer_snapshot = buffer.read(cx).snapshot();
12861                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12862                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12863                    } else {
12864                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12865                    };
12866                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12867                    new_selections_by_buffer.insert(
12868                        buffer,
12869                        (
12870                            vec![jump_to_offset..jump_to_offset],
12871                            Some(jump_data.line_offset_from_top),
12872                        ),
12873                    );
12874                }
12875            }
12876            None => {
12877                let selections = self.selections.all::<usize>(cx);
12878                let buffer = self.buffer.read(cx);
12879                for selection in selections {
12880                    for (mut buffer_handle, mut range, _) in
12881                        buffer.range_to_buffer_ranges(selection.range(), cx)
12882                    {
12883                        // When editing branch buffers, jump to the corresponding location
12884                        // in their base buffer.
12885                        let buffer = buffer_handle.read(cx);
12886                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12887                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12888                            buffer_handle = base_buffer;
12889                        }
12890
12891                        if selection.reversed {
12892                            mem::swap(&mut range.start, &mut range.end);
12893                        }
12894                        new_selections_by_buffer
12895                            .entry(buffer_handle)
12896                            .or_insert((Vec::new(), None))
12897                            .0
12898                            .push(range)
12899                    }
12900                }
12901            }
12902        }
12903
12904        if new_selections_by_buffer.is_empty() {
12905            return;
12906        }
12907
12908        // We defer the pane interaction because we ourselves are a workspace item
12909        // and activating a new item causes the pane to call a method on us reentrantly,
12910        // which panics if we're on the stack.
12911        cx.window_context().defer(move |cx| {
12912            workspace.update(cx, |workspace, cx| {
12913                let pane = if split {
12914                    workspace.adjacent_pane(cx)
12915                } else {
12916                    workspace.active_pane().clone()
12917                };
12918
12919                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12920                    let editor =
12921                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12922                    editor.update(cx, |editor, cx| {
12923                        let autoscroll = match scroll_offset {
12924                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12925                            None => Autoscroll::newest(),
12926                        };
12927                        let nav_history = editor.nav_history.take();
12928                        editor.change_selections(Some(autoscroll), cx, |s| {
12929                            s.select_ranges(ranges);
12930                        });
12931                        editor.nav_history = nav_history;
12932                    });
12933                }
12934            })
12935        });
12936    }
12937
12938    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12939        let snapshot = self.buffer.read(cx).read(cx);
12940        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12941        Some(
12942            ranges
12943                .iter()
12944                .map(move |range| {
12945                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12946                })
12947                .collect(),
12948        )
12949    }
12950
12951    fn selection_replacement_ranges(
12952        &self,
12953        range: Range<OffsetUtf16>,
12954        cx: &mut AppContext,
12955    ) -> Vec<Range<OffsetUtf16>> {
12956        let selections = self.selections.all::<OffsetUtf16>(cx);
12957        let newest_selection = selections
12958            .iter()
12959            .max_by_key(|selection| selection.id)
12960            .unwrap();
12961        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12962        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12963        let snapshot = self.buffer.read(cx).read(cx);
12964        selections
12965            .into_iter()
12966            .map(|mut selection| {
12967                selection.start.0 =
12968                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12969                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12970                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12971                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12972            })
12973            .collect()
12974    }
12975
12976    fn report_editor_event(
12977        &self,
12978        operation: &'static str,
12979        file_extension: Option<String>,
12980        cx: &AppContext,
12981    ) {
12982        if cfg!(any(test, feature = "test-support")) {
12983            return;
12984        }
12985
12986        let Some(project) = &self.project else { return };
12987
12988        // If None, we are in a file without an extension
12989        let file = self
12990            .buffer
12991            .read(cx)
12992            .as_singleton()
12993            .and_then(|b| b.read(cx).file());
12994        let file_extension = file_extension.or(file
12995            .as_ref()
12996            .and_then(|file| Path::new(file.file_name(cx)).extension())
12997            .and_then(|e| e.to_str())
12998            .map(|a| a.to_string()));
12999
13000        let vim_mode = cx
13001            .global::<SettingsStore>()
13002            .raw_user_settings()
13003            .get("vim_mode")
13004            == Some(&serde_json::Value::Bool(true));
13005
13006        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13007            == language::language_settings::InlineCompletionProvider::Copilot;
13008        let copilot_enabled_for_language = self
13009            .buffer
13010            .read(cx)
13011            .settings_at(0, cx)
13012            .show_inline_completions;
13013
13014        let project = project.read(cx);
13015        let telemetry = project.client().telemetry().clone();
13016        telemetry.report_editor_event(
13017            file_extension,
13018            vim_mode,
13019            operation,
13020            copilot_enabled,
13021            copilot_enabled_for_language,
13022            project.is_via_ssh(),
13023        )
13024    }
13025
13026    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13027    /// with each line being an array of {text, highlight} objects.
13028    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13029        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13030            return;
13031        };
13032
13033        #[derive(Serialize)]
13034        struct Chunk<'a> {
13035            text: String,
13036            highlight: Option<&'a str>,
13037        }
13038
13039        let snapshot = buffer.read(cx).snapshot();
13040        let range = self
13041            .selected_text_range(false, cx)
13042            .and_then(|selection| {
13043                if selection.range.is_empty() {
13044                    None
13045                } else {
13046                    Some(selection.range)
13047                }
13048            })
13049            .unwrap_or_else(|| 0..snapshot.len());
13050
13051        let chunks = snapshot.chunks(range, true);
13052        let mut lines = Vec::new();
13053        let mut line: VecDeque<Chunk> = VecDeque::new();
13054
13055        let Some(style) = self.style.as_ref() else {
13056            return;
13057        };
13058
13059        for chunk in chunks {
13060            let highlight = chunk
13061                .syntax_highlight_id
13062                .and_then(|id| id.name(&style.syntax));
13063            let mut chunk_lines = chunk.text.split('\n').peekable();
13064            while let Some(text) = chunk_lines.next() {
13065                let mut merged_with_last_token = false;
13066                if let Some(last_token) = line.back_mut() {
13067                    if last_token.highlight == highlight {
13068                        last_token.text.push_str(text);
13069                        merged_with_last_token = true;
13070                    }
13071                }
13072
13073                if !merged_with_last_token {
13074                    line.push_back(Chunk {
13075                        text: text.into(),
13076                        highlight,
13077                    });
13078                }
13079
13080                if chunk_lines.peek().is_some() {
13081                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13082                        line.pop_front();
13083                    }
13084                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13085                        line.pop_back();
13086                    }
13087
13088                    lines.push(mem::take(&mut line));
13089                }
13090            }
13091        }
13092
13093        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13094            return;
13095        };
13096        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13097    }
13098
13099    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13100        &self.inlay_hint_cache
13101    }
13102
13103    pub fn replay_insert_event(
13104        &mut self,
13105        text: &str,
13106        relative_utf16_range: Option<Range<isize>>,
13107        cx: &mut ViewContext<Self>,
13108    ) {
13109        if !self.input_enabled {
13110            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13111            return;
13112        }
13113        if let Some(relative_utf16_range) = relative_utf16_range {
13114            let selections = self.selections.all::<OffsetUtf16>(cx);
13115            self.change_selections(None, cx, |s| {
13116                let new_ranges = selections.into_iter().map(|range| {
13117                    let start = OffsetUtf16(
13118                        range
13119                            .head()
13120                            .0
13121                            .saturating_add_signed(relative_utf16_range.start),
13122                    );
13123                    let end = OffsetUtf16(
13124                        range
13125                            .head()
13126                            .0
13127                            .saturating_add_signed(relative_utf16_range.end),
13128                    );
13129                    start..end
13130                });
13131                s.select_ranges(new_ranges);
13132            });
13133        }
13134
13135        self.handle_input(text, cx);
13136    }
13137
13138    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13139        let Some(provider) = self.semantics_provider.as_ref() else {
13140            return false;
13141        };
13142
13143        let mut supports = false;
13144        self.buffer().read(cx).for_each_buffer(|buffer| {
13145            supports |= provider.supports_inlay_hints(buffer, cx);
13146        });
13147        supports
13148    }
13149
13150    pub fn focus(&self, cx: &mut WindowContext) {
13151        cx.focus(&self.focus_handle)
13152    }
13153
13154    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13155        self.focus_handle.is_focused(cx)
13156    }
13157
13158    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13159        cx.emit(EditorEvent::Focused);
13160
13161        if let Some(descendant) = self
13162            .last_focused_descendant
13163            .take()
13164            .and_then(|descendant| descendant.upgrade())
13165        {
13166            cx.focus(&descendant);
13167        } else {
13168            if let Some(blame) = self.blame.as_ref() {
13169                blame.update(cx, GitBlame::focus)
13170            }
13171
13172            self.blink_manager.update(cx, BlinkManager::enable);
13173            self.show_cursor_names(cx);
13174            self.buffer.update(cx, |buffer, cx| {
13175                buffer.finalize_last_transaction(cx);
13176                if self.leader_peer_id.is_none() {
13177                    buffer.set_active_selections(
13178                        &self.selections.disjoint_anchors(),
13179                        self.selections.line_mode,
13180                        self.cursor_shape,
13181                        cx,
13182                    );
13183                }
13184            });
13185        }
13186    }
13187
13188    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13189        cx.emit(EditorEvent::FocusedIn)
13190    }
13191
13192    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13193        if event.blurred != self.focus_handle {
13194            self.last_focused_descendant = Some(event.blurred);
13195        }
13196    }
13197
13198    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13199        self.blink_manager.update(cx, BlinkManager::disable);
13200        self.buffer
13201            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13202
13203        if let Some(blame) = self.blame.as_ref() {
13204            blame.update(cx, GitBlame::blur)
13205        }
13206        if !self.hover_state.focused(cx) {
13207            hide_hover(self, cx);
13208        }
13209
13210        self.hide_context_menu(cx);
13211        cx.emit(EditorEvent::Blurred);
13212        cx.notify();
13213    }
13214
13215    pub fn register_action<A: Action>(
13216        &mut self,
13217        listener: impl Fn(&A, &mut WindowContext) + 'static,
13218    ) -> Subscription {
13219        let id = self.next_editor_action_id.post_inc();
13220        let listener = Arc::new(listener);
13221        self.editor_actions.borrow_mut().insert(
13222            id,
13223            Box::new(move |cx| {
13224                let cx = cx.window_context();
13225                let listener = listener.clone();
13226                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13227                    let action = action.downcast_ref().unwrap();
13228                    if phase == DispatchPhase::Bubble {
13229                        listener(action, cx)
13230                    }
13231                })
13232            }),
13233        );
13234
13235        let editor_actions = self.editor_actions.clone();
13236        Subscription::new(move || {
13237            editor_actions.borrow_mut().remove(&id);
13238        })
13239    }
13240
13241    pub fn file_header_size(&self) -> u32 {
13242        FILE_HEADER_HEIGHT
13243    }
13244
13245    pub fn revert(
13246        &mut self,
13247        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13248        cx: &mut ViewContext<Self>,
13249    ) {
13250        self.buffer().update(cx, |multi_buffer, cx| {
13251            for (buffer_id, changes) in revert_changes {
13252                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13253                    buffer.update(cx, |buffer, cx| {
13254                        buffer.edit(
13255                            changes.into_iter().map(|(range, text)| {
13256                                (range, text.to_string().map(Arc::<str>::from))
13257                            }),
13258                            None,
13259                            cx,
13260                        );
13261                    });
13262                }
13263            }
13264        });
13265        self.change_selections(None, cx, |selections| selections.refresh());
13266    }
13267
13268    pub fn to_pixel_point(
13269        &mut self,
13270        source: multi_buffer::Anchor,
13271        editor_snapshot: &EditorSnapshot,
13272        cx: &mut ViewContext<Self>,
13273    ) -> Option<gpui::Point<Pixels>> {
13274        let source_point = source.to_display_point(editor_snapshot);
13275        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13276    }
13277
13278    pub fn display_to_pixel_point(
13279        &mut self,
13280        source: DisplayPoint,
13281        editor_snapshot: &EditorSnapshot,
13282        cx: &mut ViewContext<Self>,
13283    ) -> Option<gpui::Point<Pixels>> {
13284        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13285        let text_layout_details = self.text_layout_details(cx);
13286        let scroll_top = text_layout_details
13287            .scroll_anchor
13288            .scroll_position(editor_snapshot)
13289            .y;
13290
13291        if source.row().as_f32() < scroll_top.floor() {
13292            return None;
13293        }
13294        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13295        let source_y = line_height * (source.row().as_f32() - scroll_top);
13296        Some(gpui::Point::new(source_x, source_y))
13297    }
13298
13299    pub fn has_active_completions_menu(&self) -> bool {
13300        self.context_menu.read().as_ref().map_or(false, |menu| {
13301            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13302        })
13303    }
13304
13305    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13306        self.addons
13307            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13308    }
13309
13310    pub fn unregister_addon<T: Addon>(&mut self) {
13311        self.addons.remove(&std::any::TypeId::of::<T>());
13312    }
13313
13314    pub fn addon<T: Addon>(&self) -> Option<&T> {
13315        let type_id = std::any::TypeId::of::<T>();
13316        self.addons
13317            .get(&type_id)
13318            .and_then(|item| item.to_any().downcast_ref::<T>())
13319    }
13320}
13321
13322fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13323    let tab_size = tab_size.get() as usize;
13324    let mut width = offset;
13325
13326    for ch in text.chars() {
13327        width += if ch == '\t' {
13328            tab_size - (width % tab_size)
13329        } else {
13330            1
13331        };
13332    }
13333
13334    width - offset
13335}
13336
13337#[cfg(test)]
13338mod tests {
13339    use super::*;
13340
13341    #[test]
13342    fn test_string_size_with_expanded_tabs() {
13343        let nz = |val| NonZeroU32::new(val).unwrap();
13344        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13345        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13346        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13347        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13348        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13349        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13350        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13351        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13352    }
13353}
13354
13355/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13356struct WordBreakingTokenizer<'a> {
13357    input: &'a str,
13358}
13359
13360impl<'a> WordBreakingTokenizer<'a> {
13361    fn new(input: &'a str) -> Self {
13362        Self { input }
13363    }
13364}
13365
13366fn is_char_ideographic(ch: char) -> bool {
13367    use unicode_script::Script::*;
13368    use unicode_script::UnicodeScript;
13369    matches!(ch.script(), Han | Tangut | Yi)
13370}
13371
13372fn is_grapheme_ideographic(text: &str) -> bool {
13373    text.chars().any(is_char_ideographic)
13374}
13375
13376fn is_grapheme_whitespace(text: &str) -> bool {
13377    text.chars().any(|x| x.is_whitespace())
13378}
13379
13380fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13381    text.chars().next().map_or(false, |ch| {
13382        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13383    })
13384}
13385
13386#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13387struct WordBreakToken<'a> {
13388    token: &'a str,
13389    grapheme_len: usize,
13390    is_whitespace: bool,
13391}
13392
13393impl<'a> Iterator for WordBreakingTokenizer<'a> {
13394    /// Yields a span, the count of graphemes in the token, and whether it was
13395    /// whitespace. Note that it also breaks at word boundaries.
13396    type Item = WordBreakToken<'a>;
13397
13398    fn next(&mut self) -> Option<Self::Item> {
13399        use unicode_segmentation::UnicodeSegmentation;
13400        if self.input.is_empty() {
13401            return None;
13402        }
13403
13404        let mut iter = self.input.graphemes(true).peekable();
13405        let mut offset = 0;
13406        let mut graphemes = 0;
13407        if let Some(first_grapheme) = iter.next() {
13408            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13409            offset += first_grapheme.len();
13410            graphemes += 1;
13411            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13412                if let Some(grapheme) = iter.peek().copied() {
13413                    if should_stay_with_preceding_ideograph(grapheme) {
13414                        offset += grapheme.len();
13415                        graphemes += 1;
13416                    }
13417                }
13418            } else {
13419                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13420                let mut next_word_bound = words.peek().copied();
13421                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13422                    next_word_bound = words.next();
13423                }
13424                while let Some(grapheme) = iter.peek().copied() {
13425                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13426                        break;
13427                    };
13428                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13429                        break;
13430                    };
13431                    offset += grapheme.len();
13432                    graphemes += 1;
13433                    iter.next();
13434                }
13435            }
13436            let token = &self.input[..offset];
13437            self.input = &self.input[offset..];
13438            if is_whitespace {
13439                Some(WordBreakToken {
13440                    token: " ",
13441                    grapheme_len: 1,
13442                    is_whitespace: true,
13443                })
13444            } else {
13445                Some(WordBreakToken {
13446                    token,
13447                    grapheme_len: graphemes,
13448                    is_whitespace: false,
13449                })
13450            }
13451        } else {
13452            None
13453        }
13454    }
13455}
13456
13457#[test]
13458fn test_word_breaking_tokenizer() {
13459    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13460        ("", &[]),
13461        ("  ", &[(" ", 1, true)]),
13462        ("Ʒ", &[("Ʒ", 1, false)]),
13463        ("Ǽ", &[("Ǽ", 1, false)]),
13464        ("", &[("", 1, false)]),
13465        ("⋑⋑", &[("⋑⋑", 2, false)]),
13466        (
13467            "原理,进而",
13468            &[
13469                ("", 1, false),
13470                ("理,", 2, false),
13471                ("", 1, false),
13472                ("", 1, false),
13473            ],
13474        ),
13475        (
13476            "hello world",
13477            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13478        ),
13479        (
13480            "hello, world",
13481            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13482        ),
13483        (
13484            "  hello world",
13485            &[
13486                (" ", 1, true),
13487                ("hello", 5, false),
13488                (" ", 1, true),
13489                ("world", 5, false),
13490            ],
13491        ),
13492        (
13493            "这是什么 \n 钢笔",
13494            &[
13495                ("", 1, false),
13496                ("", 1, false),
13497                ("", 1, false),
13498                ("", 1, false),
13499                (" ", 1, true),
13500                ("", 1, false),
13501                ("", 1, false),
13502            ],
13503        ),
13504        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13505    ];
13506
13507    for (input, result) in tests {
13508        assert_eq!(
13509            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13510            result
13511                .iter()
13512                .copied()
13513                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13514                    token,
13515                    grapheme_len,
13516                    is_whitespace,
13517                })
13518                .collect::<Vec<_>>()
13519        );
13520    }
13521}
13522
13523fn wrap_with_prefix(
13524    line_prefix: String,
13525    unwrapped_text: String,
13526    wrap_column: usize,
13527    tab_size: NonZeroU32,
13528) -> String {
13529    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13530    let mut wrapped_text = String::new();
13531    let mut current_line = line_prefix.clone();
13532
13533    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13534    let mut current_line_len = line_prefix_len;
13535    for WordBreakToken {
13536        token,
13537        grapheme_len,
13538        is_whitespace,
13539    } in tokenizer
13540    {
13541        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13542            wrapped_text.push_str(current_line.trim_end());
13543            wrapped_text.push('\n');
13544            current_line.truncate(line_prefix.len());
13545            current_line_len = line_prefix_len;
13546            if !is_whitespace {
13547                current_line.push_str(token);
13548                current_line_len += grapheme_len;
13549            }
13550        } else if !is_whitespace {
13551            current_line.push_str(token);
13552            current_line_len += grapheme_len;
13553        } else if current_line_len != line_prefix_len {
13554            current_line.push(' ');
13555            current_line_len += 1;
13556        }
13557    }
13558
13559    if !current_line.is_empty() {
13560        wrapped_text.push_str(&current_line);
13561    }
13562    wrapped_text
13563}
13564
13565#[test]
13566fn test_wrap_with_prefix() {
13567    assert_eq!(
13568        wrap_with_prefix(
13569            "# ".to_string(),
13570            "abcdefg".to_string(),
13571            4,
13572            NonZeroU32::new(4).unwrap()
13573        ),
13574        "# abcdefg"
13575    );
13576    assert_eq!(
13577        wrap_with_prefix(
13578            "".to_string(),
13579            "\thello world".to_string(),
13580            8,
13581            NonZeroU32::new(4).unwrap()
13582        ),
13583        "hello\nworld"
13584    );
13585    assert_eq!(
13586        wrap_with_prefix(
13587            "// ".to_string(),
13588            "xx \nyy zz aa bb cc".to_string(),
13589            12,
13590            NonZeroU32::new(4).unwrap()
13591        ),
13592        "// xx yy zz\n// aa bb cc"
13593    );
13594    assert_eq!(
13595        wrap_with_prefix(
13596            String::new(),
13597            "这是什么 \n 钢笔".to_string(),
13598            3,
13599            NonZeroU32::new(4).unwrap()
13600        ),
13601        "这是什\n么 钢\n"
13602    );
13603}
13604
13605fn hunks_for_selections(
13606    multi_buffer_snapshot: &MultiBufferSnapshot,
13607    selections: &[Selection<Anchor>],
13608) -> Vec<MultiBufferDiffHunk> {
13609    let buffer_rows_for_selections = selections.iter().map(|selection| {
13610        let head = selection.head();
13611        let tail = selection.tail();
13612        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13613        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13614        if start > end {
13615            end..start
13616        } else {
13617            start..end
13618        }
13619    });
13620
13621    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13622}
13623
13624pub fn hunks_for_rows(
13625    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13626    multi_buffer_snapshot: &MultiBufferSnapshot,
13627) -> Vec<MultiBufferDiffHunk> {
13628    let mut hunks = Vec::new();
13629    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13630        HashMap::default();
13631    for selected_multi_buffer_rows in rows {
13632        let query_rows =
13633            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13634        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13635            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13636            // when the caret is just above or just below the deleted hunk.
13637            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13638            let related_to_selection = if allow_adjacent {
13639                hunk.row_range.overlaps(&query_rows)
13640                    || hunk.row_range.start == query_rows.end
13641                    || hunk.row_range.end == query_rows.start
13642            } else {
13643                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13644                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13645                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13646                    || selected_multi_buffer_rows.end == hunk.row_range.start
13647            };
13648            if related_to_selection {
13649                if !processed_buffer_rows
13650                    .entry(hunk.buffer_id)
13651                    .or_default()
13652                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13653                {
13654                    continue;
13655                }
13656                hunks.push(hunk);
13657            }
13658        }
13659    }
13660
13661    hunks
13662}
13663
13664pub trait CollaborationHub {
13665    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13666    fn user_participant_indices<'a>(
13667        &self,
13668        cx: &'a AppContext,
13669    ) -> &'a HashMap<u64, ParticipantIndex>;
13670    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13671}
13672
13673impl CollaborationHub for Model<Project> {
13674    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13675        self.read(cx).collaborators()
13676    }
13677
13678    fn user_participant_indices<'a>(
13679        &self,
13680        cx: &'a AppContext,
13681    ) -> &'a HashMap<u64, ParticipantIndex> {
13682        self.read(cx).user_store().read(cx).participant_indices()
13683    }
13684
13685    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13686        let this = self.read(cx);
13687        let user_ids = this.collaborators().values().map(|c| c.user_id);
13688        this.user_store().read_with(cx, |user_store, cx| {
13689            user_store.participant_names(user_ids, cx)
13690        })
13691    }
13692}
13693
13694pub trait SemanticsProvider {
13695    fn hover(
13696        &self,
13697        buffer: &Model<Buffer>,
13698        position: text::Anchor,
13699        cx: &mut AppContext,
13700    ) -> Option<Task<Vec<project::Hover>>>;
13701
13702    fn inlay_hints(
13703        &self,
13704        buffer_handle: Model<Buffer>,
13705        range: Range<text::Anchor>,
13706        cx: &mut AppContext,
13707    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13708
13709    fn resolve_inlay_hint(
13710        &self,
13711        hint: InlayHint,
13712        buffer_handle: Model<Buffer>,
13713        server_id: LanguageServerId,
13714        cx: &mut AppContext,
13715    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13716
13717    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13718
13719    fn document_highlights(
13720        &self,
13721        buffer: &Model<Buffer>,
13722        position: text::Anchor,
13723        cx: &mut AppContext,
13724    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13725
13726    fn definitions(
13727        &self,
13728        buffer: &Model<Buffer>,
13729        position: text::Anchor,
13730        kind: GotoDefinitionKind,
13731        cx: &mut AppContext,
13732    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13733
13734    fn range_for_rename(
13735        &self,
13736        buffer: &Model<Buffer>,
13737        position: text::Anchor,
13738        cx: &mut AppContext,
13739    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13740
13741    fn perform_rename(
13742        &self,
13743        buffer: &Model<Buffer>,
13744        position: text::Anchor,
13745        new_name: String,
13746        cx: &mut AppContext,
13747    ) -> Option<Task<Result<ProjectTransaction>>>;
13748}
13749
13750pub trait CompletionProvider {
13751    fn completions(
13752        &self,
13753        buffer: &Model<Buffer>,
13754        buffer_position: text::Anchor,
13755        trigger: CompletionContext,
13756        cx: &mut ViewContext<Editor>,
13757    ) -> Task<Result<Vec<Completion>>>;
13758
13759    fn resolve_completions(
13760        &self,
13761        buffer: Model<Buffer>,
13762        completion_indices: Vec<usize>,
13763        completions: Arc<RwLock<Box<[Completion]>>>,
13764        cx: &mut ViewContext<Editor>,
13765    ) -> Task<Result<bool>>;
13766
13767    fn apply_additional_edits_for_completion(
13768        &self,
13769        buffer: Model<Buffer>,
13770        completion: Completion,
13771        push_to_history: bool,
13772        cx: &mut ViewContext<Editor>,
13773    ) -> Task<Result<Option<language::Transaction>>>;
13774
13775    fn is_completion_trigger(
13776        &self,
13777        buffer: &Model<Buffer>,
13778        position: language::Anchor,
13779        text: &str,
13780        trigger_in_words: bool,
13781        cx: &mut ViewContext<Editor>,
13782    ) -> bool;
13783
13784    fn sort_completions(&self) -> bool {
13785        true
13786    }
13787}
13788
13789pub trait CodeActionProvider {
13790    fn code_actions(
13791        &self,
13792        buffer: &Model<Buffer>,
13793        range: Range<text::Anchor>,
13794        cx: &mut WindowContext,
13795    ) -> Task<Result<Vec<CodeAction>>>;
13796
13797    fn apply_code_action(
13798        &self,
13799        buffer_handle: Model<Buffer>,
13800        action: CodeAction,
13801        excerpt_id: ExcerptId,
13802        push_to_history: bool,
13803        cx: &mut WindowContext,
13804    ) -> Task<Result<ProjectTransaction>>;
13805}
13806
13807impl CodeActionProvider for Model<Project> {
13808    fn code_actions(
13809        &self,
13810        buffer: &Model<Buffer>,
13811        range: Range<text::Anchor>,
13812        cx: &mut WindowContext,
13813    ) -> Task<Result<Vec<CodeAction>>> {
13814        self.update(cx, |project, cx| {
13815            project.code_actions(buffer, range, None, cx)
13816        })
13817    }
13818
13819    fn apply_code_action(
13820        &self,
13821        buffer_handle: Model<Buffer>,
13822        action: CodeAction,
13823        _excerpt_id: ExcerptId,
13824        push_to_history: bool,
13825        cx: &mut WindowContext,
13826    ) -> Task<Result<ProjectTransaction>> {
13827        self.update(cx, |project, cx| {
13828            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13829        })
13830    }
13831}
13832
13833fn snippet_completions(
13834    project: &Project,
13835    buffer: &Model<Buffer>,
13836    buffer_position: text::Anchor,
13837    cx: &mut AppContext,
13838) -> Vec<Completion> {
13839    let language = buffer.read(cx).language_at(buffer_position);
13840    let language_name = language.as_ref().map(|language| language.lsp_id());
13841    let snippet_store = project.snippets().read(cx);
13842    let snippets = snippet_store.snippets_for(language_name, cx);
13843
13844    if snippets.is_empty() {
13845        return vec![];
13846    }
13847    let snapshot = buffer.read(cx).text_snapshot();
13848    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13849
13850    let scope = language.map(|language| language.default_scope());
13851    let classifier = CharClassifier::new(scope).for_completion(true);
13852    let mut last_word = chars
13853        .take_while(|c| classifier.is_word(*c))
13854        .collect::<String>();
13855    last_word = last_word.chars().rev().collect();
13856    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13857    let to_lsp = |point: &text::Anchor| {
13858        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13859        point_to_lsp(end)
13860    };
13861    let lsp_end = to_lsp(&buffer_position);
13862    snippets
13863        .into_iter()
13864        .filter_map(|snippet| {
13865            let matching_prefix = snippet
13866                .prefix
13867                .iter()
13868                .find(|prefix| prefix.starts_with(&last_word))?;
13869            let start = as_offset - last_word.len();
13870            let start = snapshot.anchor_before(start);
13871            let range = start..buffer_position;
13872            let lsp_start = to_lsp(&start);
13873            let lsp_range = lsp::Range {
13874                start: lsp_start,
13875                end: lsp_end,
13876            };
13877            Some(Completion {
13878                old_range: range,
13879                new_text: snippet.body.clone(),
13880                label: CodeLabel {
13881                    text: matching_prefix.clone(),
13882                    runs: vec![],
13883                    filter_range: 0..matching_prefix.len(),
13884                },
13885                server_id: LanguageServerId(usize::MAX),
13886                documentation: snippet.description.clone().map(Documentation::SingleLine),
13887                lsp_completion: lsp::CompletionItem {
13888                    label: snippet.prefix.first().unwrap().clone(),
13889                    kind: Some(CompletionItemKind::SNIPPET),
13890                    label_details: snippet.description.as_ref().map(|description| {
13891                        lsp::CompletionItemLabelDetails {
13892                            detail: Some(description.clone()),
13893                            description: None,
13894                        }
13895                    }),
13896                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13897                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13898                        lsp::InsertReplaceEdit {
13899                            new_text: snippet.body.clone(),
13900                            insert: lsp_range,
13901                            replace: lsp_range,
13902                        },
13903                    )),
13904                    filter_text: Some(snippet.body.clone()),
13905                    sort_text: Some(char::MAX.to_string()),
13906                    ..Default::default()
13907                },
13908                confirm: None,
13909            })
13910        })
13911        .collect()
13912}
13913
13914impl CompletionProvider for Model<Project> {
13915    fn completions(
13916        &self,
13917        buffer: &Model<Buffer>,
13918        buffer_position: text::Anchor,
13919        options: CompletionContext,
13920        cx: &mut ViewContext<Editor>,
13921    ) -> Task<Result<Vec<Completion>>> {
13922        self.update(cx, |project, cx| {
13923            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13924            let project_completions = project.completions(buffer, buffer_position, options, cx);
13925            cx.background_executor().spawn(async move {
13926                let mut completions = project_completions.await?;
13927                //let snippets = snippets.into_iter().;
13928                completions.extend(snippets);
13929                Ok(completions)
13930            })
13931        })
13932    }
13933
13934    fn resolve_completions(
13935        &self,
13936        buffer: Model<Buffer>,
13937        completion_indices: Vec<usize>,
13938        completions: Arc<RwLock<Box<[Completion]>>>,
13939        cx: &mut ViewContext<Editor>,
13940    ) -> Task<Result<bool>> {
13941        self.update(cx, |project, cx| {
13942            project.resolve_completions(buffer, completion_indices, completions, cx)
13943        })
13944    }
13945
13946    fn apply_additional_edits_for_completion(
13947        &self,
13948        buffer: Model<Buffer>,
13949        completion: Completion,
13950        push_to_history: bool,
13951        cx: &mut ViewContext<Editor>,
13952    ) -> Task<Result<Option<language::Transaction>>> {
13953        self.update(cx, |project, cx| {
13954            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13955        })
13956    }
13957
13958    fn is_completion_trigger(
13959        &self,
13960        buffer: &Model<Buffer>,
13961        position: language::Anchor,
13962        text: &str,
13963        trigger_in_words: bool,
13964        cx: &mut ViewContext<Editor>,
13965    ) -> bool {
13966        if !EditorSettings::get_global(cx).show_completions_on_input {
13967            return false;
13968        }
13969
13970        let mut chars = text.chars();
13971        let char = if let Some(char) = chars.next() {
13972            char
13973        } else {
13974            return false;
13975        };
13976        if chars.next().is_some() {
13977            return false;
13978        }
13979
13980        let buffer = buffer.read(cx);
13981        let classifier = buffer
13982            .snapshot()
13983            .char_classifier_at(position)
13984            .for_completion(true);
13985        if trigger_in_words && classifier.is_word(char) {
13986            return true;
13987        }
13988
13989        buffer.completion_triggers().contains(text)
13990    }
13991}
13992
13993impl SemanticsProvider for Model<Project> {
13994    fn hover(
13995        &self,
13996        buffer: &Model<Buffer>,
13997        position: text::Anchor,
13998        cx: &mut AppContext,
13999    ) -> Option<Task<Vec<project::Hover>>> {
14000        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14001    }
14002
14003    fn document_highlights(
14004        &self,
14005        buffer: &Model<Buffer>,
14006        position: text::Anchor,
14007        cx: &mut AppContext,
14008    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14009        Some(self.update(cx, |project, cx| {
14010            project.document_highlights(buffer, position, cx)
14011        }))
14012    }
14013
14014    fn definitions(
14015        &self,
14016        buffer: &Model<Buffer>,
14017        position: text::Anchor,
14018        kind: GotoDefinitionKind,
14019        cx: &mut AppContext,
14020    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14021        Some(self.update(cx, |project, cx| match kind {
14022            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14023            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14024            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14025            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14026        }))
14027    }
14028
14029    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14030        // TODO: make this work for remote projects
14031        self.read(cx)
14032            .language_servers_for_buffer(buffer.read(cx), cx)
14033            .any(
14034                |(_, server)| match server.capabilities().inlay_hint_provider {
14035                    Some(lsp::OneOf::Left(enabled)) => enabled,
14036                    Some(lsp::OneOf::Right(_)) => true,
14037                    None => false,
14038                },
14039            )
14040    }
14041
14042    fn inlay_hints(
14043        &self,
14044        buffer_handle: Model<Buffer>,
14045        range: Range<text::Anchor>,
14046        cx: &mut AppContext,
14047    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14048        Some(self.update(cx, |project, cx| {
14049            project.inlay_hints(buffer_handle, range, cx)
14050        }))
14051    }
14052
14053    fn resolve_inlay_hint(
14054        &self,
14055        hint: InlayHint,
14056        buffer_handle: Model<Buffer>,
14057        server_id: LanguageServerId,
14058        cx: &mut AppContext,
14059    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14060        Some(self.update(cx, |project, cx| {
14061            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14062        }))
14063    }
14064
14065    fn range_for_rename(
14066        &self,
14067        buffer: &Model<Buffer>,
14068        position: text::Anchor,
14069        cx: &mut AppContext,
14070    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14071        Some(self.update(cx, |project, cx| {
14072            project.prepare_rename(buffer.clone(), position, cx)
14073        }))
14074    }
14075
14076    fn perform_rename(
14077        &self,
14078        buffer: &Model<Buffer>,
14079        position: text::Anchor,
14080        new_name: String,
14081        cx: &mut AppContext,
14082    ) -> Option<Task<Result<ProjectTransaction>>> {
14083        Some(self.update(cx, |project, cx| {
14084            project.perform_rename(buffer.clone(), position, new_name, cx)
14085        }))
14086    }
14087}
14088
14089fn inlay_hint_settings(
14090    location: Anchor,
14091    snapshot: &MultiBufferSnapshot,
14092    cx: &mut ViewContext<'_, Editor>,
14093) -> InlayHintSettings {
14094    let file = snapshot.file_at(location);
14095    let language = snapshot.language_at(location).map(|l| l.name());
14096    language_settings(language, file, cx).inlay_hints
14097}
14098
14099fn consume_contiguous_rows(
14100    contiguous_row_selections: &mut Vec<Selection<Point>>,
14101    selection: &Selection<Point>,
14102    display_map: &DisplaySnapshot,
14103    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14104) -> (MultiBufferRow, MultiBufferRow) {
14105    contiguous_row_selections.push(selection.clone());
14106    let start_row = MultiBufferRow(selection.start.row);
14107    let mut end_row = ending_row(selection, display_map);
14108
14109    while let Some(next_selection) = selections.peek() {
14110        if next_selection.start.row <= end_row.0 {
14111            end_row = ending_row(next_selection, display_map);
14112            contiguous_row_selections.push(selections.next().unwrap().clone());
14113        } else {
14114            break;
14115        }
14116    }
14117    (start_row, end_row)
14118}
14119
14120fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14121    if next_selection.end.column > 0 || next_selection.is_empty() {
14122        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14123    } else {
14124        MultiBufferRow(next_selection.end.row)
14125    }
14126}
14127
14128impl EditorSnapshot {
14129    pub fn remote_selections_in_range<'a>(
14130        &'a self,
14131        range: &'a Range<Anchor>,
14132        collaboration_hub: &dyn CollaborationHub,
14133        cx: &'a AppContext,
14134    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14135        let participant_names = collaboration_hub.user_names(cx);
14136        let participant_indices = collaboration_hub.user_participant_indices(cx);
14137        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14138        let collaborators_by_replica_id = collaborators_by_peer_id
14139            .iter()
14140            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14141            .collect::<HashMap<_, _>>();
14142        self.buffer_snapshot
14143            .selections_in_range(range, false)
14144            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14145                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14146                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14147                let user_name = participant_names.get(&collaborator.user_id).cloned();
14148                Some(RemoteSelection {
14149                    replica_id,
14150                    selection,
14151                    cursor_shape,
14152                    line_mode,
14153                    participant_index,
14154                    peer_id: collaborator.peer_id,
14155                    user_name,
14156                })
14157            })
14158    }
14159
14160    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14161        self.display_snapshot.buffer_snapshot.language_at(position)
14162    }
14163
14164    pub fn is_focused(&self) -> bool {
14165        self.is_focused
14166    }
14167
14168    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14169        self.placeholder_text.as_ref()
14170    }
14171
14172    pub fn scroll_position(&self) -> gpui::Point<f32> {
14173        self.scroll_anchor.scroll_position(&self.display_snapshot)
14174    }
14175
14176    fn gutter_dimensions(
14177        &self,
14178        font_id: FontId,
14179        font_size: Pixels,
14180        em_width: Pixels,
14181        em_advance: Pixels,
14182        max_line_number_width: Pixels,
14183        cx: &AppContext,
14184    ) -> GutterDimensions {
14185        if !self.show_gutter {
14186            return GutterDimensions::default();
14187        }
14188        let descent = cx.text_system().descent(font_id, font_size);
14189
14190        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14191            matches!(
14192                ProjectSettings::get_global(cx).git.git_gutter,
14193                Some(GitGutterSetting::TrackedFiles)
14194            )
14195        });
14196        let gutter_settings = EditorSettings::get_global(cx).gutter;
14197        let show_line_numbers = self
14198            .show_line_numbers
14199            .unwrap_or(gutter_settings.line_numbers);
14200        let line_gutter_width = if show_line_numbers {
14201            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14202            let min_width_for_number_on_gutter = em_advance * 4.0;
14203            max_line_number_width.max(min_width_for_number_on_gutter)
14204        } else {
14205            0.0.into()
14206        };
14207
14208        let show_code_actions = self
14209            .show_code_actions
14210            .unwrap_or(gutter_settings.code_actions);
14211
14212        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14213
14214        let git_blame_entries_width =
14215            self.git_blame_gutter_max_author_length
14216                .map(|max_author_length| {
14217                    // Length of the author name, but also space for the commit hash,
14218                    // the spacing and the timestamp.
14219                    let max_char_count = max_author_length
14220                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14221                        + 7 // length of commit sha
14222                        + 14 // length of max relative timestamp ("60 minutes ago")
14223                        + 4; // gaps and margins
14224
14225                    em_advance * max_char_count
14226                });
14227
14228        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14229        left_padding += if show_code_actions || show_runnables {
14230            em_width * 3.0
14231        } else if show_git_gutter && show_line_numbers {
14232            em_width * 2.0
14233        } else if show_git_gutter || show_line_numbers {
14234            em_width
14235        } else {
14236            px(0.)
14237        };
14238
14239        let right_padding = if gutter_settings.folds && show_line_numbers {
14240            em_width * 4.0
14241        } else if gutter_settings.folds {
14242            em_width * 3.0
14243        } else if show_line_numbers {
14244            em_width
14245        } else {
14246            px(0.)
14247        };
14248
14249        GutterDimensions {
14250            left_padding,
14251            right_padding,
14252            width: line_gutter_width + left_padding + right_padding,
14253            margin: -descent,
14254            git_blame_entries_width,
14255        }
14256    }
14257
14258    pub fn render_crease_toggle(
14259        &self,
14260        buffer_row: MultiBufferRow,
14261        row_contains_cursor: bool,
14262        editor: View<Editor>,
14263        cx: &mut WindowContext,
14264    ) -> Option<AnyElement> {
14265        let folded = self.is_line_folded(buffer_row);
14266        let mut is_foldable = false;
14267
14268        if let Some(crease) = self
14269            .crease_snapshot
14270            .query_row(buffer_row, &self.buffer_snapshot)
14271        {
14272            is_foldable = true;
14273            match crease {
14274                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14275                    if let Some(render_toggle) = render_toggle {
14276                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14277                            if folded {
14278                                editor.update(cx, |editor, cx| {
14279                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14280                                });
14281                            } else {
14282                                editor.update(cx, |editor, cx| {
14283                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14284                                });
14285                            }
14286                        });
14287                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14288                    }
14289                }
14290            }
14291        }
14292
14293        is_foldable |= self.starts_indent(buffer_row);
14294
14295        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14296            Some(
14297                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14298                    .selected(folded)
14299                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14300                        if folded {
14301                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14302                        } else {
14303                            this.fold_at(&FoldAt { buffer_row }, cx);
14304                        }
14305                    }))
14306                    .into_any_element(),
14307            )
14308        } else {
14309            None
14310        }
14311    }
14312
14313    pub fn render_crease_trailer(
14314        &self,
14315        buffer_row: MultiBufferRow,
14316        cx: &mut WindowContext,
14317    ) -> Option<AnyElement> {
14318        let folded = self.is_line_folded(buffer_row);
14319        if let Crease::Inline { render_trailer, .. } = self
14320            .crease_snapshot
14321            .query_row(buffer_row, &self.buffer_snapshot)?
14322        {
14323            let render_trailer = render_trailer.as_ref()?;
14324            Some(render_trailer(buffer_row, folded, cx))
14325        } else {
14326            None
14327        }
14328    }
14329}
14330
14331impl Deref for EditorSnapshot {
14332    type Target = DisplaySnapshot;
14333
14334    fn deref(&self) -> &Self::Target {
14335        &self.display_snapshot
14336    }
14337}
14338
14339#[derive(Clone, Debug, PartialEq, Eq)]
14340pub enum EditorEvent {
14341    InputIgnored {
14342        text: Arc<str>,
14343    },
14344    InputHandled {
14345        utf16_range_to_replace: Option<Range<isize>>,
14346        text: Arc<str>,
14347    },
14348    ExcerptsAdded {
14349        buffer: Model<Buffer>,
14350        predecessor: ExcerptId,
14351        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14352    },
14353    ExcerptsRemoved {
14354        ids: Vec<ExcerptId>,
14355    },
14356    ExcerptsEdited {
14357        ids: Vec<ExcerptId>,
14358    },
14359    ExcerptsExpanded {
14360        ids: Vec<ExcerptId>,
14361    },
14362    BufferEdited,
14363    Edited {
14364        transaction_id: clock::Lamport,
14365    },
14366    Reparsed(BufferId),
14367    Focused,
14368    FocusedIn,
14369    Blurred,
14370    DirtyChanged,
14371    Saved,
14372    TitleChanged,
14373    DiffBaseChanged,
14374    SelectionsChanged {
14375        local: bool,
14376    },
14377    ScrollPositionChanged {
14378        local: bool,
14379        autoscroll: bool,
14380    },
14381    Closed,
14382    TransactionUndone {
14383        transaction_id: clock::Lamport,
14384    },
14385    TransactionBegun {
14386        transaction_id: clock::Lamport,
14387    },
14388    Reloaded,
14389    CursorShapeChanged,
14390}
14391
14392impl EventEmitter<EditorEvent> for Editor {}
14393
14394impl FocusableView for Editor {
14395    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14396        self.focus_handle.clone()
14397    }
14398}
14399
14400impl Render for Editor {
14401    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14402        let settings = ThemeSettings::get_global(cx);
14403
14404        let mut text_style = match self.mode {
14405            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14406                color: cx.theme().colors().editor_foreground,
14407                font_family: settings.ui_font.family.clone(),
14408                font_features: settings.ui_font.features.clone(),
14409                font_fallbacks: settings.ui_font.fallbacks.clone(),
14410                font_size: rems(0.875).into(),
14411                font_weight: settings.ui_font.weight,
14412                line_height: relative(settings.buffer_line_height.value()),
14413                ..Default::default()
14414            },
14415            EditorMode::Full => TextStyle {
14416                color: cx.theme().colors().editor_foreground,
14417                font_family: settings.buffer_font.family.clone(),
14418                font_features: settings.buffer_font.features.clone(),
14419                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14420                font_size: settings.buffer_font_size(cx).into(),
14421                font_weight: settings.buffer_font.weight,
14422                line_height: relative(settings.buffer_line_height.value()),
14423                ..Default::default()
14424            },
14425        };
14426        if let Some(text_style_refinement) = &self.text_style_refinement {
14427            text_style.refine(text_style_refinement)
14428        }
14429
14430        let background = match self.mode {
14431            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14432            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14433            EditorMode::Full => cx.theme().colors().editor_background,
14434        };
14435
14436        EditorElement::new(
14437            cx.view(),
14438            EditorStyle {
14439                background,
14440                local_player: cx.theme().players().local(),
14441                text: text_style,
14442                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14443                syntax: cx.theme().syntax().clone(),
14444                status: cx.theme().status().clone(),
14445                inlay_hints_style: make_inlay_hints_style(cx),
14446                suggestions_style: HighlightStyle {
14447                    color: Some(cx.theme().status().predictive),
14448                    ..HighlightStyle::default()
14449                },
14450                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14451            },
14452        )
14453    }
14454}
14455
14456impl ViewInputHandler for Editor {
14457    fn text_for_range(
14458        &mut self,
14459        range_utf16: Range<usize>,
14460        adjusted_range: &mut Option<Range<usize>>,
14461        cx: &mut ViewContext<Self>,
14462    ) -> Option<String> {
14463        let snapshot = self.buffer.read(cx).read(cx);
14464        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14465        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14466        if (start.0..end.0) != range_utf16 {
14467            adjusted_range.replace(start.0..end.0);
14468        }
14469        Some(snapshot.text_for_range(start..end).collect())
14470    }
14471
14472    fn selected_text_range(
14473        &mut self,
14474        ignore_disabled_input: bool,
14475        cx: &mut ViewContext<Self>,
14476    ) -> Option<UTF16Selection> {
14477        // Prevent the IME menu from appearing when holding down an alphabetic key
14478        // while input is disabled.
14479        if !ignore_disabled_input && !self.input_enabled {
14480            return None;
14481        }
14482
14483        let selection = self.selections.newest::<OffsetUtf16>(cx);
14484        let range = selection.range();
14485
14486        Some(UTF16Selection {
14487            range: range.start.0..range.end.0,
14488            reversed: selection.reversed,
14489        })
14490    }
14491
14492    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14493        let snapshot = self.buffer.read(cx).read(cx);
14494        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14495        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14496    }
14497
14498    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14499        self.clear_highlights::<InputComposition>(cx);
14500        self.ime_transaction.take();
14501    }
14502
14503    fn replace_text_in_range(
14504        &mut self,
14505        range_utf16: Option<Range<usize>>,
14506        text: &str,
14507        cx: &mut ViewContext<Self>,
14508    ) {
14509        if !self.input_enabled {
14510            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14511            return;
14512        }
14513
14514        self.transact(cx, |this, cx| {
14515            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14516                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14517                Some(this.selection_replacement_ranges(range_utf16, cx))
14518            } else {
14519                this.marked_text_ranges(cx)
14520            };
14521
14522            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14523                let newest_selection_id = this.selections.newest_anchor().id;
14524                this.selections
14525                    .all::<OffsetUtf16>(cx)
14526                    .iter()
14527                    .zip(ranges_to_replace.iter())
14528                    .find_map(|(selection, range)| {
14529                        if selection.id == newest_selection_id {
14530                            Some(
14531                                (range.start.0 as isize - selection.head().0 as isize)
14532                                    ..(range.end.0 as isize - selection.head().0 as isize),
14533                            )
14534                        } else {
14535                            None
14536                        }
14537                    })
14538            });
14539
14540            cx.emit(EditorEvent::InputHandled {
14541                utf16_range_to_replace: range_to_replace,
14542                text: text.into(),
14543            });
14544
14545            if let Some(new_selected_ranges) = new_selected_ranges {
14546                this.change_selections(None, cx, |selections| {
14547                    selections.select_ranges(new_selected_ranges)
14548                });
14549                this.backspace(&Default::default(), cx);
14550            }
14551
14552            this.handle_input(text, cx);
14553        });
14554
14555        if let Some(transaction) = self.ime_transaction {
14556            self.buffer.update(cx, |buffer, cx| {
14557                buffer.group_until_transaction(transaction, cx);
14558            });
14559        }
14560
14561        self.unmark_text(cx);
14562    }
14563
14564    fn replace_and_mark_text_in_range(
14565        &mut self,
14566        range_utf16: Option<Range<usize>>,
14567        text: &str,
14568        new_selected_range_utf16: Option<Range<usize>>,
14569        cx: &mut ViewContext<Self>,
14570    ) {
14571        if !self.input_enabled {
14572            return;
14573        }
14574
14575        let transaction = self.transact(cx, |this, cx| {
14576            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14577                let snapshot = this.buffer.read(cx).read(cx);
14578                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14579                    for marked_range in &mut marked_ranges {
14580                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14581                        marked_range.start.0 += relative_range_utf16.start;
14582                        marked_range.start =
14583                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14584                        marked_range.end =
14585                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14586                    }
14587                }
14588                Some(marked_ranges)
14589            } else if let Some(range_utf16) = range_utf16 {
14590                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14591                Some(this.selection_replacement_ranges(range_utf16, cx))
14592            } else {
14593                None
14594            };
14595
14596            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14597                let newest_selection_id = this.selections.newest_anchor().id;
14598                this.selections
14599                    .all::<OffsetUtf16>(cx)
14600                    .iter()
14601                    .zip(ranges_to_replace.iter())
14602                    .find_map(|(selection, range)| {
14603                        if selection.id == newest_selection_id {
14604                            Some(
14605                                (range.start.0 as isize - selection.head().0 as isize)
14606                                    ..(range.end.0 as isize - selection.head().0 as isize),
14607                            )
14608                        } else {
14609                            None
14610                        }
14611                    })
14612            });
14613
14614            cx.emit(EditorEvent::InputHandled {
14615                utf16_range_to_replace: range_to_replace,
14616                text: text.into(),
14617            });
14618
14619            if let Some(ranges) = ranges_to_replace {
14620                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14621            }
14622
14623            let marked_ranges = {
14624                let snapshot = this.buffer.read(cx).read(cx);
14625                this.selections
14626                    .disjoint_anchors()
14627                    .iter()
14628                    .map(|selection| {
14629                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14630                    })
14631                    .collect::<Vec<_>>()
14632            };
14633
14634            if text.is_empty() {
14635                this.unmark_text(cx);
14636            } else {
14637                this.highlight_text::<InputComposition>(
14638                    marked_ranges.clone(),
14639                    HighlightStyle {
14640                        underline: Some(UnderlineStyle {
14641                            thickness: px(1.),
14642                            color: None,
14643                            wavy: false,
14644                        }),
14645                        ..Default::default()
14646                    },
14647                    cx,
14648                );
14649            }
14650
14651            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14652            let use_autoclose = this.use_autoclose;
14653            let use_auto_surround = this.use_auto_surround;
14654            this.set_use_autoclose(false);
14655            this.set_use_auto_surround(false);
14656            this.handle_input(text, cx);
14657            this.set_use_autoclose(use_autoclose);
14658            this.set_use_auto_surround(use_auto_surround);
14659
14660            if let Some(new_selected_range) = new_selected_range_utf16 {
14661                let snapshot = this.buffer.read(cx).read(cx);
14662                let new_selected_ranges = marked_ranges
14663                    .into_iter()
14664                    .map(|marked_range| {
14665                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14666                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14667                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14668                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14669                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14670                    })
14671                    .collect::<Vec<_>>();
14672
14673                drop(snapshot);
14674                this.change_selections(None, cx, |selections| {
14675                    selections.select_ranges(new_selected_ranges)
14676                });
14677            }
14678        });
14679
14680        self.ime_transaction = self.ime_transaction.or(transaction);
14681        if let Some(transaction) = self.ime_transaction {
14682            self.buffer.update(cx, |buffer, cx| {
14683                buffer.group_until_transaction(transaction, cx);
14684            });
14685        }
14686
14687        if self.text_highlights::<InputComposition>(cx).is_none() {
14688            self.ime_transaction.take();
14689        }
14690    }
14691
14692    fn bounds_for_range(
14693        &mut self,
14694        range_utf16: Range<usize>,
14695        element_bounds: gpui::Bounds<Pixels>,
14696        cx: &mut ViewContext<Self>,
14697    ) -> Option<gpui::Bounds<Pixels>> {
14698        let text_layout_details = self.text_layout_details(cx);
14699        let style = &text_layout_details.editor_style;
14700        let font_id = cx.text_system().resolve_font(&style.text.font());
14701        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14702        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14703
14704        let em_width = cx
14705            .text_system()
14706            .typographic_bounds(font_id, font_size, 'm')
14707            .unwrap()
14708            .size
14709            .width;
14710
14711        let snapshot = self.snapshot(cx);
14712        let scroll_position = snapshot.scroll_position();
14713        let scroll_left = scroll_position.x * em_width;
14714
14715        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14716        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14717            + self.gutter_dimensions.width;
14718        let y = line_height * (start.row().as_f32() - scroll_position.y);
14719
14720        Some(Bounds {
14721            origin: element_bounds.origin + point(x, y),
14722            size: size(em_width, line_height),
14723        })
14724    }
14725}
14726
14727trait SelectionExt {
14728    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14729    fn spanned_rows(
14730        &self,
14731        include_end_if_at_line_start: bool,
14732        map: &DisplaySnapshot,
14733    ) -> Range<MultiBufferRow>;
14734}
14735
14736impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14737    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14738        let start = self
14739            .start
14740            .to_point(&map.buffer_snapshot)
14741            .to_display_point(map);
14742        let end = self
14743            .end
14744            .to_point(&map.buffer_snapshot)
14745            .to_display_point(map);
14746        if self.reversed {
14747            end..start
14748        } else {
14749            start..end
14750        }
14751    }
14752
14753    fn spanned_rows(
14754        &self,
14755        include_end_if_at_line_start: bool,
14756        map: &DisplaySnapshot,
14757    ) -> Range<MultiBufferRow> {
14758        let start = self.start.to_point(&map.buffer_snapshot);
14759        let mut end = self.end.to_point(&map.buffer_snapshot);
14760        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14761            end.row -= 1;
14762        }
14763
14764        let buffer_start = map.prev_line_boundary(start).0;
14765        let buffer_end = map.next_line_boundary(end).0;
14766        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14767    }
14768}
14769
14770impl<T: InvalidationRegion> InvalidationStack<T> {
14771    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14772    where
14773        S: Clone + ToOffset,
14774    {
14775        while let Some(region) = self.last() {
14776            let all_selections_inside_invalidation_ranges =
14777                if selections.len() == region.ranges().len() {
14778                    selections
14779                        .iter()
14780                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14781                        .all(|(selection, invalidation_range)| {
14782                            let head = selection.head().to_offset(buffer);
14783                            invalidation_range.start <= head && invalidation_range.end >= head
14784                        })
14785                } else {
14786                    false
14787                };
14788
14789            if all_selections_inside_invalidation_ranges {
14790                break;
14791            } else {
14792                self.pop();
14793            }
14794        }
14795    }
14796}
14797
14798impl<T> Default for InvalidationStack<T> {
14799    fn default() -> Self {
14800        Self(Default::default())
14801    }
14802}
14803
14804impl<T> Deref for InvalidationStack<T> {
14805    type Target = Vec<T>;
14806
14807    fn deref(&self) -> &Self::Target {
14808        &self.0
14809    }
14810}
14811
14812impl<T> DerefMut for InvalidationStack<T> {
14813    fn deref_mut(&mut self) -> &mut Self::Target {
14814        &mut self.0
14815    }
14816}
14817
14818impl InvalidationRegion for SnippetState {
14819    fn ranges(&self) -> &[Range<Anchor>] {
14820        &self.ranges[self.active_index]
14821    }
14822}
14823
14824pub fn diagnostic_block_renderer(
14825    diagnostic: Diagnostic,
14826    max_message_rows: Option<u8>,
14827    allow_closing: bool,
14828    _is_valid: bool,
14829) -> RenderBlock {
14830    let (text_without_backticks, code_ranges) =
14831        highlight_diagnostic_message(&diagnostic, max_message_rows);
14832
14833    Arc::new(move |cx: &mut BlockContext| {
14834        let group_id: SharedString = cx.block_id.to_string().into();
14835
14836        let mut text_style = cx.text_style().clone();
14837        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14838        let theme_settings = ThemeSettings::get_global(cx);
14839        text_style.font_family = theme_settings.buffer_font.family.clone();
14840        text_style.font_style = theme_settings.buffer_font.style;
14841        text_style.font_features = theme_settings.buffer_font.features.clone();
14842        text_style.font_weight = theme_settings.buffer_font.weight;
14843
14844        let multi_line_diagnostic = diagnostic.message.contains('\n');
14845
14846        let buttons = |diagnostic: &Diagnostic| {
14847            if multi_line_diagnostic {
14848                v_flex()
14849            } else {
14850                h_flex()
14851            }
14852            .when(allow_closing, |div| {
14853                div.children(diagnostic.is_primary.then(|| {
14854                    IconButton::new("close-block", IconName::XCircle)
14855                        .icon_color(Color::Muted)
14856                        .size(ButtonSize::Compact)
14857                        .style(ButtonStyle::Transparent)
14858                        .visible_on_hover(group_id.clone())
14859                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14860                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14861                }))
14862            })
14863            .child(
14864                IconButton::new("copy-block", IconName::Copy)
14865                    .icon_color(Color::Muted)
14866                    .size(ButtonSize::Compact)
14867                    .style(ButtonStyle::Transparent)
14868                    .visible_on_hover(group_id.clone())
14869                    .on_click({
14870                        let message = diagnostic.message.clone();
14871                        move |_click, cx| {
14872                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14873                        }
14874                    })
14875                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14876            )
14877        };
14878
14879        let icon_size = buttons(&diagnostic)
14880            .into_any_element()
14881            .layout_as_root(AvailableSpace::min_size(), cx);
14882
14883        h_flex()
14884            .id(cx.block_id)
14885            .group(group_id.clone())
14886            .relative()
14887            .size_full()
14888            .block_mouse_down()
14889            .pl(cx.gutter_dimensions.width)
14890            .w(cx.max_width - cx.gutter_dimensions.full_width())
14891            .child(
14892                div()
14893                    .flex()
14894                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14895                    .flex_shrink(),
14896            )
14897            .child(buttons(&diagnostic))
14898            .child(div().flex().flex_shrink_0().child(
14899                StyledText::new(text_without_backticks.clone()).with_highlights(
14900                    &text_style,
14901                    code_ranges.iter().map(|range| {
14902                        (
14903                            range.clone(),
14904                            HighlightStyle {
14905                                font_weight: Some(FontWeight::BOLD),
14906                                ..Default::default()
14907                            },
14908                        )
14909                    }),
14910                ),
14911            ))
14912            .into_any_element()
14913    })
14914}
14915
14916pub fn highlight_diagnostic_message(
14917    diagnostic: &Diagnostic,
14918    mut max_message_rows: Option<u8>,
14919) -> (SharedString, Vec<Range<usize>>) {
14920    let mut text_without_backticks = String::new();
14921    let mut code_ranges = Vec::new();
14922
14923    if let Some(source) = &diagnostic.source {
14924        text_without_backticks.push_str(source);
14925        code_ranges.push(0..source.len());
14926        text_without_backticks.push_str(": ");
14927    }
14928
14929    let mut prev_offset = 0;
14930    let mut in_code_block = false;
14931    let has_row_limit = max_message_rows.is_some();
14932    let mut newline_indices = diagnostic
14933        .message
14934        .match_indices('\n')
14935        .filter(|_| has_row_limit)
14936        .map(|(ix, _)| ix)
14937        .fuse()
14938        .peekable();
14939
14940    for (quote_ix, _) in diagnostic
14941        .message
14942        .match_indices('`')
14943        .chain([(diagnostic.message.len(), "")])
14944    {
14945        let mut first_newline_ix = None;
14946        let mut last_newline_ix = None;
14947        while let Some(newline_ix) = newline_indices.peek() {
14948            if *newline_ix < quote_ix {
14949                if first_newline_ix.is_none() {
14950                    first_newline_ix = Some(*newline_ix);
14951                }
14952                last_newline_ix = Some(*newline_ix);
14953
14954                if let Some(rows_left) = &mut max_message_rows {
14955                    if *rows_left == 0 {
14956                        break;
14957                    } else {
14958                        *rows_left -= 1;
14959                    }
14960                }
14961                let _ = newline_indices.next();
14962            } else {
14963                break;
14964            }
14965        }
14966        let prev_len = text_without_backticks.len();
14967        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14968        text_without_backticks.push_str(new_text);
14969        if in_code_block {
14970            code_ranges.push(prev_len..text_without_backticks.len());
14971        }
14972        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14973        in_code_block = !in_code_block;
14974        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14975            text_without_backticks.push_str("...");
14976            break;
14977        }
14978    }
14979
14980    (text_without_backticks.into(), code_ranges)
14981}
14982
14983fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14984    match severity {
14985        DiagnosticSeverity::ERROR => colors.error,
14986        DiagnosticSeverity::WARNING => colors.warning,
14987        DiagnosticSeverity::INFORMATION => colors.info,
14988        DiagnosticSeverity::HINT => colors.info,
14989        _ => colors.ignored,
14990    }
14991}
14992
14993pub fn styled_runs_for_code_label<'a>(
14994    label: &'a CodeLabel,
14995    syntax_theme: &'a theme::SyntaxTheme,
14996) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14997    let fade_out = HighlightStyle {
14998        fade_out: Some(0.35),
14999        ..Default::default()
15000    };
15001
15002    let mut prev_end = label.filter_range.end;
15003    label
15004        .runs
15005        .iter()
15006        .enumerate()
15007        .flat_map(move |(ix, (range, highlight_id))| {
15008            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15009                style
15010            } else {
15011                return Default::default();
15012            };
15013            let mut muted_style = style;
15014            muted_style.highlight(fade_out);
15015
15016            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15017            if range.start >= label.filter_range.end {
15018                if range.start > prev_end {
15019                    runs.push((prev_end..range.start, fade_out));
15020                }
15021                runs.push((range.clone(), muted_style));
15022            } else if range.end <= label.filter_range.end {
15023                runs.push((range.clone(), style));
15024            } else {
15025                runs.push((range.start..label.filter_range.end, style));
15026                runs.push((label.filter_range.end..range.end, muted_style));
15027            }
15028            prev_end = cmp::max(prev_end, range.end);
15029
15030            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15031                runs.push((prev_end..label.text.len(), fade_out));
15032            }
15033
15034            runs
15035        })
15036}
15037
15038pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15039    let mut prev_index = 0;
15040    let mut prev_codepoint: Option<char> = None;
15041    text.char_indices()
15042        .chain([(text.len(), '\0')])
15043        .filter_map(move |(index, codepoint)| {
15044            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15045            let is_boundary = index == text.len()
15046                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15047                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15048            if is_boundary {
15049                let chunk = &text[prev_index..index];
15050                prev_index = index;
15051                Some(chunk)
15052            } else {
15053                None
15054            }
15055        })
15056}
15057
15058pub trait RangeToAnchorExt: Sized {
15059    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15060
15061    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15062        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15063        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15064    }
15065}
15066
15067impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15068    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15069        let start_offset = self.start.to_offset(snapshot);
15070        let end_offset = self.end.to_offset(snapshot);
15071        if start_offset == end_offset {
15072            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15073        } else {
15074            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15075        }
15076    }
15077}
15078
15079pub trait RowExt {
15080    fn as_f32(&self) -> f32;
15081
15082    fn next_row(&self) -> Self;
15083
15084    fn previous_row(&self) -> Self;
15085
15086    fn minus(&self, other: Self) -> u32;
15087}
15088
15089impl RowExt for DisplayRow {
15090    fn as_f32(&self) -> f32 {
15091        self.0 as f32
15092    }
15093
15094    fn next_row(&self) -> Self {
15095        Self(self.0 + 1)
15096    }
15097
15098    fn previous_row(&self) -> Self {
15099        Self(self.0.saturating_sub(1))
15100    }
15101
15102    fn minus(&self, other: Self) -> u32 {
15103        self.0 - other.0
15104    }
15105}
15106
15107impl RowExt for MultiBufferRow {
15108    fn as_f32(&self) -> f32 {
15109        self.0 as f32
15110    }
15111
15112    fn next_row(&self) -> Self {
15113        Self(self.0 + 1)
15114    }
15115
15116    fn previous_row(&self) -> Self {
15117        Self(self.0.saturating_sub(1))
15118    }
15119
15120    fn minus(&self, other: Self) -> u32 {
15121        self.0 - other.0
15122    }
15123}
15124
15125trait RowRangeExt {
15126    type Row;
15127
15128    fn len(&self) -> usize;
15129
15130    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15131}
15132
15133impl RowRangeExt for Range<MultiBufferRow> {
15134    type Row = MultiBufferRow;
15135
15136    fn len(&self) -> usize {
15137        (self.end.0 - self.start.0) as usize
15138    }
15139
15140    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15141        (self.start.0..self.end.0).map(MultiBufferRow)
15142    }
15143}
15144
15145impl RowRangeExt for Range<DisplayRow> {
15146    type Row = DisplayRow;
15147
15148    fn len(&self) -> usize {
15149        (self.end.0 - self.start.0) as usize
15150    }
15151
15152    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15153        (self.start.0..self.end.0).map(DisplayRow)
15154    }
15155}
15156
15157fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15158    if hunk.diff_base_byte_range.is_empty() {
15159        DiffHunkStatus::Added
15160    } else if hunk.row_range.is_empty() {
15161        DiffHunkStatus::Removed
15162    } else {
15163        DiffHunkStatus::Modified
15164    }
15165}
15166
15167/// If select range has more than one line, we
15168/// just point the cursor to range.start.
15169fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15170    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15171        range
15172    } else {
15173        range.start..range.start
15174    }
15175}
15176
15177pub struct KillRing(ClipboardItem);
15178impl Global for KillRing {}
15179
15180const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);