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, Location, LocationLink,
  129    Project, ProjectItem, 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
  537/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  538///
  539/// See the [module level documentation](self) for more information.
  540pub struct Editor {
  541    focus_handle: FocusHandle,
  542    last_focused_descendant: Option<WeakFocusHandle>,
  543    /// The text buffer being edited
  544    buffer: Model<MultiBuffer>,
  545    /// Map of how text in the buffer should be displayed.
  546    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  547    pub display_map: Model<DisplayMap>,
  548    pub selections: SelectionsCollection,
  549    pub scroll_manager: ScrollManager,
  550    /// When inline assist editors are linked, they all render cursors because
  551    /// typing enters text into each of them, even the ones that aren't focused.
  552    pub(crate) show_cursor_when_unfocused: bool,
  553    columnar_selection_tail: Option<Anchor>,
  554    add_selections_state: Option<AddSelectionsState>,
  555    select_next_state: Option<SelectNextState>,
  556    select_prev_state: Option<SelectNextState>,
  557    selection_history: SelectionHistory,
  558    autoclose_regions: Vec<AutocloseRegion>,
  559    snippet_stack: InvalidationStack<SnippetState>,
  560    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  561    ime_transaction: Option<TransactionId>,
  562    active_diagnostics: Option<ActiveDiagnosticGroup>,
  563    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  564
  565    project: Option<Model<Project>>,
  566    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  567    completion_provider: Option<Box<dyn CompletionProvider>>,
  568    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  569    blink_manager: Model<BlinkManager>,
  570    show_cursor_names: bool,
  571    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  572    pub show_local_selections: bool,
  573    mode: EditorMode,
  574    show_breadcrumbs: bool,
  575    show_gutter: bool,
  576    show_line_numbers: Option<bool>,
  577    use_relative_line_numbers: Option<bool>,
  578    show_git_diff_gutter: Option<bool>,
  579    show_code_actions: Option<bool>,
  580    show_runnables: Option<bool>,
  581    show_wrap_guides: Option<bool>,
  582    show_indent_guides: Option<bool>,
  583    placeholder_text: Option<Arc<str>>,
  584    highlight_order: usize,
  585    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  586    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  587    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  588    scrollbar_marker_state: ScrollbarMarkerState,
  589    active_indent_guides_state: ActiveIndentGuidesState,
  590    nav_history: Option<ItemNavHistory>,
  591    context_menu: RwLock<Option<ContextMenu>>,
  592    mouse_context_menu: Option<MouseContextMenu>,
  593    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  594    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  595    signature_help_state: SignatureHelpState,
  596    auto_signature_help: Option<bool>,
  597    find_all_references_task_sources: Vec<Anchor>,
  598    next_completion_id: CompletionId,
  599    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  600    code_actions_task: Option<Task<Result<()>>>,
  601    document_highlights_task: Option<Task<()>>,
  602    linked_editing_range_task: Option<Task<Option<()>>>,
  603    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  604    pending_rename: Option<RenameState>,
  605    searchable: bool,
  606    cursor_shape: CursorShape,
  607    current_line_highlight: Option<CurrentLineHighlight>,
  608    collapse_matches: bool,
  609    autoindent_mode: Option<AutoindentMode>,
  610    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  611    input_enabled: bool,
  612    use_modal_editing: bool,
  613    read_only: bool,
  614    leader_peer_id: Option<PeerId>,
  615    remote_id: Option<ViewId>,
  616    hover_state: HoverState,
  617    gutter_hovered: bool,
  618    hovered_link_state: Option<HoveredLinkState>,
  619    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  620    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  621    active_inline_completion: Option<CompletionState>,
  622    // enable_inline_completions is a switch that Vim can use to disable
  623    // inline completions based on its mode.
  624    enable_inline_completions: bool,
  625    show_inline_completions_override: Option<bool>,
  626    inlay_hint_cache: InlayHintCache,
  627    expanded_hunks: ExpandedHunks,
  628    next_inlay_id: usize,
  629    _subscriptions: Vec<Subscription>,
  630    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  631    gutter_dimensions: GutterDimensions,
  632    style: Option<EditorStyle>,
  633    text_style_refinement: Option<TextStyleRefinement>,
  634    next_editor_action_id: EditorActionId,
  635    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  636    use_autoclose: bool,
  637    use_auto_surround: bool,
  638    auto_replace_emoji_shortcode: bool,
  639    show_git_blame_gutter: bool,
  640    show_git_blame_inline: bool,
  641    show_git_blame_inline_delay_task: Option<Task<()>>,
  642    git_blame_inline_enabled: bool,
  643    serialize_dirty_buffers: bool,
  644    show_selection_menu: Option<bool>,
  645    blame: Option<Model<GitBlame>>,
  646    blame_subscription: Option<Subscription>,
  647    custom_context_menu: Option<
  648        Box<
  649            dyn 'static
  650                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  651        >,
  652    >,
  653    last_bounds: Option<Bounds<Pixels>>,
  654    expect_bounds_change: Option<Bounds<Pixels>>,
  655    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  656    tasks_update_task: Option<Task<()>>,
  657    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  658    breadcrumb_header: Option<String>,
  659    focused_block: Option<FocusedBlock>,
  660    next_scroll_position: NextScrollCursorCenterTopBottom,
  661    addons: HashMap<TypeId, Box<dyn Addon>>,
  662    _scroll_cursor_center_top_bottom_task: Task<()>,
  663}
  664
  665#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  666enum NextScrollCursorCenterTopBottom {
  667    #[default]
  668    Center,
  669    Top,
  670    Bottom,
  671}
  672
  673impl NextScrollCursorCenterTopBottom {
  674    fn next(&self) -> Self {
  675        match self {
  676            Self::Center => Self::Top,
  677            Self::Top => Self::Bottom,
  678            Self::Bottom => Self::Center,
  679        }
  680    }
  681}
  682
  683#[derive(Clone)]
  684pub struct EditorSnapshot {
  685    pub mode: EditorMode,
  686    show_gutter: bool,
  687    show_line_numbers: Option<bool>,
  688    show_git_diff_gutter: Option<bool>,
  689    show_code_actions: Option<bool>,
  690    show_runnables: Option<bool>,
  691    git_blame_gutter_max_author_length: Option<usize>,
  692    pub display_snapshot: DisplaySnapshot,
  693    pub placeholder_text: Option<Arc<str>>,
  694    is_focused: bool,
  695    scroll_anchor: ScrollAnchor,
  696    ongoing_scroll: OngoingScroll,
  697    current_line_highlight: CurrentLineHighlight,
  698    gutter_hovered: bool,
  699}
  700
  701const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  702
  703#[derive(Default, Debug, Clone, Copy)]
  704pub struct GutterDimensions {
  705    pub left_padding: Pixels,
  706    pub right_padding: Pixels,
  707    pub width: Pixels,
  708    pub margin: Pixels,
  709    pub git_blame_entries_width: Option<Pixels>,
  710}
  711
  712impl GutterDimensions {
  713    /// The full width of the space taken up by the gutter.
  714    pub fn full_width(&self) -> Pixels {
  715        self.margin + self.width
  716    }
  717
  718    /// The width of the space reserved for the fold indicators,
  719    /// use alongside 'justify_end' and `gutter_width` to
  720    /// right align content with the line numbers
  721    pub fn fold_area_width(&self) -> Pixels {
  722        self.margin + self.right_padding
  723    }
  724}
  725
  726#[derive(Debug)]
  727pub struct RemoteSelection {
  728    pub replica_id: ReplicaId,
  729    pub selection: Selection<Anchor>,
  730    pub cursor_shape: CursorShape,
  731    pub peer_id: PeerId,
  732    pub line_mode: bool,
  733    pub participant_index: Option<ParticipantIndex>,
  734    pub user_name: Option<SharedString>,
  735}
  736
  737#[derive(Clone, Debug)]
  738struct SelectionHistoryEntry {
  739    selections: Arc<[Selection<Anchor>]>,
  740    select_next_state: Option<SelectNextState>,
  741    select_prev_state: Option<SelectNextState>,
  742    add_selections_state: Option<AddSelectionsState>,
  743}
  744
  745enum SelectionHistoryMode {
  746    Normal,
  747    Undoing,
  748    Redoing,
  749}
  750
  751#[derive(Clone, PartialEq, Eq, Hash)]
  752struct HoveredCursor {
  753    replica_id: u16,
  754    selection_id: usize,
  755}
  756
  757impl Default for SelectionHistoryMode {
  758    fn default() -> Self {
  759        Self::Normal
  760    }
  761}
  762
  763#[derive(Default)]
  764struct SelectionHistory {
  765    #[allow(clippy::type_complexity)]
  766    selections_by_transaction:
  767        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  768    mode: SelectionHistoryMode,
  769    undo_stack: VecDeque<SelectionHistoryEntry>,
  770    redo_stack: VecDeque<SelectionHistoryEntry>,
  771}
  772
  773impl SelectionHistory {
  774    fn insert_transaction(
  775        &mut self,
  776        transaction_id: TransactionId,
  777        selections: Arc<[Selection<Anchor>]>,
  778    ) {
  779        self.selections_by_transaction
  780            .insert(transaction_id, (selections, None));
  781    }
  782
  783    #[allow(clippy::type_complexity)]
  784    fn transaction(
  785        &self,
  786        transaction_id: TransactionId,
  787    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  788        self.selections_by_transaction.get(&transaction_id)
  789    }
  790
  791    #[allow(clippy::type_complexity)]
  792    fn transaction_mut(
  793        &mut self,
  794        transaction_id: TransactionId,
  795    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  796        self.selections_by_transaction.get_mut(&transaction_id)
  797    }
  798
  799    fn push(&mut self, entry: SelectionHistoryEntry) {
  800        if !entry.selections.is_empty() {
  801            match self.mode {
  802                SelectionHistoryMode::Normal => {
  803                    self.push_undo(entry);
  804                    self.redo_stack.clear();
  805                }
  806                SelectionHistoryMode::Undoing => self.push_redo(entry),
  807                SelectionHistoryMode::Redoing => self.push_undo(entry),
  808            }
  809        }
  810    }
  811
  812    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  813        if self
  814            .undo_stack
  815            .back()
  816            .map_or(true, |e| e.selections != entry.selections)
  817        {
  818            self.undo_stack.push_back(entry);
  819            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  820                self.undo_stack.pop_front();
  821            }
  822        }
  823    }
  824
  825    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  826        if self
  827            .redo_stack
  828            .back()
  829            .map_or(true, |e| e.selections != entry.selections)
  830        {
  831            self.redo_stack.push_back(entry);
  832            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  833                self.redo_stack.pop_front();
  834            }
  835        }
  836    }
  837}
  838
  839struct RowHighlight {
  840    index: usize,
  841    range: Range<Anchor>,
  842    color: Hsla,
  843    should_autoscroll: bool,
  844}
  845
  846#[derive(Clone, Debug)]
  847struct AddSelectionsState {
  848    above: bool,
  849    stack: Vec<usize>,
  850}
  851
  852#[derive(Clone)]
  853struct SelectNextState {
  854    query: AhoCorasick,
  855    wordwise: bool,
  856    done: bool,
  857}
  858
  859impl std::fmt::Debug for SelectNextState {
  860    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  861        f.debug_struct(std::any::type_name::<Self>())
  862            .field("wordwise", &self.wordwise)
  863            .field("done", &self.done)
  864            .finish()
  865    }
  866}
  867
  868#[derive(Debug)]
  869struct AutocloseRegion {
  870    selection_id: usize,
  871    range: Range<Anchor>,
  872    pair: BracketPair,
  873}
  874
  875#[derive(Debug)]
  876struct SnippetState {
  877    ranges: Vec<Vec<Range<Anchor>>>,
  878    active_index: usize,
  879    choices: Vec<Option<Vec<String>>>,
  880}
  881
  882#[doc(hidden)]
  883pub struct RenameState {
  884    pub range: Range<Anchor>,
  885    pub old_name: Arc<str>,
  886    pub editor: View<Editor>,
  887    block_id: CustomBlockId,
  888}
  889
  890struct InvalidationStack<T>(Vec<T>);
  891
  892struct RegisteredInlineCompletionProvider {
  893    provider: Arc<dyn InlineCompletionProviderHandle>,
  894    _subscription: Subscription,
  895}
  896
  897enum ContextMenu {
  898    Completions(CompletionsMenu),
  899    CodeActions(CodeActionsMenu),
  900}
  901
  902impl ContextMenu {
  903    fn select_first(
  904        &mut self,
  905        provider: Option<&dyn CompletionProvider>,
  906        cx: &mut ViewContext<Editor>,
  907    ) -> bool {
  908        if self.visible() {
  909            match self {
  910                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  911                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  912            }
  913            true
  914        } else {
  915            false
  916        }
  917    }
  918
  919    fn select_prev(
  920        &mut self,
  921        provider: Option<&dyn CompletionProvider>,
  922        cx: &mut ViewContext<Editor>,
  923    ) -> bool {
  924        if self.visible() {
  925            match self {
  926                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  927                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  928            }
  929            true
  930        } else {
  931            false
  932        }
  933    }
  934
  935    fn select_next(
  936        &mut self,
  937        provider: Option<&dyn CompletionProvider>,
  938        cx: &mut ViewContext<Editor>,
  939    ) -> bool {
  940        if self.visible() {
  941            match self {
  942                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  943                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  944            }
  945            true
  946        } else {
  947            false
  948        }
  949    }
  950
  951    fn select_last(
  952        &mut self,
  953        provider: Option<&dyn CompletionProvider>,
  954        cx: &mut ViewContext<Editor>,
  955    ) -> bool {
  956        if self.visible() {
  957            match self {
  958                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  959                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  960            }
  961            true
  962        } else {
  963            false
  964        }
  965    }
  966
  967    fn visible(&self) -> bool {
  968        match self {
  969            ContextMenu::Completions(menu) => menu.visible(),
  970            ContextMenu::CodeActions(menu) => menu.visible(),
  971        }
  972    }
  973
  974    fn render(
  975        &self,
  976        cursor_position: DisplayPoint,
  977        style: &EditorStyle,
  978        max_height: Pixels,
  979        workspace: Option<WeakView<Workspace>>,
  980        cx: &mut ViewContext<Editor>,
  981    ) -> (ContextMenuOrigin, AnyElement) {
  982        match self {
  983            ContextMenu::Completions(menu) => (
  984                ContextMenuOrigin::EditorPoint(cursor_position),
  985                menu.render(style, max_height, workspace, cx),
  986            ),
  987            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  988        }
  989    }
  990}
  991
  992enum ContextMenuOrigin {
  993    EditorPoint(DisplayPoint),
  994    GutterIndicator(DisplayRow),
  995}
  996
  997#[derive(Clone, Debug)]
  998struct CompletionsMenu {
  999    id: CompletionId,
 1000    sort_completions: bool,
 1001    initial_position: Anchor,
 1002    buffer: Model<Buffer>,
 1003    completions: Arc<RwLock<Box<[Completion]>>>,
 1004    match_candidates: Arc<[StringMatchCandidate]>,
 1005    matches: Arc<[StringMatch]>,
 1006    selected_item: usize,
 1007    scroll_handle: UniformListScrollHandle,
 1008    selected_completion_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
 1009}
 1010
 1011impl CompletionsMenu {
 1012    fn new(
 1013        id: CompletionId,
 1014        sort_completions: bool,
 1015        initial_position: Anchor,
 1016        buffer: Model<Buffer>,
 1017        completions: Box<[Completion]>,
 1018    ) -> Self {
 1019        let match_candidates = completions
 1020            .iter()
 1021            .enumerate()
 1022            .map(|(id, completion)| {
 1023                StringMatchCandidate::new(
 1024                    id,
 1025                    completion.label.text[completion.label.filter_range.clone()].into(),
 1026                )
 1027            })
 1028            .collect();
 1029
 1030        Self {
 1031            id,
 1032            sort_completions,
 1033            initial_position,
 1034            buffer,
 1035            completions: Arc::new(RwLock::new(completions)),
 1036            match_candidates,
 1037            matches: Vec::new().into(),
 1038            selected_item: 0,
 1039            scroll_handle: UniformListScrollHandle::new(),
 1040            selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
 1041        }
 1042    }
 1043
 1044    fn new_snippet_choices(
 1045        id: CompletionId,
 1046        sort_completions: bool,
 1047        choices: &Vec<String>,
 1048        selection: Range<Anchor>,
 1049        buffer: Model<Buffer>,
 1050    ) -> Self {
 1051        let completions = choices
 1052            .iter()
 1053            .map(|choice| Completion {
 1054                old_range: selection.start.text_anchor..selection.end.text_anchor,
 1055                new_text: choice.to_string(),
 1056                label: CodeLabel {
 1057                    text: choice.to_string(),
 1058                    runs: Default::default(),
 1059                    filter_range: Default::default(),
 1060                },
 1061                server_id: LanguageServerId(usize::MAX),
 1062                documentation: None,
 1063                lsp_completion: Default::default(),
 1064                confirm: None,
 1065            })
 1066            .collect();
 1067
 1068        let match_candidates = choices
 1069            .iter()
 1070            .enumerate()
 1071            .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
 1072            .collect();
 1073        let matches = choices
 1074            .iter()
 1075            .enumerate()
 1076            .map(|(id, completion)| StringMatch {
 1077                candidate_id: id,
 1078                score: 1.,
 1079                positions: vec![],
 1080                string: completion.clone(),
 1081            })
 1082            .collect();
 1083        Self {
 1084            id,
 1085            sort_completions,
 1086            initial_position: selection.start,
 1087            buffer,
 1088            completions: Arc::new(RwLock::new(completions)),
 1089            match_candidates,
 1090            matches,
 1091            selected_item: 0,
 1092            scroll_handle: UniformListScrollHandle::new(),
 1093            selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
 1094        }
 1095    }
 1096
 1097    fn suppress_documentation_resolution(mut self) -> Self {
 1098        self.selected_completion_resolve_debounce.take();
 1099        self
 1100    }
 1101
 1102    fn select_first(
 1103        &mut self,
 1104        provider: Option<&dyn CompletionProvider>,
 1105        cx: &mut ViewContext<Editor>,
 1106    ) {
 1107        self.selected_item = 0;
 1108        self.scroll_handle
 1109            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1110        self.resolve_selected_completion(provider, cx);
 1111        cx.notify();
 1112    }
 1113
 1114    fn select_prev(
 1115        &mut self,
 1116        provider: Option<&dyn CompletionProvider>,
 1117        cx: &mut ViewContext<Editor>,
 1118    ) {
 1119        if self.selected_item > 0 {
 1120            self.selected_item -= 1;
 1121        } else {
 1122            self.selected_item = self.matches.len() - 1;
 1123        }
 1124        self.scroll_handle
 1125            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1126        self.resolve_selected_completion(provider, cx);
 1127        cx.notify();
 1128    }
 1129
 1130    fn select_next(
 1131        &mut self,
 1132        provider: Option<&dyn CompletionProvider>,
 1133        cx: &mut ViewContext<Editor>,
 1134    ) {
 1135        if self.selected_item + 1 < self.matches.len() {
 1136            self.selected_item += 1;
 1137        } else {
 1138            self.selected_item = 0;
 1139        }
 1140        self.scroll_handle
 1141            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1142        self.resolve_selected_completion(provider, cx);
 1143        cx.notify();
 1144    }
 1145
 1146    fn select_last(
 1147        &mut self,
 1148        provider: Option<&dyn CompletionProvider>,
 1149        cx: &mut ViewContext<Editor>,
 1150    ) {
 1151        self.selected_item = self.matches.len() - 1;
 1152        self.scroll_handle
 1153            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1154        self.resolve_selected_completion(provider, cx);
 1155        cx.notify();
 1156    }
 1157
 1158    fn resolve_selected_completion(
 1159        &mut self,
 1160        provider: Option<&dyn CompletionProvider>,
 1161        cx: &mut ViewContext<Editor>,
 1162    ) {
 1163        let completion_index = self.matches[self.selected_item].candidate_id;
 1164        let Some(provider) = provider else {
 1165            return;
 1166        };
 1167        let Some(completion_resolve) = self.selected_completion_resolve_debounce.as_ref() else {
 1168            return;
 1169        };
 1170
 1171        let resolve_task = provider.resolve_completions(
 1172            self.buffer.clone(),
 1173            vec![completion_index],
 1174            self.completions.clone(),
 1175            cx,
 1176        );
 1177
 1178        let delay_ms =
 1179            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1180        let delay = Duration::from_millis(delay_ms);
 1181
 1182        completion_resolve.lock().fire_new(delay, cx, |_, cx| {
 1183            cx.spawn(move |this, mut cx| async move {
 1184                if let Some(true) = resolve_task.await.log_err() {
 1185                    this.update(&mut cx, |_, cx| cx.notify()).ok();
 1186                }
 1187            })
 1188        });
 1189    }
 1190
 1191    fn visible(&self) -> bool {
 1192        !self.matches.is_empty()
 1193    }
 1194
 1195    fn render(
 1196        &self,
 1197        style: &EditorStyle,
 1198        max_height: Pixels,
 1199        workspace: Option<WeakView<Workspace>>,
 1200        cx: &mut ViewContext<Editor>,
 1201    ) -> AnyElement {
 1202        let settings = EditorSettings::get_global(cx);
 1203        let show_completion_documentation = settings.show_completion_documentation;
 1204
 1205        let widest_completion_ix = self
 1206            .matches
 1207            .iter()
 1208            .enumerate()
 1209            .max_by_key(|(_, mat)| {
 1210                let completions = self.completions.read();
 1211                let completion = &completions[mat.candidate_id];
 1212                let documentation = &completion.documentation;
 1213
 1214                let mut len = completion.label.text.chars().count();
 1215                if let Some(Documentation::SingleLine(text)) = documentation {
 1216                    if show_completion_documentation {
 1217                        len += text.chars().count();
 1218                    }
 1219                }
 1220
 1221                len
 1222            })
 1223            .map(|(ix, _)| ix);
 1224
 1225        let completions = self.completions.clone();
 1226        let matches = self.matches.clone();
 1227        let selected_item = self.selected_item;
 1228        let style = style.clone();
 1229
 1230        let multiline_docs = if show_completion_documentation {
 1231            let mat = &self.matches[selected_item];
 1232            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1233                Some(Documentation::MultiLinePlainText(text)) => {
 1234                    Some(div().child(SharedString::from(text.clone())))
 1235                }
 1236                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1237                    Some(div().child(render_parsed_markdown(
 1238                        "completions_markdown",
 1239                        parsed,
 1240                        &style,
 1241                        workspace,
 1242                        cx,
 1243                    )))
 1244                }
 1245                _ => None,
 1246            };
 1247            multiline_docs.map(|div| {
 1248                div.id("multiline_docs")
 1249                    .max_h(max_height)
 1250                    .flex_1()
 1251                    .px_1p5()
 1252                    .py_1()
 1253                    .min_w(px(260.))
 1254                    .max_w(px(640.))
 1255                    .w(px(500.))
 1256                    .overflow_y_scroll()
 1257                    .occlude()
 1258            })
 1259        } else {
 1260            None
 1261        };
 1262
 1263        let list = uniform_list(
 1264            cx.view().clone(),
 1265            "completions",
 1266            matches.len(),
 1267            move |_editor, range, cx| {
 1268                let start_ix = range.start;
 1269                let completions_guard = completions.read();
 1270
 1271                matches[range]
 1272                    .iter()
 1273                    .enumerate()
 1274                    .map(|(ix, mat)| {
 1275                        let item_ix = start_ix + ix;
 1276                        let candidate_id = mat.candidate_id;
 1277                        let completion = &completions_guard[candidate_id];
 1278
 1279                        let documentation = if show_completion_documentation {
 1280                            &completion.documentation
 1281                        } else {
 1282                            &None
 1283                        };
 1284
 1285                        let highlights = gpui::combine_highlights(
 1286                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1287                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1288                                |(range, mut highlight)| {
 1289                                    // Ignore font weight for syntax highlighting, as we'll use it
 1290                                    // for fuzzy matches.
 1291                                    highlight.font_weight = None;
 1292
 1293                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1294                                        highlight.strikethrough = Some(StrikethroughStyle {
 1295                                            thickness: 1.0.into(),
 1296                                            ..Default::default()
 1297                                        });
 1298                                        highlight.color = Some(cx.theme().colors().text_muted);
 1299                                    }
 1300
 1301                                    (range, highlight)
 1302                                },
 1303                            ),
 1304                        );
 1305                        let completion_label = StyledText::new(completion.label.text.clone())
 1306                            .with_highlights(&style.text, highlights);
 1307                        let documentation_label =
 1308                            if let Some(Documentation::SingleLine(text)) = documentation {
 1309                                if text.trim().is_empty() {
 1310                                    None
 1311                                } else {
 1312                                    Some(
 1313                                        Label::new(text.clone())
 1314                                            .ml_4()
 1315                                            .size(LabelSize::Small)
 1316                                            .color(Color::Muted),
 1317                                    )
 1318                                }
 1319                            } else {
 1320                                None
 1321                            };
 1322
 1323                        let color_swatch = completion
 1324                            .color()
 1325                            .map(|color| div().size_4().bg(color).rounded_sm());
 1326
 1327                        div().min_w(px(220.)).max_w(px(540.)).child(
 1328                            ListItem::new(mat.candidate_id)
 1329                                .inset(true)
 1330                                .selected(item_ix == selected_item)
 1331                                .on_click(cx.listener(move |editor, _event, cx| {
 1332                                    cx.stop_propagation();
 1333                                    if let Some(task) = editor.confirm_completion(
 1334                                        &ConfirmCompletion {
 1335                                            item_ix: Some(item_ix),
 1336                                        },
 1337                                        cx,
 1338                                    ) {
 1339                                        task.detach_and_log_err(cx)
 1340                                    }
 1341                                }))
 1342                                .start_slot::<Div>(color_swatch)
 1343                                .child(h_flex().overflow_hidden().child(completion_label))
 1344                                .end_slot::<Label>(documentation_label),
 1345                        )
 1346                    })
 1347                    .collect()
 1348            },
 1349        )
 1350        .occlude()
 1351        .max_h(max_height)
 1352        .track_scroll(self.scroll_handle.clone())
 1353        .with_width_from_item(widest_completion_ix)
 1354        .with_sizing_behavior(ListSizingBehavior::Infer);
 1355
 1356        Popover::new()
 1357            .child(list)
 1358            .when_some(multiline_docs, |popover, multiline_docs| {
 1359                popover.aside(multiline_docs)
 1360            })
 1361            .into_any_element()
 1362    }
 1363
 1364    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1365        let mut matches = if let Some(query) = query {
 1366            fuzzy::match_strings(
 1367                &self.match_candidates,
 1368                query,
 1369                query.chars().any(|c| c.is_uppercase()),
 1370                100,
 1371                &Default::default(),
 1372                executor,
 1373            )
 1374            .await
 1375        } else {
 1376            self.match_candidates
 1377                .iter()
 1378                .enumerate()
 1379                .map(|(candidate_id, candidate)| StringMatch {
 1380                    candidate_id,
 1381                    score: Default::default(),
 1382                    positions: Default::default(),
 1383                    string: candidate.string.clone(),
 1384                })
 1385                .collect()
 1386        };
 1387
 1388        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1389        if let Some(query) = query {
 1390            if let Some(query_start) = query.chars().next() {
 1391                matches.retain(|string_match| {
 1392                    split_words(&string_match.string).any(|word| {
 1393                        // Check that the first codepoint of the word as lowercase matches the first
 1394                        // codepoint of the query as lowercase
 1395                        word.chars()
 1396                            .flat_map(|codepoint| codepoint.to_lowercase())
 1397                            .zip(query_start.to_lowercase())
 1398                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1399                    })
 1400                });
 1401            }
 1402        }
 1403
 1404        let completions = self.completions.read();
 1405        if self.sort_completions {
 1406            matches.sort_unstable_by_key(|mat| {
 1407                // We do want to strike a balance here between what the language server tells us
 1408                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1409                // `Creat` and there is a local variable called `CreateComponent`).
 1410                // So what we do is: we bucket all matches into two buckets
 1411                // - Strong matches
 1412                // - Weak matches
 1413                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1414                // and the Weak matches are the rest.
 1415                //
 1416                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1417                // matches, we prefer language-server sort_text first.
 1418                //
 1419                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1420                // Rest of the matches(weak) can be sorted as language-server expects.
 1421
 1422                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1423                enum MatchScore<'a> {
 1424                    Strong {
 1425                        score: Reverse<OrderedFloat<f64>>,
 1426                        sort_text: Option<&'a str>,
 1427                        sort_key: (usize, &'a str),
 1428                    },
 1429                    Weak {
 1430                        sort_text: Option<&'a str>,
 1431                        score: Reverse<OrderedFloat<f64>>,
 1432                        sort_key: (usize, &'a str),
 1433                    },
 1434                }
 1435
 1436                let completion = &completions[mat.candidate_id];
 1437                let sort_key = completion.sort_key();
 1438                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1439                let score = Reverse(OrderedFloat(mat.score));
 1440
 1441                if mat.score >= 0.2 {
 1442                    MatchScore::Strong {
 1443                        score,
 1444                        sort_text,
 1445                        sort_key,
 1446                    }
 1447                } else {
 1448                    MatchScore::Weak {
 1449                        sort_text,
 1450                        score,
 1451                        sort_key,
 1452                    }
 1453                }
 1454            });
 1455        }
 1456
 1457        for mat in &mut matches {
 1458            let completion = &completions[mat.candidate_id];
 1459            mat.string.clone_from(&completion.label.text);
 1460            for position in &mut mat.positions {
 1461                *position += completion.label.filter_range.start;
 1462            }
 1463        }
 1464        drop(completions);
 1465
 1466        self.matches = matches.into();
 1467        self.selected_item = 0;
 1468    }
 1469}
 1470
 1471#[derive(Clone)]
 1472struct AvailableCodeAction {
 1473    excerpt_id: ExcerptId,
 1474    action: CodeAction,
 1475    provider: Arc<dyn CodeActionProvider>,
 1476}
 1477
 1478#[derive(Clone)]
 1479struct CodeActionContents {
 1480    tasks: Option<Arc<ResolvedTasks>>,
 1481    actions: Option<Arc<[AvailableCodeAction]>>,
 1482}
 1483
 1484impl CodeActionContents {
 1485    fn len(&self) -> usize {
 1486        match (&self.tasks, &self.actions) {
 1487            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1488            (Some(tasks), None) => tasks.templates.len(),
 1489            (None, Some(actions)) => actions.len(),
 1490            (None, None) => 0,
 1491        }
 1492    }
 1493
 1494    fn is_empty(&self) -> bool {
 1495        match (&self.tasks, &self.actions) {
 1496            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1497            (Some(tasks), None) => tasks.templates.is_empty(),
 1498            (None, Some(actions)) => actions.is_empty(),
 1499            (None, None) => true,
 1500        }
 1501    }
 1502
 1503    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1504        self.tasks
 1505            .iter()
 1506            .flat_map(|tasks| {
 1507                tasks
 1508                    .templates
 1509                    .iter()
 1510                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1511            })
 1512            .chain(self.actions.iter().flat_map(|actions| {
 1513                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1514                    excerpt_id: available.excerpt_id,
 1515                    action: available.action.clone(),
 1516                    provider: available.provider.clone(),
 1517                })
 1518            }))
 1519    }
 1520    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1521        match (&self.tasks, &self.actions) {
 1522            (Some(tasks), Some(actions)) => {
 1523                if index < tasks.templates.len() {
 1524                    tasks
 1525                        .templates
 1526                        .get(index)
 1527                        .cloned()
 1528                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1529                } else {
 1530                    actions.get(index - tasks.templates.len()).map(|available| {
 1531                        CodeActionsItem::CodeAction {
 1532                            excerpt_id: available.excerpt_id,
 1533                            action: available.action.clone(),
 1534                            provider: available.provider.clone(),
 1535                        }
 1536                    })
 1537                }
 1538            }
 1539            (Some(tasks), None) => tasks
 1540                .templates
 1541                .get(index)
 1542                .cloned()
 1543                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1544            (None, Some(actions)) => {
 1545                actions
 1546                    .get(index)
 1547                    .map(|available| CodeActionsItem::CodeAction {
 1548                        excerpt_id: available.excerpt_id,
 1549                        action: available.action.clone(),
 1550                        provider: available.provider.clone(),
 1551                    })
 1552            }
 1553            (None, None) => None,
 1554        }
 1555    }
 1556}
 1557
 1558#[allow(clippy::large_enum_variant)]
 1559#[derive(Clone)]
 1560enum CodeActionsItem {
 1561    Task(TaskSourceKind, ResolvedTask),
 1562    CodeAction {
 1563        excerpt_id: ExcerptId,
 1564        action: CodeAction,
 1565        provider: Arc<dyn CodeActionProvider>,
 1566    },
 1567}
 1568
 1569impl CodeActionsItem {
 1570    fn as_task(&self) -> Option<&ResolvedTask> {
 1571        let Self::Task(_, task) = self else {
 1572            return None;
 1573        };
 1574        Some(task)
 1575    }
 1576    fn as_code_action(&self) -> Option<&CodeAction> {
 1577        let Self::CodeAction { action, .. } = self else {
 1578            return None;
 1579        };
 1580        Some(action)
 1581    }
 1582    fn label(&self) -> String {
 1583        match self {
 1584            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1585            Self::Task(_, task) => task.resolved_label.clone(),
 1586        }
 1587    }
 1588}
 1589
 1590struct CodeActionsMenu {
 1591    actions: CodeActionContents,
 1592    buffer: Model<Buffer>,
 1593    selected_item: usize,
 1594    scroll_handle: UniformListScrollHandle,
 1595    deployed_from_indicator: Option<DisplayRow>,
 1596}
 1597
 1598impl CodeActionsMenu {
 1599    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1600        self.selected_item = 0;
 1601        self.scroll_handle
 1602            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1603        cx.notify()
 1604    }
 1605
 1606    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1607        if self.selected_item > 0 {
 1608            self.selected_item -= 1;
 1609        } else {
 1610            self.selected_item = self.actions.len() - 1;
 1611        }
 1612        self.scroll_handle
 1613            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1614        cx.notify();
 1615    }
 1616
 1617    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1618        if self.selected_item + 1 < self.actions.len() {
 1619            self.selected_item += 1;
 1620        } else {
 1621            self.selected_item = 0;
 1622        }
 1623        self.scroll_handle
 1624            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1625        cx.notify();
 1626    }
 1627
 1628    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1629        self.selected_item = self.actions.len() - 1;
 1630        self.scroll_handle
 1631            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1632        cx.notify()
 1633    }
 1634
 1635    fn visible(&self) -> bool {
 1636        !self.actions.is_empty()
 1637    }
 1638
 1639    fn render(
 1640        &self,
 1641        cursor_position: DisplayPoint,
 1642        _style: &EditorStyle,
 1643        max_height: Pixels,
 1644        cx: &mut ViewContext<Editor>,
 1645    ) -> (ContextMenuOrigin, AnyElement) {
 1646        let actions = self.actions.clone();
 1647        let selected_item = self.selected_item;
 1648        let element = uniform_list(
 1649            cx.view().clone(),
 1650            "code_actions_menu",
 1651            self.actions.len(),
 1652            move |_this, range, cx| {
 1653                actions
 1654                    .iter()
 1655                    .skip(range.start)
 1656                    .take(range.end - range.start)
 1657                    .enumerate()
 1658                    .map(|(ix, action)| {
 1659                        let item_ix = range.start + ix;
 1660                        let selected = selected_item == item_ix;
 1661                        let colors = cx.theme().colors();
 1662                        div()
 1663                            .px_1()
 1664                            .rounded_md()
 1665                            .text_color(colors.text)
 1666                            .when(selected, |style| {
 1667                                style
 1668                                    .bg(colors.element_active)
 1669                                    .text_color(colors.text_accent)
 1670                            })
 1671                            .hover(|style| {
 1672                                style
 1673                                    .bg(colors.element_hover)
 1674                                    .text_color(colors.text_accent)
 1675                            })
 1676                            .whitespace_nowrap()
 1677                            .when_some(action.as_code_action(), |this, action| {
 1678                                this.on_mouse_down(
 1679                                    MouseButton::Left,
 1680                                    cx.listener(move |editor, _, cx| {
 1681                                        cx.stop_propagation();
 1682                                        if let Some(task) = editor.confirm_code_action(
 1683                                            &ConfirmCodeAction {
 1684                                                item_ix: Some(item_ix),
 1685                                            },
 1686                                            cx,
 1687                                        ) {
 1688                                            task.detach_and_log_err(cx)
 1689                                        }
 1690                                    }),
 1691                                )
 1692                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1693                                .child(SharedString::from(
 1694                                    action.lsp_action.title.replace("\n", ""),
 1695                                ))
 1696                            })
 1697                            .when_some(action.as_task(), |this, task| {
 1698                                this.on_mouse_down(
 1699                                    MouseButton::Left,
 1700                                    cx.listener(move |editor, _, cx| {
 1701                                        cx.stop_propagation();
 1702                                        if let Some(task) = editor.confirm_code_action(
 1703                                            &ConfirmCodeAction {
 1704                                                item_ix: Some(item_ix),
 1705                                            },
 1706                                            cx,
 1707                                        ) {
 1708                                            task.detach_and_log_err(cx)
 1709                                        }
 1710                                    }),
 1711                                )
 1712                                .child(SharedString::from(task.resolved_label.replace("\n", "")))
 1713                            })
 1714                    })
 1715                    .collect()
 1716            },
 1717        )
 1718        .elevation_1(cx)
 1719        .p_1()
 1720        .max_h(max_height)
 1721        .occlude()
 1722        .track_scroll(self.scroll_handle.clone())
 1723        .with_width_from_item(
 1724            self.actions
 1725                .iter()
 1726                .enumerate()
 1727                .max_by_key(|(_, action)| match action {
 1728                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1729                    CodeActionsItem::CodeAction { action, .. } => {
 1730                        action.lsp_action.title.chars().count()
 1731                    }
 1732                })
 1733                .map(|(ix, _)| ix),
 1734        )
 1735        .with_sizing_behavior(ListSizingBehavior::Infer)
 1736        .into_any_element();
 1737
 1738        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1739            ContextMenuOrigin::GutterIndicator(row)
 1740        } else {
 1741            ContextMenuOrigin::EditorPoint(cursor_position)
 1742        };
 1743
 1744        (cursor_position, element)
 1745    }
 1746}
 1747
 1748#[derive(Debug)]
 1749struct ActiveDiagnosticGroup {
 1750    primary_range: Range<Anchor>,
 1751    primary_message: String,
 1752    group_id: usize,
 1753    blocks: HashMap<CustomBlockId, Diagnostic>,
 1754    is_valid: bool,
 1755}
 1756
 1757#[derive(Serialize, Deserialize, Clone, Debug)]
 1758pub struct ClipboardSelection {
 1759    pub len: usize,
 1760    pub is_entire_line: bool,
 1761    pub first_line_indent: u32,
 1762}
 1763
 1764#[derive(Debug)]
 1765pub(crate) struct NavigationData {
 1766    cursor_anchor: Anchor,
 1767    cursor_position: Point,
 1768    scroll_anchor: ScrollAnchor,
 1769    scroll_top_row: u32,
 1770}
 1771
 1772#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1773pub enum GotoDefinitionKind {
 1774    Symbol,
 1775    Declaration,
 1776    Type,
 1777    Implementation,
 1778}
 1779
 1780#[derive(Debug, Clone)]
 1781enum InlayHintRefreshReason {
 1782    Toggle(bool),
 1783    SettingsChange(InlayHintSettings),
 1784    NewLinesShown,
 1785    BufferEdited(HashSet<Arc<Language>>),
 1786    RefreshRequested,
 1787    ExcerptsRemoved(Vec<ExcerptId>),
 1788}
 1789
 1790impl InlayHintRefreshReason {
 1791    fn description(&self) -> &'static str {
 1792        match self {
 1793            Self::Toggle(_) => "toggle",
 1794            Self::SettingsChange(_) => "settings change",
 1795            Self::NewLinesShown => "new lines shown",
 1796            Self::BufferEdited(_) => "buffer edited",
 1797            Self::RefreshRequested => "refresh requested",
 1798            Self::ExcerptsRemoved(_) => "excerpts removed",
 1799        }
 1800    }
 1801}
 1802
 1803pub(crate) struct FocusedBlock {
 1804    id: BlockId,
 1805    focus_handle: WeakFocusHandle,
 1806}
 1807
 1808#[derive(Clone)]
 1809struct JumpData {
 1810    excerpt_id: ExcerptId,
 1811    position: Point,
 1812    anchor: text::Anchor,
 1813    path: Option<project::ProjectPath>,
 1814    line_offset_from_top: u32,
 1815}
 1816
 1817impl Editor {
 1818    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1819        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1820        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1821        Self::new(
 1822            EditorMode::SingleLine { auto_width: false },
 1823            buffer,
 1824            None,
 1825            false,
 1826            cx,
 1827        )
 1828    }
 1829
 1830    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1831        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1832        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1833        Self::new(EditorMode::Full, buffer, None, false, cx)
 1834    }
 1835
 1836    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1837        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1838        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1839        Self::new(
 1840            EditorMode::SingleLine { auto_width: true },
 1841            buffer,
 1842            None,
 1843            false,
 1844            cx,
 1845        )
 1846    }
 1847
 1848    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1849        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1850        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1851        Self::new(
 1852            EditorMode::AutoHeight { max_lines },
 1853            buffer,
 1854            None,
 1855            false,
 1856            cx,
 1857        )
 1858    }
 1859
 1860    pub fn for_buffer(
 1861        buffer: Model<Buffer>,
 1862        project: Option<Model<Project>>,
 1863        cx: &mut ViewContext<Self>,
 1864    ) -> Self {
 1865        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1866        Self::new(EditorMode::Full, buffer, project, false, cx)
 1867    }
 1868
 1869    pub fn for_multibuffer(
 1870        buffer: Model<MultiBuffer>,
 1871        project: Option<Model<Project>>,
 1872        show_excerpt_controls: bool,
 1873        cx: &mut ViewContext<Self>,
 1874    ) -> Self {
 1875        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1876    }
 1877
 1878    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1879        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1880        let mut clone = Self::new(
 1881            self.mode,
 1882            self.buffer.clone(),
 1883            self.project.clone(),
 1884            show_excerpt_controls,
 1885            cx,
 1886        );
 1887        self.display_map.update(cx, |display_map, cx| {
 1888            let snapshot = display_map.snapshot(cx);
 1889            clone.display_map.update(cx, |display_map, cx| {
 1890                display_map.set_state(&snapshot, cx);
 1891            });
 1892        });
 1893        clone.selections.clone_state(&self.selections);
 1894        clone.scroll_manager.clone_state(&self.scroll_manager);
 1895        clone.searchable = self.searchable;
 1896        clone
 1897    }
 1898
 1899    pub fn new(
 1900        mode: EditorMode,
 1901        buffer: Model<MultiBuffer>,
 1902        project: Option<Model<Project>>,
 1903        show_excerpt_controls: bool,
 1904        cx: &mut ViewContext<Self>,
 1905    ) -> Self {
 1906        let style = cx.text_style();
 1907        let font_size = style.font_size.to_pixels(cx.rem_size());
 1908        let editor = cx.view().downgrade();
 1909        let fold_placeholder = FoldPlaceholder {
 1910            constrain_width: true,
 1911            render: Arc::new(move |fold_id, fold_range, cx| {
 1912                let editor = editor.clone();
 1913                div()
 1914                    .id(fold_id)
 1915                    .bg(cx.theme().colors().ghost_element_background)
 1916                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1917                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1918                    .rounded_sm()
 1919                    .size_full()
 1920                    .cursor_pointer()
 1921                    .child("")
 1922                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1923                    .on_click(move |_, cx| {
 1924                        editor
 1925                            .update(cx, |editor, cx| {
 1926                                editor.unfold_ranges(
 1927                                    &[fold_range.start..fold_range.end],
 1928                                    true,
 1929                                    false,
 1930                                    cx,
 1931                                );
 1932                                cx.stop_propagation();
 1933                            })
 1934                            .ok();
 1935                    })
 1936                    .into_any()
 1937            }),
 1938            merge_adjacent: true,
 1939            ..Default::default()
 1940        };
 1941        let display_map = cx.new_model(|cx| {
 1942            DisplayMap::new(
 1943                buffer.clone(),
 1944                style.font(),
 1945                font_size,
 1946                None,
 1947                show_excerpt_controls,
 1948                FILE_HEADER_HEIGHT,
 1949                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1950                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1951                fold_placeholder,
 1952                cx,
 1953            )
 1954        });
 1955
 1956        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1957
 1958        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1959
 1960        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1961            .then(|| language_settings::SoftWrap::None);
 1962
 1963        let mut project_subscriptions = Vec::new();
 1964        if mode == EditorMode::Full {
 1965            if let Some(project) = project.as_ref() {
 1966                if buffer.read(cx).is_singleton() {
 1967                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1968                        cx.emit(EditorEvent::TitleChanged);
 1969                    }));
 1970                }
 1971                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1972                    if let project::Event::RefreshInlayHints = event {
 1973                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1974                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1975                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1976                            let focus_handle = editor.focus_handle(cx);
 1977                            if focus_handle.is_focused(cx) {
 1978                                let snapshot = buffer.read(cx).snapshot();
 1979                                for (range, snippet) in snippet_edits {
 1980                                    let editor_range =
 1981                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1982                                    editor
 1983                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1984                                        .ok();
 1985                                }
 1986                            }
 1987                        }
 1988                    }
 1989                }));
 1990                if let Some(task_inventory) = project
 1991                    .read(cx)
 1992                    .task_store()
 1993                    .read(cx)
 1994                    .task_inventory()
 1995                    .cloned()
 1996                {
 1997                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1998                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1999                    }));
 2000                }
 2001            }
 2002        }
 2003
 2004        let inlay_hint_settings = inlay_hint_settings(
 2005            selections.newest_anchor().head(),
 2006            &buffer.read(cx).snapshot(cx),
 2007            cx,
 2008        );
 2009        let focus_handle = cx.focus_handle();
 2010        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 2011        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 2012            .detach();
 2013        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 2014            .detach();
 2015        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 2016
 2017        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 2018            Some(false)
 2019        } else {
 2020            None
 2021        };
 2022
 2023        let mut code_action_providers = Vec::new();
 2024        if let Some(project) = project.clone() {
 2025            code_action_providers.push(Arc::new(project) as Arc<_>);
 2026        }
 2027
 2028        let mut this = Self {
 2029            focus_handle,
 2030            show_cursor_when_unfocused: false,
 2031            last_focused_descendant: None,
 2032            buffer: buffer.clone(),
 2033            display_map: display_map.clone(),
 2034            selections,
 2035            scroll_manager: ScrollManager::new(cx),
 2036            columnar_selection_tail: None,
 2037            add_selections_state: None,
 2038            select_next_state: None,
 2039            select_prev_state: None,
 2040            selection_history: Default::default(),
 2041            autoclose_regions: Default::default(),
 2042            snippet_stack: Default::default(),
 2043            select_larger_syntax_node_stack: Vec::new(),
 2044            ime_transaction: Default::default(),
 2045            active_diagnostics: None,
 2046            soft_wrap_mode_override,
 2047            completion_provider: project.clone().map(|project| Box::new(project) as _),
 2048            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 2049            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 2050            project,
 2051            blink_manager: blink_manager.clone(),
 2052            show_local_selections: true,
 2053            mode,
 2054            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2055            show_gutter: mode == EditorMode::Full,
 2056            show_line_numbers: None,
 2057            use_relative_line_numbers: None,
 2058            show_git_diff_gutter: None,
 2059            show_code_actions: None,
 2060            show_runnables: None,
 2061            show_wrap_guides: None,
 2062            show_indent_guides,
 2063            placeholder_text: None,
 2064            highlight_order: 0,
 2065            highlighted_rows: HashMap::default(),
 2066            background_highlights: Default::default(),
 2067            gutter_highlights: TreeMap::default(),
 2068            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2069            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2070            nav_history: None,
 2071            context_menu: RwLock::new(None),
 2072            mouse_context_menu: None,
 2073            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2074            completion_tasks: Default::default(),
 2075            signature_help_state: SignatureHelpState::default(),
 2076            auto_signature_help: None,
 2077            find_all_references_task_sources: Vec::new(),
 2078            next_completion_id: 0,
 2079            next_inlay_id: 0,
 2080            code_action_providers,
 2081            available_code_actions: Default::default(),
 2082            code_actions_task: Default::default(),
 2083            document_highlights_task: Default::default(),
 2084            linked_editing_range_task: Default::default(),
 2085            pending_rename: Default::default(),
 2086            searchable: true,
 2087            cursor_shape: EditorSettings::get_global(cx)
 2088                .cursor_shape
 2089                .unwrap_or_default(),
 2090            current_line_highlight: None,
 2091            autoindent_mode: Some(AutoindentMode::EachLine),
 2092            collapse_matches: false,
 2093            workspace: None,
 2094            input_enabled: true,
 2095            use_modal_editing: mode == EditorMode::Full,
 2096            read_only: false,
 2097            use_autoclose: true,
 2098            use_auto_surround: true,
 2099            auto_replace_emoji_shortcode: false,
 2100            leader_peer_id: None,
 2101            remote_id: None,
 2102            hover_state: Default::default(),
 2103            hovered_link_state: Default::default(),
 2104            inline_completion_provider: None,
 2105            active_inline_completion: None,
 2106            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2107            expanded_hunks: ExpandedHunks::default(),
 2108            gutter_hovered: false,
 2109            pixel_position_of_newest_cursor: None,
 2110            last_bounds: None,
 2111            expect_bounds_change: None,
 2112            gutter_dimensions: GutterDimensions::default(),
 2113            style: None,
 2114            show_cursor_names: false,
 2115            hovered_cursors: Default::default(),
 2116            next_editor_action_id: EditorActionId::default(),
 2117            editor_actions: Rc::default(),
 2118            show_inline_completions_override: None,
 2119            enable_inline_completions: true,
 2120            custom_context_menu: None,
 2121            show_git_blame_gutter: false,
 2122            show_git_blame_inline: false,
 2123            show_selection_menu: None,
 2124            show_git_blame_inline_delay_task: None,
 2125            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2126            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2127                .session
 2128                .restore_unsaved_buffers,
 2129            blame: None,
 2130            blame_subscription: None,
 2131            tasks: Default::default(),
 2132            _subscriptions: vec![
 2133                cx.observe(&buffer, Self::on_buffer_changed),
 2134                cx.subscribe(&buffer, Self::on_buffer_event),
 2135                cx.observe(&display_map, Self::on_display_map_changed),
 2136                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2137                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2138                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2139                cx.observe_window_activation(|editor, cx| {
 2140                    let active = cx.is_window_active();
 2141                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2142                        if active {
 2143                            blink_manager.enable(cx);
 2144                        } else {
 2145                            blink_manager.disable(cx);
 2146                        }
 2147                    });
 2148                }),
 2149            ],
 2150            tasks_update_task: None,
 2151            linked_edit_ranges: Default::default(),
 2152            previous_search_ranges: None,
 2153            breadcrumb_header: None,
 2154            focused_block: None,
 2155            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2156            addons: HashMap::default(),
 2157            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2158            text_style_refinement: None,
 2159        };
 2160        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2161        this._subscriptions.extend(project_subscriptions);
 2162
 2163        this.end_selection(cx);
 2164        this.scroll_manager.show_scrollbar(cx);
 2165
 2166        if mode == EditorMode::Full {
 2167            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2168            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2169
 2170            if this.git_blame_inline_enabled {
 2171                this.git_blame_inline_enabled = true;
 2172                this.start_git_blame_inline(false, cx);
 2173            }
 2174        }
 2175
 2176        this.report_editor_event("open", None, cx);
 2177        this
 2178    }
 2179
 2180    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2181        self.mouse_context_menu
 2182            .as_ref()
 2183            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2184    }
 2185
 2186    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2187        let mut key_context = KeyContext::new_with_defaults();
 2188        key_context.add("Editor");
 2189        let mode = match self.mode {
 2190            EditorMode::SingleLine { .. } => "single_line",
 2191            EditorMode::AutoHeight { .. } => "auto_height",
 2192            EditorMode::Full => "full",
 2193        };
 2194
 2195        if EditorSettings::jupyter_enabled(cx) {
 2196            key_context.add("jupyter");
 2197        }
 2198
 2199        key_context.set("mode", mode);
 2200        if self.pending_rename.is_some() {
 2201            key_context.add("renaming");
 2202        }
 2203        if self.context_menu_visible() {
 2204            match self.context_menu.read().as_ref() {
 2205                Some(ContextMenu::Completions(_)) => {
 2206                    key_context.add("menu");
 2207                    key_context.add("showing_completions")
 2208                }
 2209                Some(ContextMenu::CodeActions(_)) => {
 2210                    key_context.add("menu");
 2211                    key_context.add("showing_code_actions")
 2212                }
 2213                None => {}
 2214            }
 2215        }
 2216
 2217        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2218        if !self.focus_handle(cx).contains_focused(cx)
 2219            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2220        {
 2221            for addon in self.addons.values() {
 2222                addon.extend_key_context(&mut key_context, cx)
 2223            }
 2224        }
 2225
 2226        if let Some(extension) = self
 2227            .buffer
 2228            .read(cx)
 2229            .as_singleton()
 2230            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2231        {
 2232            key_context.set("extension", extension.to_string());
 2233        }
 2234
 2235        if self.has_active_inline_completion(cx) {
 2236            key_context.add("copilot_suggestion");
 2237            key_context.add("inline_completion");
 2238        }
 2239
 2240        key_context
 2241    }
 2242
 2243    pub fn new_file(
 2244        workspace: &mut Workspace,
 2245        _: &workspace::NewFile,
 2246        cx: &mut ViewContext<Workspace>,
 2247    ) {
 2248        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2249            "Failed to create buffer",
 2250            cx,
 2251            |e, _| match e.error_code() {
 2252                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2253                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2254                e.error_tag("required").unwrap_or("the latest version")
 2255            )),
 2256                _ => None,
 2257            },
 2258        );
 2259    }
 2260
 2261    pub fn new_in_workspace(
 2262        workspace: &mut Workspace,
 2263        cx: &mut ViewContext<Workspace>,
 2264    ) -> Task<Result<View<Editor>>> {
 2265        let project = workspace.project().clone();
 2266        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2267
 2268        cx.spawn(|workspace, mut cx| async move {
 2269            let buffer = create.await?;
 2270            workspace.update(&mut cx, |workspace, cx| {
 2271                let editor =
 2272                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2273                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2274                editor
 2275            })
 2276        })
 2277    }
 2278
 2279    fn new_file_vertical(
 2280        workspace: &mut Workspace,
 2281        _: &workspace::NewFileSplitVertical,
 2282        cx: &mut ViewContext<Workspace>,
 2283    ) {
 2284        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2285    }
 2286
 2287    fn new_file_horizontal(
 2288        workspace: &mut Workspace,
 2289        _: &workspace::NewFileSplitHorizontal,
 2290        cx: &mut ViewContext<Workspace>,
 2291    ) {
 2292        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2293    }
 2294
 2295    fn new_file_in_direction(
 2296        workspace: &mut Workspace,
 2297        direction: SplitDirection,
 2298        cx: &mut ViewContext<Workspace>,
 2299    ) {
 2300        let project = workspace.project().clone();
 2301        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2302
 2303        cx.spawn(|workspace, mut cx| async move {
 2304            let buffer = create.await?;
 2305            workspace.update(&mut cx, move |workspace, cx| {
 2306                workspace.split_item(
 2307                    direction,
 2308                    Box::new(
 2309                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2310                    ),
 2311                    cx,
 2312                )
 2313            })?;
 2314            anyhow::Ok(())
 2315        })
 2316        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2317            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2318                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2319                e.error_tag("required").unwrap_or("the latest version")
 2320            )),
 2321            _ => None,
 2322        });
 2323    }
 2324
 2325    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2326        self.leader_peer_id
 2327    }
 2328
 2329    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2330        &self.buffer
 2331    }
 2332
 2333    pub fn workspace(&self) -> Option<View<Workspace>> {
 2334        self.workspace.as_ref()?.0.upgrade()
 2335    }
 2336
 2337    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2338        self.buffer().read(cx).title(cx)
 2339    }
 2340
 2341    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2342        let git_blame_gutter_max_author_length = self
 2343            .render_git_blame_gutter(cx)
 2344            .then(|| {
 2345                if let Some(blame) = self.blame.as_ref() {
 2346                    let max_author_length =
 2347                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2348                    Some(max_author_length)
 2349                } else {
 2350                    None
 2351                }
 2352            })
 2353            .flatten();
 2354
 2355        EditorSnapshot {
 2356            mode: self.mode,
 2357            show_gutter: self.show_gutter,
 2358            show_line_numbers: self.show_line_numbers,
 2359            show_git_diff_gutter: self.show_git_diff_gutter,
 2360            show_code_actions: self.show_code_actions,
 2361            show_runnables: self.show_runnables,
 2362            git_blame_gutter_max_author_length,
 2363            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2364            scroll_anchor: self.scroll_manager.anchor(),
 2365            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2366            placeholder_text: self.placeholder_text.clone(),
 2367            is_focused: self.focus_handle.is_focused(cx),
 2368            current_line_highlight: self
 2369                .current_line_highlight
 2370                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2371            gutter_hovered: self.gutter_hovered,
 2372        }
 2373    }
 2374
 2375    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2376        self.buffer.read(cx).language_at(point, cx)
 2377    }
 2378
 2379    pub fn file_at<T: ToOffset>(
 2380        &self,
 2381        point: T,
 2382        cx: &AppContext,
 2383    ) -> Option<Arc<dyn language::File>> {
 2384        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2385    }
 2386
 2387    pub fn active_excerpt(
 2388        &self,
 2389        cx: &AppContext,
 2390    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2391        self.buffer
 2392            .read(cx)
 2393            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2394    }
 2395
 2396    pub fn mode(&self) -> EditorMode {
 2397        self.mode
 2398    }
 2399
 2400    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2401        self.collaboration_hub.as_deref()
 2402    }
 2403
 2404    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2405        self.collaboration_hub = Some(hub);
 2406    }
 2407
 2408    pub fn set_custom_context_menu(
 2409        &mut self,
 2410        f: impl 'static
 2411            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2412    ) {
 2413        self.custom_context_menu = Some(Box::new(f))
 2414    }
 2415
 2416    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2417        self.completion_provider = provider;
 2418    }
 2419
 2420    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2421        self.semantics_provider.clone()
 2422    }
 2423
 2424    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2425        self.semantics_provider = provider;
 2426    }
 2427
 2428    pub fn set_inline_completion_provider<T>(
 2429        &mut self,
 2430        provider: Option<Model<T>>,
 2431        cx: &mut ViewContext<Self>,
 2432    ) where
 2433        T: InlineCompletionProvider,
 2434    {
 2435        self.inline_completion_provider =
 2436            provider.map(|provider| RegisteredInlineCompletionProvider {
 2437                _subscription: cx.observe(&provider, |this, _, cx| {
 2438                    if this.focus_handle.is_focused(cx) {
 2439                        this.update_visible_inline_completion(cx);
 2440                    }
 2441                }),
 2442                provider: Arc::new(provider),
 2443            });
 2444        self.refresh_inline_completion(false, false, cx);
 2445    }
 2446
 2447    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2448        self.placeholder_text.as_deref()
 2449    }
 2450
 2451    pub fn set_placeholder_text(
 2452        &mut self,
 2453        placeholder_text: impl Into<Arc<str>>,
 2454        cx: &mut ViewContext<Self>,
 2455    ) {
 2456        let placeholder_text = Some(placeholder_text.into());
 2457        if self.placeholder_text != placeholder_text {
 2458            self.placeholder_text = placeholder_text;
 2459            cx.notify();
 2460        }
 2461    }
 2462
 2463    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2464        self.cursor_shape = cursor_shape;
 2465
 2466        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2467        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2468
 2469        cx.notify();
 2470    }
 2471
 2472    pub fn set_current_line_highlight(
 2473        &mut self,
 2474        current_line_highlight: Option<CurrentLineHighlight>,
 2475    ) {
 2476        self.current_line_highlight = current_line_highlight;
 2477    }
 2478
 2479    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2480        self.collapse_matches = collapse_matches;
 2481    }
 2482
 2483    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2484        if self.collapse_matches {
 2485            return range.start..range.start;
 2486        }
 2487        range.clone()
 2488    }
 2489
 2490    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2491        if self.display_map.read(cx).clip_at_line_ends != clip {
 2492            self.display_map
 2493                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2494        }
 2495    }
 2496
 2497    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2498        self.input_enabled = input_enabled;
 2499    }
 2500
 2501    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2502        self.enable_inline_completions = enabled;
 2503    }
 2504
 2505    pub fn set_autoindent(&mut self, autoindent: bool) {
 2506        if autoindent {
 2507            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2508        } else {
 2509            self.autoindent_mode = None;
 2510        }
 2511    }
 2512
 2513    pub fn read_only(&self, cx: &AppContext) -> bool {
 2514        self.read_only || self.buffer.read(cx).read_only()
 2515    }
 2516
 2517    pub fn set_read_only(&mut self, read_only: bool) {
 2518        self.read_only = read_only;
 2519    }
 2520
 2521    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2522        self.use_autoclose = autoclose;
 2523    }
 2524
 2525    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2526        self.use_auto_surround = auto_surround;
 2527    }
 2528
 2529    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2530        self.auto_replace_emoji_shortcode = auto_replace;
 2531    }
 2532
 2533    pub fn toggle_inline_completions(
 2534        &mut self,
 2535        _: &ToggleInlineCompletions,
 2536        cx: &mut ViewContext<Self>,
 2537    ) {
 2538        if self.show_inline_completions_override.is_some() {
 2539            self.set_show_inline_completions(None, cx);
 2540        } else {
 2541            let cursor = self.selections.newest_anchor().head();
 2542            if let Some((buffer, cursor_buffer_position)) =
 2543                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2544            {
 2545                let show_inline_completions =
 2546                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2547                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2548            }
 2549        }
 2550    }
 2551
 2552    pub fn set_show_inline_completions(
 2553        &mut self,
 2554        show_inline_completions: Option<bool>,
 2555        cx: &mut ViewContext<Self>,
 2556    ) {
 2557        self.show_inline_completions_override = show_inline_completions;
 2558        self.refresh_inline_completion(false, true, cx);
 2559    }
 2560
 2561    fn should_show_inline_completions(
 2562        &self,
 2563        buffer: &Model<Buffer>,
 2564        buffer_position: language::Anchor,
 2565        cx: &AppContext,
 2566    ) -> bool {
 2567        if !self.snippet_stack.is_empty() {
 2568            return false;
 2569        }
 2570
 2571        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2572            return false;
 2573        }
 2574
 2575        if let Some(provider) = self.inline_completion_provider() {
 2576            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2577                show_inline_completions
 2578            } else {
 2579                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2580            }
 2581        } else {
 2582            false
 2583        }
 2584    }
 2585
 2586    fn inline_completions_disabled_in_scope(
 2587        &self,
 2588        buffer: &Model<Buffer>,
 2589        buffer_position: language::Anchor,
 2590        cx: &AppContext,
 2591    ) -> bool {
 2592        let snapshot = buffer.read(cx).snapshot();
 2593        let settings = snapshot.settings_at(buffer_position, cx);
 2594
 2595        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2596            return false;
 2597        };
 2598
 2599        scope.override_name().map_or(false, |scope_name| {
 2600            settings
 2601                .inline_completions_disabled_in
 2602                .iter()
 2603                .any(|s| s == scope_name)
 2604        })
 2605    }
 2606
 2607    pub fn set_use_modal_editing(&mut self, to: bool) {
 2608        self.use_modal_editing = to;
 2609    }
 2610
 2611    pub fn use_modal_editing(&self) -> bool {
 2612        self.use_modal_editing
 2613    }
 2614
 2615    fn selections_did_change(
 2616        &mut self,
 2617        local: bool,
 2618        old_cursor_position: &Anchor,
 2619        show_completions: bool,
 2620        cx: &mut ViewContext<Self>,
 2621    ) {
 2622        cx.invalidate_character_coordinates();
 2623
 2624        // Copy selections to primary selection buffer
 2625        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2626        if local {
 2627            let selections = self.selections.all::<usize>(cx);
 2628            let buffer_handle = self.buffer.read(cx).read(cx);
 2629
 2630            let mut text = String::new();
 2631            for (index, selection) in selections.iter().enumerate() {
 2632                let text_for_selection = buffer_handle
 2633                    .text_for_range(selection.start..selection.end)
 2634                    .collect::<String>();
 2635
 2636                text.push_str(&text_for_selection);
 2637                if index != selections.len() - 1 {
 2638                    text.push('\n');
 2639                }
 2640            }
 2641
 2642            if !text.is_empty() {
 2643                cx.write_to_primary(ClipboardItem::new_string(text));
 2644            }
 2645        }
 2646
 2647        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2648            self.buffer.update(cx, |buffer, cx| {
 2649                buffer.set_active_selections(
 2650                    &self.selections.disjoint_anchors(),
 2651                    self.selections.line_mode,
 2652                    self.cursor_shape,
 2653                    cx,
 2654                )
 2655            });
 2656        }
 2657        let display_map = self
 2658            .display_map
 2659            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2660        let buffer = &display_map.buffer_snapshot;
 2661        self.add_selections_state = None;
 2662        self.select_next_state = None;
 2663        self.select_prev_state = None;
 2664        self.select_larger_syntax_node_stack.clear();
 2665        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2666        self.snippet_stack
 2667            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2668        self.take_rename(false, cx);
 2669
 2670        let new_cursor_position = self.selections.newest_anchor().head();
 2671
 2672        self.push_to_nav_history(
 2673            *old_cursor_position,
 2674            Some(new_cursor_position.to_point(buffer)),
 2675            cx,
 2676        );
 2677
 2678        if local {
 2679            let new_cursor_position = self.selections.newest_anchor().head();
 2680            let mut context_menu = self.context_menu.write();
 2681            let completion_menu = match context_menu.as_ref() {
 2682                Some(ContextMenu::Completions(menu)) => Some(menu),
 2683
 2684                _ => {
 2685                    *context_menu = None;
 2686                    None
 2687                }
 2688            };
 2689
 2690            if let Some(completion_menu) = completion_menu {
 2691                let cursor_position = new_cursor_position.to_offset(buffer);
 2692                let (word_range, kind) =
 2693                    buffer.surrounding_word(completion_menu.initial_position, true);
 2694                if kind == Some(CharKind::Word)
 2695                    && word_range.to_inclusive().contains(&cursor_position)
 2696                {
 2697                    let mut completion_menu = completion_menu.clone();
 2698                    drop(context_menu);
 2699
 2700                    let query = Self::completion_query(buffer, cursor_position);
 2701                    cx.spawn(move |this, mut cx| async move {
 2702                        completion_menu
 2703                            .filter(query.as_deref(), cx.background_executor().clone())
 2704                            .await;
 2705
 2706                        this.update(&mut cx, |this, cx| {
 2707                            let mut context_menu = this.context_menu.write();
 2708                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2709                                return;
 2710                            };
 2711
 2712                            if menu.id > completion_menu.id {
 2713                                return;
 2714                            }
 2715
 2716                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2717                            drop(context_menu);
 2718                            cx.notify();
 2719                        })
 2720                    })
 2721                    .detach();
 2722
 2723                    if show_completions {
 2724                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2725                    }
 2726                } else {
 2727                    drop(context_menu);
 2728                    self.hide_context_menu(cx);
 2729                }
 2730            } else {
 2731                drop(context_menu);
 2732            }
 2733
 2734            hide_hover(self, cx);
 2735
 2736            if old_cursor_position.to_display_point(&display_map).row()
 2737                != new_cursor_position.to_display_point(&display_map).row()
 2738            {
 2739                self.available_code_actions.take();
 2740            }
 2741            self.refresh_code_actions(cx);
 2742            self.refresh_document_highlights(cx);
 2743            refresh_matching_bracket_highlights(self, cx);
 2744            self.discard_inline_completion(false, cx);
 2745            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2746            if self.git_blame_inline_enabled {
 2747                self.start_inline_blame_timer(cx);
 2748            }
 2749        }
 2750
 2751        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2752        cx.emit(EditorEvent::SelectionsChanged { local });
 2753
 2754        if self.selections.disjoint_anchors().len() == 1 {
 2755            cx.emit(SearchEvent::ActiveMatchChanged)
 2756        }
 2757        cx.notify();
 2758    }
 2759
 2760    pub fn change_selections<R>(
 2761        &mut self,
 2762        autoscroll: Option<Autoscroll>,
 2763        cx: &mut ViewContext<Self>,
 2764        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2765    ) -> R {
 2766        self.change_selections_inner(autoscroll, true, cx, change)
 2767    }
 2768
 2769    pub fn change_selections_inner<R>(
 2770        &mut self,
 2771        autoscroll: Option<Autoscroll>,
 2772        request_completions: bool,
 2773        cx: &mut ViewContext<Self>,
 2774        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2775    ) -> R {
 2776        let old_cursor_position = self.selections.newest_anchor().head();
 2777        self.push_to_selection_history();
 2778
 2779        let (changed, result) = self.selections.change_with(cx, change);
 2780
 2781        if changed {
 2782            if let Some(autoscroll) = autoscroll {
 2783                self.request_autoscroll(autoscroll, cx);
 2784            }
 2785            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2786
 2787            if self.should_open_signature_help_automatically(
 2788                &old_cursor_position,
 2789                self.signature_help_state.backspace_pressed(),
 2790                cx,
 2791            ) {
 2792                self.show_signature_help(&ShowSignatureHelp, cx);
 2793            }
 2794            self.signature_help_state.set_backspace_pressed(false);
 2795        }
 2796
 2797        result
 2798    }
 2799
 2800    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2801    where
 2802        I: IntoIterator<Item = (Range<S>, T)>,
 2803        S: ToOffset,
 2804        T: Into<Arc<str>>,
 2805    {
 2806        if self.read_only(cx) {
 2807            return;
 2808        }
 2809
 2810        self.buffer
 2811            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2812    }
 2813
 2814    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2815    where
 2816        I: IntoIterator<Item = (Range<S>, T)>,
 2817        S: ToOffset,
 2818        T: Into<Arc<str>>,
 2819    {
 2820        if self.read_only(cx) {
 2821            return;
 2822        }
 2823
 2824        self.buffer.update(cx, |buffer, cx| {
 2825            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2826        });
 2827    }
 2828
 2829    pub fn edit_with_block_indent<I, S, T>(
 2830        &mut self,
 2831        edits: I,
 2832        original_indent_columns: Vec<u32>,
 2833        cx: &mut ViewContext<Self>,
 2834    ) where
 2835        I: IntoIterator<Item = (Range<S>, T)>,
 2836        S: ToOffset,
 2837        T: Into<Arc<str>>,
 2838    {
 2839        if self.read_only(cx) {
 2840            return;
 2841        }
 2842
 2843        self.buffer.update(cx, |buffer, cx| {
 2844            buffer.edit(
 2845                edits,
 2846                Some(AutoindentMode::Block {
 2847                    original_indent_columns,
 2848                }),
 2849                cx,
 2850            )
 2851        });
 2852    }
 2853
 2854    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2855        self.hide_context_menu(cx);
 2856
 2857        match phase {
 2858            SelectPhase::Begin {
 2859                position,
 2860                add,
 2861                click_count,
 2862            } => self.begin_selection(position, add, click_count, cx),
 2863            SelectPhase::BeginColumnar {
 2864                position,
 2865                goal_column,
 2866                reset,
 2867            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2868            SelectPhase::Extend {
 2869                position,
 2870                click_count,
 2871            } => self.extend_selection(position, click_count, cx),
 2872            SelectPhase::Update {
 2873                position,
 2874                goal_column,
 2875                scroll_delta,
 2876            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2877            SelectPhase::End => self.end_selection(cx),
 2878        }
 2879    }
 2880
 2881    fn extend_selection(
 2882        &mut self,
 2883        position: DisplayPoint,
 2884        click_count: usize,
 2885        cx: &mut ViewContext<Self>,
 2886    ) {
 2887        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2888        let tail = self.selections.newest::<usize>(cx).tail();
 2889        self.begin_selection(position, false, click_count, cx);
 2890
 2891        let position = position.to_offset(&display_map, Bias::Left);
 2892        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2893
 2894        let mut pending_selection = self
 2895            .selections
 2896            .pending_anchor()
 2897            .expect("extend_selection not called with pending selection");
 2898        if position >= tail {
 2899            pending_selection.start = tail_anchor;
 2900        } else {
 2901            pending_selection.end = tail_anchor;
 2902            pending_selection.reversed = true;
 2903        }
 2904
 2905        let mut pending_mode = self.selections.pending_mode().unwrap();
 2906        match &mut pending_mode {
 2907            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2908            _ => {}
 2909        }
 2910
 2911        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2912            s.set_pending(pending_selection, pending_mode)
 2913        });
 2914    }
 2915
 2916    fn begin_selection(
 2917        &mut self,
 2918        position: DisplayPoint,
 2919        add: bool,
 2920        click_count: usize,
 2921        cx: &mut ViewContext<Self>,
 2922    ) {
 2923        if !self.focus_handle.is_focused(cx) {
 2924            self.last_focused_descendant = None;
 2925            cx.focus(&self.focus_handle);
 2926        }
 2927
 2928        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2929        let buffer = &display_map.buffer_snapshot;
 2930        let newest_selection = self.selections.newest_anchor().clone();
 2931        let position = display_map.clip_point(position, Bias::Left);
 2932
 2933        let start;
 2934        let end;
 2935        let mode;
 2936        let mut auto_scroll;
 2937        match click_count {
 2938            1 => {
 2939                start = buffer.anchor_before(position.to_point(&display_map));
 2940                end = start;
 2941                mode = SelectMode::Character;
 2942                auto_scroll = true;
 2943            }
 2944            2 => {
 2945                let range = movement::surrounding_word(&display_map, position);
 2946                start = buffer.anchor_before(range.start.to_point(&display_map));
 2947                end = buffer.anchor_before(range.end.to_point(&display_map));
 2948                mode = SelectMode::Word(start..end);
 2949                auto_scroll = true;
 2950            }
 2951            3 => {
 2952                let position = display_map
 2953                    .clip_point(position, Bias::Left)
 2954                    .to_point(&display_map);
 2955                let line_start = display_map.prev_line_boundary(position).0;
 2956                let next_line_start = buffer.clip_point(
 2957                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2958                    Bias::Left,
 2959                );
 2960                start = buffer.anchor_before(line_start);
 2961                end = buffer.anchor_before(next_line_start);
 2962                mode = SelectMode::Line(start..end);
 2963                auto_scroll = true;
 2964            }
 2965            _ => {
 2966                start = buffer.anchor_before(0);
 2967                end = buffer.anchor_before(buffer.len());
 2968                mode = SelectMode::All;
 2969                auto_scroll = false;
 2970            }
 2971        }
 2972        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2973
 2974        let point_to_delete: Option<usize> = {
 2975            let selected_points: Vec<Selection<Point>> =
 2976                self.selections.disjoint_in_range(start..end, cx);
 2977
 2978            if !add || click_count > 1 {
 2979                None
 2980            } else if !selected_points.is_empty() {
 2981                Some(selected_points[0].id)
 2982            } else {
 2983                let clicked_point_already_selected =
 2984                    self.selections.disjoint.iter().find(|selection| {
 2985                        selection.start.to_point(buffer) == start.to_point(buffer)
 2986                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2987                    });
 2988
 2989                clicked_point_already_selected.map(|selection| selection.id)
 2990            }
 2991        };
 2992
 2993        let selections_count = self.selections.count();
 2994
 2995        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2996            if let Some(point_to_delete) = point_to_delete {
 2997                s.delete(point_to_delete);
 2998
 2999                if selections_count == 1 {
 3000                    s.set_pending_anchor_range(start..end, mode);
 3001                }
 3002            } else {
 3003                if !add {
 3004                    s.clear_disjoint();
 3005                } else if click_count > 1 {
 3006                    s.delete(newest_selection.id)
 3007                }
 3008
 3009                s.set_pending_anchor_range(start..end, mode);
 3010            }
 3011        });
 3012    }
 3013
 3014    fn begin_columnar_selection(
 3015        &mut self,
 3016        position: DisplayPoint,
 3017        goal_column: u32,
 3018        reset: bool,
 3019        cx: &mut ViewContext<Self>,
 3020    ) {
 3021        if !self.focus_handle.is_focused(cx) {
 3022            self.last_focused_descendant = None;
 3023            cx.focus(&self.focus_handle);
 3024        }
 3025
 3026        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3027
 3028        if reset {
 3029            let pointer_position = display_map
 3030                .buffer_snapshot
 3031                .anchor_before(position.to_point(&display_map));
 3032
 3033            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 3034                s.clear_disjoint();
 3035                s.set_pending_anchor_range(
 3036                    pointer_position..pointer_position,
 3037                    SelectMode::Character,
 3038                );
 3039            });
 3040        }
 3041
 3042        let tail = self.selections.newest::<Point>(cx).tail();
 3043        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3044
 3045        if !reset {
 3046            self.select_columns(
 3047                tail.to_display_point(&display_map),
 3048                position,
 3049                goal_column,
 3050                &display_map,
 3051                cx,
 3052            );
 3053        }
 3054    }
 3055
 3056    fn update_selection(
 3057        &mut self,
 3058        position: DisplayPoint,
 3059        goal_column: u32,
 3060        scroll_delta: gpui::Point<f32>,
 3061        cx: &mut ViewContext<Self>,
 3062    ) {
 3063        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3064
 3065        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3066            let tail = tail.to_display_point(&display_map);
 3067            self.select_columns(tail, position, goal_column, &display_map, cx);
 3068        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3069            let buffer = self.buffer.read(cx).snapshot(cx);
 3070            let head;
 3071            let tail;
 3072            let mode = self.selections.pending_mode().unwrap();
 3073            match &mode {
 3074                SelectMode::Character => {
 3075                    head = position.to_point(&display_map);
 3076                    tail = pending.tail().to_point(&buffer);
 3077                }
 3078                SelectMode::Word(original_range) => {
 3079                    let original_display_range = original_range.start.to_display_point(&display_map)
 3080                        ..original_range.end.to_display_point(&display_map);
 3081                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3082                        ..original_display_range.end.to_point(&display_map);
 3083                    if movement::is_inside_word(&display_map, position)
 3084                        || original_display_range.contains(&position)
 3085                    {
 3086                        let word_range = movement::surrounding_word(&display_map, position);
 3087                        if word_range.start < original_display_range.start {
 3088                            head = word_range.start.to_point(&display_map);
 3089                        } else {
 3090                            head = word_range.end.to_point(&display_map);
 3091                        }
 3092                    } else {
 3093                        head = position.to_point(&display_map);
 3094                    }
 3095
 3096                    if head <= original_buffer_range.start {
 3097                        tail = original_buffer_range.end;
 3098                    } else {
 3099                        tail = original_buffer_range.start;
 3100                    }
 3101                }
 3102                SelectMode::Line(original_range) => {
 3103                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3104
 3105                    let position = display_map
 3106                        .clip_point(position, Bias::Left)
 3107                        .to_point(&display_map);
 3108                    let line_start = display_map.prev_line_boundary(position).0;
 3109                    let next_line_start = buffer.clip_point(
 3110                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3111                        Bias::Left,
 3112                    );
 3113
 3114                    if line_start < original_range.start {
 3115                        head = line_start
 3116                    } else {
 3117                        head = next_line_start
 3118                    }
 3119
 3120                    if head <= original_range.start {
 3121                        tail = original_range.end;
 3122                    } else {
 3123                        tail = original_range.start;
 3124                    }
 3125                }
 3126                SelectMode::All => {
 3127                    return;
 3128                }
 3129            };
 3130
 3131            if head < tail {
 3132                pending.start = buffer.anchor_before(head);
 3133                pending.end = buffer.anchor_before(tail);
 3134                pending.reversed = true;
 3135            } else {
 3136                pending.start = buffer.anchor_before(tail);
 3137                pending.end = buffer.anchor_before(head);
 3138                pending.reversed = false;
 3139            }
 3140
 3141            self.change_selections(None, cx, |s| {
 3142                s.set_pending(pending, mode);
 3143            });
 3144        } else {
 3145            log::error!("update_selection dispatched with no pending selection");
 3146            return;
 3147        }
 3148
 3149        self.apply_scroll_delta(scroll_delta, cx);
 3150        cx.notify();
 3151    }
 3152
 3153    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3154        self.columnar_selection_tail.take();
 3155        if self.selections.pending_anchor().is_some() {
 3156            let selections = self.selections.all::<usize>(cx);
 3157            self.change_selections(None, cx, |s| {
 3158                s.select(selections);
 3159                s.clear_pending();
 3160            });
 3161        }
 3162    }
 3163
 3164    fn select_columns(
 3165        &mut self,
 3166        tail: DisplayPoint,
 3167        head: DisplayPoint,
 3168        goal_column: u32,
 3169        display_map: &DisplaySnapshot,
 3170        cx: &mut ViewContext<Self>,
 3171    ) {
 3172        let start_row = cmp::min(tail.row(), head.row());
 3173        let end_row = cmp::max(tail.row(), head.row());
 3174        let start_column = cmp::min(tail.column(), goal_column);
 3175        let end_column = cmp::max(tail.column(), goal_column);
 3176        let reversed = start_column < tail.column();
 3177
 3178        let selection_ranges = (start_row.0..=end_row.0)
 3179            .map(DisplayRow)
 3180            .filter_map(|row| {
 3181                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3182                    let start = display_map
 3183                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3184                        .to_point(display_map);
 3185                    let end = display_map
 3186                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3187                        .to_point(display_map);
 3188                    if reversed {
 3189                        Some(end..start)
 3190                    } else {
 3191                        Some(start..end)
 3192                    }
 3193                } else {
 3194                    None
 3195                }
 3196            })
 3197            .collect::<Vec<_>>();
 3198
 3199        self.change_selections(None, cx, |s| {
 3200            s.select_ranges(selection_ranges);
 3201        });
 3202        cx.notify();
 3203    }
 3204
 3205    pub fn has_pending_nonempty_selection(&self) -> bool {
 3206        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3207            Some(Selection { start, end, .. }) => start != end,
 3208            None => false,
 3209        };
 3210
 3211        pending_nonempty_selection
 3212            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3213    }
 3214
 3215    pub fn has_pending_selection(&self) -> bool {
 3216        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3217    }
 3218
 3219    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3220        if self.clear_expanded_diff_hunks(cx) {
 3221            cx.notify();
 3222            return;
 3223        }
 3224        if self.dismiss_menus_and_popups(true, cx) {
 3225            return;
 3226        }
 3227
 3228        if self.mode == EditorMode::Full
 3229            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3230        {
 3231            return;
 3232        }
 3233
 3234        cx.propagate();
 3235    }
 3236
 3237    pub fn dismiss_menus_and_popups(
 3238        &mut self,
 3239        should_report_inline_completion_event: bool,
 3240        cx: &mut ViewContext<Self>,
 3241    ) -> bool {
 3242        if self.take_rename(false, cx).is_some() {
 3243            return true;
 3244        }
 3245
 3246        if hide_hover(self, cx) {
 3247            return true;
 3248        }
 3249
 3250        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3251            return true;
 3252        }
 3253
 3254        if self.hide_context_menu(cx).is_some() {
 3255            return true;
 3256        }
 3257
 3258        if self.mouse_context_menu.take().is_some() {
 3259            return true;
 3260        }
 3261
 3262        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3263            return true;
 3264        }
 3265
 3266        if self.snippet_stack.pop().is_some() {
 3267            return true;
 3268        }
 3269
 3270        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3271            self.dismiss_diagnostics(cx);
 3272            return true;
 3273        }
 3274
 3275        false
 3276    }
 3277
 3278    fn linked_editing_ranges_for(
 3279        &self,
 3280        selection: Range<text::Anchor>,
 3281        cx: &AppContext,
 3282    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3283        if self.linked_edit_ranges.is_empty() {
 3284            return None;
 3285        }
 3286        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3287            selection.end.buffer_id.and_then(|end_buffer_id| {
 3288                if selection.start.buffer_id != Some(end_buffer_id) {
 3289                    return None;
 3290                }
 3291                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3292                let snapshot = buffer.read(cx).snapshot();
 3293                self.linked_edit_ranges
 3294                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3295                    .map(|ranges| (ranges, snapshot, buffer))
 3296            })?;
 3297        use text::ToOffset as TO;
 3298        // find offset from the start of current range to current cursor position
 3299        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3300
 3301        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3302        let start_difference = start_offset - start_byte_offset;
 3303        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3304        let end_difference = end_offset - start_byte_offset;
 3305        // Current range has associated linked ranges.
 3306        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3307        for range in linked_ranges.iter() {
 3308            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3309            let end_offset = start_offset + end_difference;
 3310            let start_offset = start_offset + start_difference;
 3311            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3312                continue;
 3313            }
 3314            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3315                if s.start.buffer_id != selection.start.buffer_id
 3316                    || s.end.buffer_id != selection.end.buffer_id
 3317                {
 3318                    return false;
 3319                }
 3320                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3321                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3322            }) {
 3323                continue;
 3324            }
 3325            let start = buffer_snapshot.anchor_after(start_offset);
 3326            let end = buffer_snapshot.anchor_after(end_offset);
 3327            linked_edits
 3328                .entry(buffer.clone())
 3329                .or_default()
 3330                .push(start..end);
 3331        }
 3332        Some(linked_edits)
 3333    }
 3334
 3335    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3336        let text: Arc<str> = text.into();
 3337
 3338        if self.read_only(cx) {
 3339            return;
 3340        }
 3341
 3342        let selections = self.selections.all_adjusted(cx);
 3343        let mut bracket_inserted = false;
 3344        let mut edits = Vec::new();
 3345        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3346        let mut new_selections = Vec::with_capacity(selections.len());
 3347        let mut new_autoclose_regions = Vec::new();
 3348        let snapshot = self.buffer.read(cx).read(cx);
 3349
 3350        for (selection, autoclose_region) in
 3351            self.selections_with_autoclose_regions(selections, &snapshot)
 3352        {
 3353            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3354                // Determine if the inserted text matches the opening or closing
 3355                // bracket of any of this language's bracket pairs.
 3356                let mut bracket_pair = None;
 3357                let mut is_bracket_pair_start = false;
 3358                let mut is_bracket_pair_end = false;
 3359                if !text.is_empty() {
 3360                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3361                    //  and they are removing the character that triggered IME popup.
 3362                    for (pair, enabled) in scope.brackets() {
 3363                        if !pair.close && !pair.surround {
 3364                            continue;
 3365                        }
 3366
 3367                        if enabled && pair.start.ends_with(text.as_ref()) {
 3368                            let prefix_len = pair.start.len() - text.len();
 3369                            let preceding_text_matches_prefix = prefix_len == 0
 3370                                || (selection.start.column >= (prefix_len as u32)
 3371                                    && snapshot.contains_str_at(
 3372                                        Point::new(
 3373                                            selection.start.row,
 3374                                            selection.start.column - (prefix_len as u32),
 3375                                        ),
 3376                                        &pair.start[..prefix_len],
 3377                                    ));
 3378                            if preceding_text_matches_prefix {
 3379                                bracket_pair = Some(pair.clone());
 3380                                is_bracket_pair_start = true;
 3381                                break;
 3382                            }
 3383                        }
 3384                        if pair.end.as_str() == text.as_ref() {
 3385                            bracket_pair = Some(pair.clone());
 3386                            is_bracket_pair_end = true;
 3387                            break;
 3388                        }
 3389                    }
 3390                }
 3391
 3392                if let Some(bracket_pair) = bracket_pair {
 3393                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3394                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3395                    let auto_surround =
 3396                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3397                    if selection.is_empty() {
 3398                        if is_bracket_pair_start {
 3399                            // If the inserted text is a suffix of an opening bracket and the
 3400                            // selection is preceded by the rest of the opening bracket, then
 3401                            // insert the closing bracket.
 3402                            let following_text_allows_autoclose = snapshot
 3403                                .chars_at(selection.start)
 3404                                .next()
 3405                                .map_or(true, |c| scope.should_autoclose_before(c));
 3406
 3407                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3408                                && bracket_pair.start.len() == 1
 3409                            {
 3410                                let target = bracket_pair.start.chars().next().unwrap();
 3411                                let current_line_count = snapshot
 3412                                    .reversed_chars_at(selection.start)
 3413                                    .take_while(|&c| c != '\n')
 3414                                    .filter(|&c| c == target)
 3415                                    .count();
 3416                                current_line_count % 2 == 1
 3417                            } else {
 3418                                false
 3419                            };
 3420
 3421                            if autoclose
 3422                                && bracket_pair.close
 3423                                && following_text_allows_autoclose
 3424                                && !is_closing_quote
 3425                            {
 3426                                let anchor = snapshot.anchor_before(selection.end);
 3427                                new_selections.push((selection.map(|_| anchor), text.len()));
 3428                                new_autoclose_regions.push((
 3429                                    anchor,
 3430                                    text.len(),
 3431                                    selection.id,
 3432                                    bracket_pair.clone(),
 3433                                ));
 3434                                edits.push((
 3435                                    selection.range(),
 3436                                    format!("{}{}", text, bracket_pair.end).into(),
 3437                                ));
 3438                                bracket_inserted = true;
 3439                                continue;
 3440                            }
 3441                        }
 3442
 3443                        if let Some(region) = autoclose_region {
 3444                            // If the selection is followed by an auto-inserted closing bracket,
 3445                            // then don't insert that closing bracket again; just move the selection
 3446                            // past the closing bracket.
 3447                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3448                                && text.as_ref() == region.pair.end.as_str();
 3449                            if should_skip {
 3450                                let anchor = snapshot.anchor_after(selection.end);
 3451                                new_selections
 3452                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3453                                continue;
 3454                            }
 3455                        }
 3456
 3457                        let always_treat_brackets_as_autoclosed = snapshot
 3458                            .settings_at(selection.start, cx)
 3459                            .always_treat_brackets_as_autoclosed;
 3460                        if always_treat_brackets_as_autoclosed
 3461                            && is_bracket_pair_end
 3462                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3463                        {
 3464                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3465                            // and the inserted text is a closing bracket and the selection is followed
 3466                            // by the closing bracket then move the selection past the closing bracket.
 3467                            let anchor = snapshot.anchor_after(selection.end);
 3468                            new_selections.push((selection.map(|_| anchor), text.len()));
 3469                            continue;
 3470                        }
 3471                    }
 3472                    // If an opening bracket is 1 character long and is typed while
 3473                    // text is selected, then surround that text with the bracket pair.
 3474                    else if auto_surround
 3475                        && bracket_pair.surround
 3476                        && is_bracket_pair_start
 3477                        && bracket_pair.start.chars().count() == 1
 3478                    {
 3479                        edits.push((selection.start..selection.start, text.clone()));
 3480                        edits.push((
 3481                            selection.end..selection.end,
 3482                            bracket_pair.end.as_str().into(),
 3483                        ));
 3484                        bracket_inserted = true;
 3485                        new_selections.push((
 3486                            Selection {
 3487                                id: selection.id,
 3488                                start: snapshot.anchor_after(selection.start),
 3489                                end: snapshot.anchor_before(selection.end),
 3490                                reversed: selection.reversed,
 3491                                goal: selection.goal,
 3492                            },
 3493                            0,
 3494                        ));
 3495                        continue;
 3496                    }
 3497                }
 3498            }
 3499
 3500            if self.auto_replace_emoji_shortcode
 3501                && selection.is_empty()
 3502                && text.as_ref().ends_with(':')
 3503            {
 3504                if let Some(possible_emoji_short_code) =
 3505                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3506                {
 3507                    if !possible_emoji_short_code.is_empty() {
 3508                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3509                            let emoji_shortcode_start = Point::new(
 3510                                selection.start.row,
 3511                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3512                            );
 3513
 3514                            // Remove shortcode from buffer
 3515                            edits.push((
 3516                                emoji_shortcode_start..selection.start,
 3517                                "".to_string().into(),
 3518                            ));
 3519                            new_selections.push((
 3520                                Selection {
 3521                                    id: selection.id,
 3522                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3523                                    end: snapshot.anchor_before(selection.start),
 3524                                    reversed: selection.reversed,
 3525                                    goal: selection.goal,
 3526                                },
 3527                                0,
 3528                            ));
 3529
 3530                            // Insert emoji
 3531                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3532                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3533                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3534
 3535                            continue;
 3536                        }
 3537                    }
 3538                }
 3539            }
 3540
 3541            // If not handling any auto-close operation, then just replace the selected
 3542            // text with the given input and move the selection to the end of the
 3543            // newly inserted text.
 3544            let anchor = snapshot.anchor_after(selection.end);
 3545            if !self.linked_edit_ranges.is_empty() {
 3546                let start_anchor = snapshot.anchor_before(selection.start);
 3547
 3548                let is_word_char = text.chars().next().map_or(true, |char| {
 3549                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3550                    classifier.is_word(char)
 3551                });
 3552
 3553                if is_word_char {
 3554                    if let Some(ranges) = self
 3555                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3556                    {
 3557                        for (buffer, edits) in ranges {
 3558                            linked_edits
 3559                                .entry(buffer.clone())
 3560                                .or_default()
 3561                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3562                        }
 3563                    }
 3564                }
 3565            }
 3566
 3567            new_selections.push((selection.map(|_| anchor), 0));
 3568            edits.push((selection.start..selection.end, text.clone()));
 3569        }
 3570
 3571        drop(snapshot);
 3572
 3573        self.transact(cx, |this, cx| {
 3574            this.buffer.update(cx, |buffer, cx| {
 3575                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3576            });
 3577            for (buffer, edits) in linked_edits {
 3578                buffer.update(cx, |buffer, cx| {
 3579                    let snapshot = buffer.snapshot();
 3580                    let edits = edits
 3581                        .into_iter()
 3582                        .map(|(range, text)| {
 3583                            use text::ToPoint as TP;
 3584                            let end_point = TP::to_point(&range.end, &snapshot);
 3585                            let start_point = TP::to_point(&range.start, &snapshot);
 3586                            (start_point..end_point, text)
 3587                        })
 3588                        .sorted_by_key(|(range, _)| range.start)
 3589                        .collect::<Vec<_>>();
 3590                    buffer.edit(edits, None, cx);
 3591                })
 3592            }
 3593            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3594            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3595            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3596            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3597                .zip(new_selection_deltas)
 3598                .map(|(selection, delta)| Selection {
 3599                    id: selection.id,
 3600                    start: selection.start + delta,
 3601                    end: selection.end + delta,
 3602                    reversed: selection.reversed,
 3603                    goal: SelectionGoal::None,
 3604                })
 3605                .collect::<Vec<_>>();
 3606
 3607            let mut i = 0;
 3608            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3609                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3610                let start = map.buffer_snapshot.anchor_before(position);
 3611                let end = map.buffer_snapshot.anchor_after(position);
 3612                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3613                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3614                        Ordering::Less => i += 1,
 3615                        Ordering::Greater => break,
 3616                        Ordering::Equal => {
 3617                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3618                                Ordering::Less => i += 1,
 3619                                Ordering::Equal => break,
 3620                                Ordering::Greater => break,
 3621                            }
 3622                        }
 3623                    }
 3624                }
 3625                this.autoclose_regions.insert(
 3626                    i,
 3627                    AutocloseRegion {
 3628                        selection_id,
 3629                        range: start..end,
 3630                        pair,
 3631                    },
 3632                );
 3633            }
 3634
 3635            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3636            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3637                s.select(new_selections)
 3638            });
 3639
 3640            if !bracket_inserted {
 3641                if let Some(on_type_format_task) =
 3642                    this.trigger_on_type_formatting(text.to_string(), cx)
 3643                {
 3644                    on_type_format_task.detach_and_log_err(cx);
 3645                }
 3646            }
 3647
 3648            let editor_settings = EditorSettings::get_global(cx);
 3649            if bracket_inserted
 3650                && (editor_settings.auto_signature_help
 3651                    || editor_settings.show_signature_help_after_edits)
 3652            {
 3653                this.show_signature_help(&ShowSignatureHelp, cx);
 3654            }
 3655
 3656            let trigger_in_words = !had_active_inline_completion;
 3657            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3658            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3659            this.refresh_inline_completion(true, false, cx);
 3660        });
 3661    }
 3662
 3663    fn find_possible_emoji_shortcode_at_position(
 3664        snapshot: &MultiBufferSnapshot,
 3665        position: Point,
 3666    ) -> Option<String> {
 3667        let mut chars = Vec::new();
 3668        let mut found_colon = false;
 3669        for char in snapshot.reversed_chars_at(position).take(100) {
 3670            // Found a possible emoji shortcode in the middle of the buffer
 3671            if found_colon {
 3672                if char.is_whitespace() {
 3673                    chars.reverse();
 3674                    return Some(chars.iter().collect());
 3675                }
 3676                // If the previous character is not a whitespace, we are in the middle of a word
 3677                // and we only want to complete the shortcode if the word is made up of other emojis
 3678                let mut containing_word = String::new();
 3679                for ch in snapshot
 3680                    .reversed_chars_at(position)
 3681                    .skip(chars.len() + 1)
 3682                    .take(100)
 3683                {
 3684                    if ch.is_whitespace() {
 3685                        break;
 3686                    }
 3687                    containing_word.push(ch);
 3688                }
 3689                let containing_word = containing_word.chars().rev().collect::<String>();
 3690                if util::word_consists_of_emojis(containing_word.as_str()) {
 3691                    chars.reverse();
 3692                    return Some(chars.iter().collect());
 3693                }
 3694            }
 3695
 3696            if char.is_whitespace() || !char.is_ascii() {
 3697                return None;
 3698            }
 3699            if char == ':' {
 3700                found_colon = true;
 3701            } else {
 3702                chars.push(char);
 3703            }
 3704        }
 3705        // Found a possible emoji shortcode at the beginning of the buffer
 3706        chars.reverse();
 3707        Some(chars.iter().collect())
 3708    }
 3709
 3710    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3711        self.transact(cx, |this, cx| {
 3712            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3713                let selections = this.selections.all::<usize>(cx);
 3714                let multi_buffer = this.buffer.read(cx);
 3715                let buffer = multi_buffer.snapshot(cx);
 3716                selections
 3717                    .iter()
 3718                    .map(|selection| {
 3719                        let start_point = selection.start.to_point(&buffer);
 3720                        let mut indent =
 3721                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3722                        indent.len = cmp::min(indent.len, start_point.column);
 3723                        let start = selection.start;
 3724                        let end = selection.end;
 3725                        let selection_is_empty = start == end;
 3726                        let language_scope = buffer.language_scope_at(start);
 3727                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3728                            &language_scope
 3729                        {
 3730                            let leading_whitespace_len = buffer
 3731                                .reversed_chars_at(start)
 3732                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3733                                .map(|c| c.len_utf8())
 3734                                .sum::<usize>();
 3735
 3736                            let trailing_whitespace_len = buffer
 3737                                .chars_at(end)
 3738                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3739                                .map(|c| c.len_utf8())
 3740                                .sum::<usize>();
 3741
 3742                            let insert_extra_newline =
 3743                                language.brackets().any(|(pair, enabled)| {
 3744                                    let pair_start = pair.start.trim_end();
 3745                                    let pair_end = pair.end.trim_start();
 3746
 3747                                    enabled
 3748                                        && pair.newline
 3749                                        && buffer.contains_str_at(
 3750                                            end + trailing_whitespace_len,
 3751                                            pair_end,
 3752                                        )
 3753                                        && buffer.contains_str_at(
 3754                                            (start - leading_whitespace_len)
 3755                                                .saturating_sub(pair_start.len()),
 3756                                            pair_start,
 3757                                        )
 3758                                });
 3759
 3760                            // Comment extension on newline is allowed only for cursor selections
 3761                            let comment_delimiter = maybe!({
 3762                                if !selection_is_empty {
 3763                                    return None;
 3764                                }
 3765
 3766                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3767                                    return None;
 3768                                }
 3769
 3770                                let delimiters = language.line_comment_prefixes();
 3771                                let max_len_of_delimiter =
 3772                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3773                                let (snapshot, range) =
 3774                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3775
 3776                                let mut index_of_first_non_whitespace = 0;
 3777                                let comment_candidate = snapshot
 3778                                    .chars_for_range(range)
 3779                                    .skip_while(|c| {
 3780                                        let should_skip = c.is_whitespace();
 3781                                        if should_skip {
 3782                                            index_of_first_non_whitespace += 1;
 3783                                        }
 3784                                        should_skip
 3785                                    })
 3786                                    .take(max_len_of_delimiter)
 3787                                    .collect::<String>();
 3788                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3789                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3790                                })?;
 3791                                let cursor_is_placed_after_comment_marker =
 3792                                    index_of_first_non_whitespace + comment_prefix.len()
 3793                                        <= start_point.column as usize;
 3794                                if cursor_is_placed_after_comment_marker {
 3795                                    Some(comment_prefix.clone())
 3796                                } else {
 3797                                    None
 3798                                }
 3799                            });
 3800                            (comment_delimiter, insert_extra_newline)
 3801                        } else {
 3802                            (None, false)
 3803                        };
 3804
 3805                        let capacity_for_delimiter = comment_delimiter
 3806                            .as_deref()
 3807                            .map(str::len)
 3808                            .unwrap_or_default();
 3809                        let mut new_text =
 3810                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3811                        new_text.push('\n');
 3812                        new_text.extend(indent.chars());
 3813                        if let Some(delimiter) = &comment_delimiter {
 3814                            new_text.push_str(delimiter);
 3815                        }
 3816                        if insert_extra_newline {
 3817                            new_text = new_text.repeat(2);
 3818                        }
 3819
 3820                        let anchor = buffer.anchor_after(end);
 3821                        let new_selection = selection.map(|_| anchor);
 3822                        (
 3823                            (start..end, new_text),
 3824                            (insert_extra_newline, new_selection),
 3825                        )
 3826                    })
 3827                    .unzip()
 3828            };
 3829
 3830            this.edit_with_autoindent(edits, cx);
 3831            let buffer = this.buffer.read(cx).snapshot(cx);
 3832            let new_selections = selection_fixup_info
 3833                .into_iter()
 3834                .map(|(extra_newline_inserted, new_selection)| {
 3835                    let mut cursor = new_selection.end.to_point(&buffer);
 3836                    if extra_newline_inserted {
 3837                        cursor.row -= 1;
 3838                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3839                    }
 3840                    new_selection.map(|_| cursor)
 3841                })
 3842                .collect();
 3843
 3844            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3845            this.refresh_inline_completion(true, false, cx);
 3846        });
 3847    }
 3848
 3849    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3850        let buffer = self.buffer.read(cx);
 3851        let snapshot = buffer.snapshot(cx);
 3852
 3853        let mut edits = Vec::new();
 3854        let mut rows = Vec::new();
 3855
 3856        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3857            let cursor = selection.head();
 3858            let row = cursor.row;
 3859
 3860            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3861
 3862            let newline = "\n".to_string();
 3863            edits.push((start_of_line..start_of_line, newline));
 3864
 3865            rows.push(row + rows_inserted as u32);
 3866        }
 3867
 3868        self.transact(cx, |editor, cx| {
 3869            editor.edit(edits, cx);
 3870
 3871            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3872                let mut index = 0;
 3873                s.move_cursors_with(|map, _, _| {
 3874                    let row = rows[index];
 3875                    index += 1;
 3876
 3877                    let point = Point::new(row, 0);
 3878                    let boundary = map.next_line_boundary(point).1;
 3879                    let clipped = map.clip_point(boundary, Bias::Left);
 3880
 3881                    (clipped, SelectionGoal::None)
 3882                });
 3883            });
 3884
 3885            let mut indent_edits = Vec::new();
 3886            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3887            for row in rows {
 3888                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3889                for (row, indent) in indents {
 3890                    if indent.len == 0 {
 3891                        continue;
 3892                    }
 3893
 3894                    let text = match indent.kind {
 3895                        IndentKind::Space => " ".repeat(indent.len as usize),
 3896                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3897                    };
 3898                    let point = Point::new(row.0, 0);
 3899                    indent_edits.push((point..point, text));
 3900                }
 3901            }
 3902            editor.edit(indent_edits, cx);
 3903        });
 3904    }
 3905
 3906    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3907        let buffer = self.buffer.read(cx);
 3908        let snapshot = buffer.snapshot(cx);
 3909
 3910        let mut edits = Vec::new();
 3911        let mut rows = Vec::new();
 3912        let mut rows_inserted = 0;
 3913
 3914        for selection in self.selections.all_adjusted(cx) {
 3915            let cursor = selection.head();
 3916            let row = cursor.row;
 3917
 3918            let point = Point::new(row + 1, 0);
 3919            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3920
 3921            let newline = "\n".to_string();
 3922            edits.push((start_of_line..start_of_line, newline));
 3923
 3924            rows_inserted += 1;
 3925            rows.push(row + rows_inserted);
 3926        }
 3927
 3928        self.transact(cx, |editor, cx| {
 3929            editor.edit(edits, cx);
 3930
 3931            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3932                let mut index = 0;
 3933                s.move_cursors_with(|map, _, _| {
 3934                    let row = rows[index];
 3935                    index += 1;
 3936
 3937                    let point = Point::new(row, 0);
 3938                    let boundary = map.next_line_boundary(point).1;
 3939                    let clipped = map.clip_point(boundary, Bias::Left);
 3940
 3941                    (clipped, SelectionGoal::None)
 3942                });
 3943            });
 3944
 3945            let mut indent_edits = Vec::new();
 3946            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3947            for row in rows {
 3948                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3949                for (row, indent) in indents {
 3950                    if indent.len == 0 {
 3951                        continue;
 3952                    }
 3953
 3954                    let text = match indent.kind {
 3955                        IndentKind::Space => " ".repeat(indent.len as usize),
 3956                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3957                    };
 3958                    let point = Point::new(row.0, 0);
 3959                    indent_edits.push((point..point, text));
 3960                }
 3961            }
 3962            editor.edit(indent_edits, cx);
 3963        });
 3964    }
 3965
 3966    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3967        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3968            original_indent_columns: Vec::new(),
 3969        });
 3970        self.insert_with_autoindent_mode(text, autoindent, cx);
 3971    }
 3972
 3973    fn insert_with_autoindent_mode(
 3974        &mut self,
 3975        text: &str,
 3976        autoindent_mode: Option<AutoindentMode>,
 3977        cx: &mut ViewContext<Self>,
 3978    ) {
 3979        if self.read_only(cx) {
 3980            return;
 3981        }
 3982
 3983        let text: Arc<str> = text.into();
 3984        self.transact(cx, |this, cx| {
 3985            let old_selections = this.selections.all_adjusted(cx);
 3986            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3987                let anchors = {
 3988                    let snapshot = buffer.read(cx);
 3989                    old_selections
 3990                        .iter()
 3991                        .map(|s| {
 3992                            let anchor = snapshot.anchor_after(s.head());
 3993                            s.map(|_| anchor)
 3994                        })
 3995                        .collect::<Vec<_>>()
 3996                };
 3997                buffer.edit(
 3998                    old_selections
 3999                        .iter()
 4000                        .map(|s| (s.start..s.end, text.clone())),
 4001                    autoindent_mode,
 4002                    cx,
 4003                );
 4004                anchors
 4005            });
 4006
 4007            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4008                s.select_anchors(selection_anchors);
 4009            })
 4010        });
 4011    }
 4012
 4013    fn trigger_completion_on_input(
 4014        &mut self,
 4015        text: &str,
 4016        trigger_in_words: bool,
 4017        cx: &mut ViewContext<Self>,
 4018    ) {
 4019        if self.is_completion_trigger(text, trigger_in_words, cx) {
 4020            self.show_completions(
 4021                &ShowCompletions {
 4022                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4023                },
 4024                cx,
 4025            );
 4026        } else {
 4027            self.hide_context_menu(cx);
 4028        }
 4029    }
 4030
 4031    fn is_completion_trigger(
 4032        &self,
 4033        text: &str,
 4034        trigger_in_words: bool,
 4035        cx: &mut ViewContext<Self>,
 4036    ) -> bool {
 4037        let position = self.selections.newest_anchor().head();
 4038        let multibuffer = self.buffer.read(cx);
 4039        let Some(buffer) = position
 4040            .buffer_id
 4041            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4042        else {
 4043            return false;
 4044        };
 4045
 4046        if let Some(completion_provider) = &self.completion_provider {
 4047            completion_provider.is_completion_trigger(
 4048                &buffer,
 4049                position.text_anchor,
 4050                text,
 4051                trigger_in_words,
 4052                cx,
 4053            )
 4054        } else {
 4055            false
 4056        }
 4057    }
 4058
 4059    /// If any empty selections is touching the start of its innermost containing autoclose
 4060    /// region, expand it to select the brackets.
 4061    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4062        let selections = self.selections.all::<usize>(cx);
 4063        let buffer = self.buffer.read(cx).read(cx);
 4064        let new_selections = self
 4065            .selections_with_autoclose_regions(selections, &buffer)
 4066            .map(|(mut selection, region)| {
 4067                if !selection.is_empty() {
 4068                    return selection;
 4069                }
 4070
 4071                if let Some(region) = region {
 4072                    let mut range = region.range.to_offset(&buffer);
 4073                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4074                        range.start -= region.pair.start.len();
 4075                        if buffer.contains_str_at(range.start, &region.pair.start)
 4076                            && buffer.contains_str_at(range.end, &region.pair.end)
 4077                        {
 4078                            range.end += region.pair.end.len();
 4079                            selection.start = range.start;
 4080                            selection.end = range.end;
 4081
 4082                            return selection;
 4083                        }
 4084                    }
 4085                }
 4086
 4087                let always_treat_brackets_as_autoclosed = buffer
 4088                    .settings_at(selection.start, cx)
 4089                    .always_treat_brackets_as_autoclosed;
 4090
 4091                if !always_treat_brackets_as_autoclosed {
 4092                    return selection;
 4093                }
 4094
 4095                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4096                    for (pair, enabled) in scope.brackets() {
 4097                        if !enabled || !pair.close {
 4098                            continue;
 4099                        }
 4100
 4101                        if buffer.contains_str_at(selection.start, &pair.end) {
 4102                            let pair_start_len = pair.start.len();
 4103                            if buffer.contains_str_at(
 4104                                selection.start.saturating_sub(pair_start_len),
 4105                                &pair.start,
 4106                            ) {
 4107                                selection.start -= pair_start_len;
 4108                                selection.end += pair.end.len();
 4109
 4110                                return selection;
 4111                            }
 4112                        }
 4113                    }
 4114                }
 4115
 4116                selection
 4117            })
 4118            .collect();
 4119
 4120        drop(buffer);
 4121        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4122    }
 4123
 4124    /// Iterate the given selections, and for each one, find the smallest surrounding
 4125    /// autoclose region. This uses the ordering of the selections and the autoclose
 4126    /// regions to avoid repeated comparisons.
 4127    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4128        &'a self,
 4129        selections: impl IntoIterator<Item = Selection<D>>,
 4130        buffer: &'a MultiBufferSnapshot,
 4131    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4132        let mut i = 0;
 4133        let mut regions = self.autoclose_regions.as_slice();
 4134        selections.into_iter().map(move |selection| {
 4135            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4136
 4137            let mut enclosing = None;
 4138            while let Some(pair_state) = regions.get(i) {
 4139                if pair_state.range.end.to_offset(buffer) < range.start {
 4140                    regions = &regions[i + 1..];
 4141                    i = 0;
 4142                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4143                    break;
 4144                } else {
 4145                    if pair_state.selection_id == selection.id {
 4146                        enclosing = Some(pair_state);
 4147                    }
 4148                    i += 1;
 4149                }
 4150            }
 4151
 4152            (selection, enclosing)
 4153        })
 4154    }
 4155
 4156    /// Remove any autoclose regions that no longer contain their selection.
 4157    fn invalidate_autoclose_regions(
 4158        &mut self,
 4159        mut selections: &[Selection<Anchor>],
 4160        buffer: &MultiBufferSnapshot,
 4161    ) {
 4162        self.autoclose_regions.retain(|state| {
 4163            let mut i = 0;
 4164            while let Some(selection) = selections.get(i) {
 4165                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4166                    selections = &selections[1..];
 4167                    continue;
 4168                }
 4169                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4170                    break;
 4171                }
 4172                if selection.id == state.selection_id {
 4173                    return true;
 4174                } else {
 4175                    i += 1;
 4176                }
 4177            }
 4178            false
 4179        });
 4180    }
 4181
 4182    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4183        let offset = position.to_offset(buffer);
 4184        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4185        if offset > word_range.start && kind == Some(CharKind::Word) {
 4186            Some(
 4187                buffer
 4188                    .text_for_range(word_range.start..offset)
 4189                    .collect::<String>(),
 4190            )
 4191        } else {
 4192            None
 4193        }
 4194    }
 4195
 4196    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4197        self.refresh_inlay_hints(
 4198            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4199            cx,
 4200        );
 4201    }
 4202
 4203    pub fn inlay_hints_enabled(&self) -> bool {
 4204        self.inlay_hint_cache.enabled
 4205    }
 4206
 4207    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4208        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4209            return;
 4210        }
 4211
 4212        let reason_description = reason.description();
 4213        let ignore_debounce = matches!(
 4214            reason,
 4215            InlayHintRefreshReason::SettingsChange(_)
 4216                | InlayHintRefreshReason::Toggle(_)
 4217                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4218        );
 4219        let (invalidate_cache, required_languages) = match reason {
 4220            InlayHintRefreshReason::Toggle(enabled) => {
 4221                self.inlay_hint_cache.enabled = enabled;
 4222                if enabled {
 4223                    (InvalidationStrategy::RefreshRequested, None)
 4224                } else {
 4225                    self.inlay_hint_cache.clear();
 4226                    self.splice_inlays(
 4227                        self.visible_inlay_hints(cx)
 4228                            .iter()
 4229                            .map(|inlay| inlay.id)
 4230                            .collect(),
 4231                        Vec::new(),
 4232                        cx,
 4233                    );
 4234                    return;
 4235                }
 4236            }
 4237            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4238                match self.inlay_hint_cache.update_settings(
 4239                    &self.buffer,
 4240                    new_settings,
 4241                    self.visible_inlay_hints(cx),
 4242                    cx,
 4243                ) {
 4244                    ControlFlow::Break(Some(InlaySplice {
 4245                        to_remove,
 4246                        to_insert,
 4247                    })) => {
 4248                        self.splice_inlays(to_remove, to_insert, cx);
 4249                        return;
 4250                    }
 4251                    ControlFlow::Break(None) => return,
 4252                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4253                }
 4254            }
 4255            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4256                if let Some(InlaySplice {
 4257                    to_remove,
 4258                    to_insert,
 4259                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4260                {
 4261                    self.splice_inlays(to_remove, to_insert, cx);
 4262                }
 4263                return;
 4264            }
 4265            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4266            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4267                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4268            }
 4269            InlayHintRefreshReason::RefreshRequested => {
 4270                (InvalidationStrategy::RefreshRequested, None)
 4271            }
 4272        };
 4273
 4274        if let Some(InlaySplice {
 4275            to_remove,
 4276            to_insert,
 4277        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4278            reason_description,
 4279            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4280            invalidate_cache,
 4281            ignore_debounce,
 4282            cx,
 4283        ) {
 4284            self.splice_inlays(to_remove, to_insert, cx);
 4285        }
 4286    }
 4287
 4288    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4289        self.display_map
 4290            .read(cx)
 4291            .current_inlays()
 4292            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4293            .cloned()
 4294            .collect()
 4295    }
 4296
 4297    pub fn excerpts_for_inlay_hints_query(
 4298        &self,
 4299        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4300        cx: &mut ViewContext<Editor>,
 4301    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4302        let Some(project) = self.project.as_ref() else {
 4303            return HashMap::default();
 4304        };
 4305        let project = project.read(cx);
 4306        let multi_buffer = self.buffer().read(cx);
 4307        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4308        let multi_buffer_visible_start = self
 4309            .scroll_manager
 4310            .anchor()
 4311            .anchor
 4312            .to_point(&multi_buffer_snapshot);
 4313        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4314            multi_buffer_visible_start
 4315                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4316            Bias::Left,
 4317        );
 4318        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4319        multi_buffer
 4320            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4321            .into_iter()
 4322            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4323            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4324                let buffer = buffer_handle.read(cx);
 4325                let buffer_file = project::File::from_dyn(buffer.file())?;
 4326                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4327                let worktree_entry = buffer_worktree
 4328                    .read(cx)
 4329                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4330                if worktree_entry.is_ignored {
 4331                    return None;
 4332                }
 4333
 4334                let language = buffer.language()?;
 4335                if let Some(restrict_to_languages) = restrict_to_languages {
 4336                    if !restrict_to_languages.contains(language) {
 4337                        return None;
 4338                    }
 4339                }
 4340                Some((
 4341                    excerpt_id,
 4342                    (
 4343                        buffer_handle,
 4344                        buffer.version().clone(),
 4345                        excerpt_visible_range,
 4346                    ),
 4347                ))
 4348            })
 4349            .collect()
 4350    }
 4351
 4352    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4353        TextLayoutDetails {
 4354            text_system: cx.text_system().clone(),
 4355            editor_style: self.style.clone().unwrap(),
 4356            rem_size: cx.rem_size(),
 4357            scroll_anchor: self.scroll_manager.anchor(),
 4358            visible_rows: self.visible_line_count(),
 4359            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4360        }
 4361    }
 4362
 4363    fn splice_inlays(
 4364        &self,
 4365        to_remove: Vec<InlayId>,
 4366        to_insert: Vec<Inlay>,
 4367        cx: &mut ViewContext<Self>,
 4368    ) {
 4369        self.display_map.update(cx, |display_map, cx| {
 4370            display_map.splice_inlays(to_remove, to_insert, cx);
 4371        });
 4372        cx.notify();
 4373    }
 4374
 4375    fn trigger_on_type_formatting(
 4376        &self,
 4377        input: String,
 4378        cx: &mut ViewContext<Self>,
 4379    ) -> Option<Task<Result<()>>> {
 4380        if input.len() != 1 {
 4381            return None;
 4382        }
 4383
 4384        let project = self.project.as_ref()?;
 4385        let position = self.selections.newest_anchor().head();
 4386        let (buffer, buffer_position) = self
 4387            .buffer
 4388            .read(cx)
 4389            .text_anchor_for_position(position, cx)?;
 4390
 4391        let settings = language_settings::language_settings(
 4392            buffer
 4393                .read(cx)
 4394                .language_at(buffer_position)
 4395                .map(|l| l.name()),
 4396            buffer.read(cx).file(),
 4397            cx,
 4398        );
 4399        if !settings.use_on_type_format {
 4400            return None;
 4401        }
 4402
 4403        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4404        // hence we do LSP request & edit on host side only — add formats to host's history.
 4405        let push_to_lsp_host_history = true;
 4406        // If this is not the host, append its history with new edits.
 4407        let push_to_client_history = project.read(cx).is_via_collab();
 4408
 4409        let on_type_formatting = project.update(cx, |project, cx| {
 4410            project.on_type_format(
 4411                buffer.clone(),
 4412                buffer_position,
 4413                input,
 4414                push_to_lsp_host_history,
 4415                cx,
 4416            )
 4417        });
 4418        Some(cx.spawn(|editor, mut cx| async move {
 4419            if let Some(transaction) = on_type_formatting.await? {
 4420                if push_to_client_history {
 4421                    buffer
 4422                        .update(&mut cx, |buffer, _| {
 4423                            buffer.push_transaction(transaction, Instant::now());
 4424                        })
 4425                        .ok();
 4426                }
 4427                editor.update(&mut cx, |editor, cx| {
 4428                    editor.refresh_document_highlights(cx);
 4429                })?;
 4430            }
 4431            Ok(())
 4432        }))
 4433    }
 4434
 4435    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4436        if self.pending_rename.is_some() {
 4437            return;
 4438        }
 4439
 4440        let Some(provider) = self.completion_provider.as_ref() else {
 4441            return;
 4442        };
 4443
 4444        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4445            return;
 4446        }
 4447
 4448        let position = self.selections.newest_anchor().head();
 4449        let (buffer, buffer_position) =
 4450            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4451                output
 4452            } else {
 4453                return;
 4454            };
 4455
 4456        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4457        let is_followup_invoke = {
 4458            let context_menu_state = self.context_menu.read();
 4459            matches!(
 4460                context_menu_state.deref(),
 4461                Some(ContextMenu::Completions(_))
 4462            )
 4463        };
 4464        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4465            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4466            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4467                CompletionTriggerKind::TRIGGER_CHARACTER
 4468            }
 4469
 4470            _ => CompletionTriggerKind::INVOKED,
 4471        };
 4472        let completion_context = CompletionContext {
 4473            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4474                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4475                    Some(String::from(trigger))
 4476                } else {
 4477                    None
 4478                }
 4479            }),
 4480            trigger_kind,
 4481        };
 4482        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4483        let sort_completions = provider.sort_completions();
 4484
 4485        let id = post_inc(&mut self.next_completion_id);
 4486        let task = cx.spawn(|editor, mut cx| {
 4487            async move {
 4488                editor.update(&mut cx, |this, _| {
 4489                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4490                })?;
 4491                let completions = completions.await.log_err();
 4492                let menu = if let Some(completions) = completions {
 4493                    let mut menu = CompletionsMenu::new(
 4494                        id,
 4495                        sort_completions,
 4496                        position,
 4497                        buffer.clone(),
 4498                        completions.into(),
 4499                    );
 4500                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4501                        .await;
 4502
 4503                    if menu.matches.is_empty() {
 4504                        None
 4505                    } else {
 4506                        Some(menu)
 4507                    }
 4508                } else {
 4509                    None
 4510                };
 4511
 4512                editor.update(&mut cx, |editor, cx| {
 4513                    let mut context_menu = editor.context_menu.write();
 4514                    match context_menu.as_ref() {
 4515                        None => {}
 4516
 4517                        Some(ContextMenu::Completions(prev_menu)) => {
 4518                            if prev_menu.id > id {
 4519                                return;
 4520                            }
 4521                        }
 4522
 4523                        _ => return,
 4524                    }
 4525
 4526                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 4527                        let mut menu = menu.unwrap();
 4528                        menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
 4529                        *context_menu = Some(ContextMenu::Completions(menu));
 4530                        drop(context_menu);
 4531                        editor.discard_inline_completion(false, cx);
 4532                        cx.notify();
 4533                    } else if editor.completion_tasks.len() <= 1 {
 4534                        // If there are no more completion tasks and the last menu was
 4535                        // empty, we should hide it. If it was already hidden, we should
 4536                        // also show the copilot completion when available.
 4537                        drop(context_menu);
 4538                        if editor.hide_context_menu(cx).is_none() {
 4539                            editor.update_visible_inline_completion(cx);
 4540                        }
 4541                    }
 4542                })?;
 4543
 4544                Ok::<_, anyhow::Error>(())
 4545            }
 4546            .log_err()
 4547        });
 4548
 4549        self.completion_tasks.push((id, task));
 4550    }
 4551
 4552    pub fn confirm_completion(
 4553        &mut self,
 4554        action: &ConfirmCompletion,
 4555        cx: &mut ViewContext<Self>,
 4556    ) -> Option<Task<Result<()>>> {
 4557        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4558    }
 4559
 4560    pub fn compose_completion(
 4561        &mut self,
 4562        action: &ComposeCompletion,
 4563        cx: &mut ViewContext<Self>,
 4564    ) -> Option<Task<Result<()>>> {
 4565        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4566    }
 4567
 4568    fn do_completion(
 4569        &mut self,
 4570        item_ix: Option<usize>,
 4571        intent: CompletionIntent,
 4572        cx: &mut ViewContext<Editor>,
 4573    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4574        use language::ToOffset as _;
 4575
 4576        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4577            menu
 4578        } else {
 4579            return None;
 4580        };
 4581
 4582        let mat = completions_menu
 4583            .matches
 4584            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4585        let buffer_handle = completions_menu.buffer;
 4586        let completions = completions_menu.completions.read();
 4587        let completion = completions.get(mat.candidate_id)?;
 4588        cx.stop_propagation();
 4589
 4590        let snippet;
 4591        let text;
 4592
 4593        if completion.is_snippet() {
 4594            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4595            text = snippet.as_ref().unwrap().text.clone();
 4596        } else {
 4597            snippet = None;
 4598            text = completion.new_text.clone();
 4599        };
 4600        let selections = self.selections.all::<usize>(cx);
 4601        let buffer = buffer_handle.read(cx);
 4602        let old_range = completion.old_range.to_offset(buffer);
 4603        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4604
 4605        let newest_selection = self.selections.newest_anchor();
 4606        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4607            return None;
 4608        }
 4609
 4610        let lookbehind = newest_selection
 4611            .start
 4612            .text_anchor
 4613            .to_offset(buffer)
 4614            .saturating_sub(old_range.start);
 4615        let lookahead = old_range
 4616            .end
 4617            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4618        let mut common_prefix_len = old_text
 4619            .bytes()
 4620            .zip(text.bytes())
 4621            .take_while(|(a, b)| a == b)
 4622            .count();
 4623
 4624        let snapshot = self.buffer.read(cx).snapshot(cx);
 4625        let mut range_to_replace: Option<Range<isize>> = None;
 4626        let mut ranges = Vec::new();
 4627        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4628        for selection in &selections {
 4629            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4630                let start = selection.start.saturating_sub(lookbehind);
 4631                let end = selection.end + lookahead;
 4632                if selection.id == newest_selection.id {
 4633                    range_to_replace = Some(
 4634                        ((start + common_prefix_len) as isize - selection.start as isize)
 4635                            ..(end as isize - selection.start as isize),
 4636                    );
 4637                }
 4638                ranges.push(start + common_prefix_len..end);
 4639            } else {
 4640                common_prefix_len = 0;
 4641                ranges.clear();
 4642                ranges.extend(selections.iter().map(|s| {
 4643                    if s.id == newest_selection.id {
 4644                        range_to_replace = Some(
 4645                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4646                                - selection.start as isize
 4647                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4648                                    - selection.start as isize,
 4649                        );
 4650                        old_range.clone()
 4651                    } else {
 4652                        s.start..s.end
 4653                    }
 4654                }));
 4655                break;
 4656            }
 4657            if !self.linked_edit_ranges.is_empty() {
 4658                let start_anchor = snapshot.anchor_before(selection.head());
 4659                let end_anchor = snapshot.anchor_after(selection.tail());
 4660                if let Some(ranges) = self
 4661                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4662                {
 4663                    for (buffer, edits) in ranges {
 4664                        linked_edits.entry(buffer.clone()).or_default().extend(
 4665                            edits
 4666                                .into_iter()
 4667                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4668                        );
 4669                    }
 4670                }
 4671            }
 4672        }
 4673        let text = &text[common_prefix_len..];
 4674
 4675        cx.emit(EditorEvent::InputHandled {
 4676            utf16_range_to_replace: range_to_replace,
 4677            text: text.into(),
 4678        });
 4679
 4680        self.transact(cx, |this, cx| {
 4681            if let Some(mut snippet) = snippet {
 4682                snippet.text = text.to_string();
 4683                for tabstop in snippet
 4684                    .tabstops
 4685                    .iter_mut()
 4686                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4687                {
 4688                    tabstop.start -= common_prefix_len as isize;
 4689                    tabstop.end -= common_prefix_len as isize;
 4690                }
 4691
 4692                this.insert_snippet(&ranges, snippet, cx).log_err();
 4693            } else {
 4694                this.buffer.update(cx, |buffer, cx| {
 4695                    buffer.edit(
 4696                        ranges.iter().map(|range| (range.clone(), text)),
 4697                        this.autoindent_mode.clone(),
 4698                        cx,
 4699                    );
 4700                });
 4701            }
 4702            for (buffer, edits) in linked_edits {
 4703                buffer.update(cx, |buffer, cx| {
 4704                    let snapshot = buffer.snapshot();
 4705                    let edits = edits
 4706                        .into_iter()
 4707                        .map(|(range, text)| {
 4708                            use text::ToPoint as TP;
 4709                            let end_point = TP::to_point(&range.end, &snapshot);
 4710                            let start_point = TP::to_point(&range.start, &snapshot);
 4711                            (start_point..end_point, text)
 4712                        })
 4713                        .sorted_by_key(|(range, _)| range.start)
 4714                        .collect::<Vec<_>>();
 4715                    buffer.edit(edits, None, cx);
 4716                })
 4717            }
 4718
 4719            this.refresh_inline_completion(true, false, cx);
 4720        });
 4721
 4722        let show_new_completions_on_confirm = completion
 4723            .confirm
 4724            .as_ref()
 4725            .map_or(false, |confirm| confirm(intent, cx));
 4726        if show_new_completions_on_confirm {
 4727            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4728        }
 4729
 4730        let provider = self.completion_provider.as_ref()?;
 4731        let apply_edits = provider.apply_additional_edits_for_completion(
 4732            buffer_handle,
 4733            completion.clone(),
 4734            true,
 4735            cx,
 4736        );
 4737
 4738        let editor_settings = EditorSettings::get_global(cx);
 4739        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4740            // After the code completion is finished, users often want to know what signatures are needed.
 4741            // so we should automatically call signature_help
 4742            self.show_signature_help(&ShowSignatureHelp, cx);
 4743        }
 4744
 4745        Some(cx.foreground_executor().spawn(async move {
 4746            apply_edits.await?;
 4747            Ok(())
 4748        }))
 4749    }
 4750
 4751    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4752        let mut context_menu = self.context_menu.write();
 4753        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4754            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4755                // Toggle if we're selecting the same one
 4756                *context_menu = None;
 4757                cx.notify();
 4758                return;
 4759            } else {
 4760                // Otherwise, clear it and start a new one
 4761                *context_menu = None;
 4762                cx.notify();
 4763            }
 4764        }
 4765        drop(context_menu);
 4766        let snapshot = self.snapshot(cx);
 4767        let deployed_from_indicator = action.deployed_from_indicator;
 4768        let mut task = self.code_actions_task.take();
 4769        let action = action.clone();
 4770        cx.spawn(|editor, mut cx| async move {
 4771            while let Some(prev_task) = task {
 4772                prev_task.await.log_err();
 4773                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4774            }
 4775
 4776            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4777                if editor.focus_handle.is_focused(cx) {
 4778                    let multibuffer_point = action
 4779                        .deployed_from_indicator
 4780                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4781                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4782                    let (buffer, buffer_row) = snapshot
 4783                        .buffer_snapshot
 4784                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4785                        .and_then(|(buffer_snapshot, range)| {
 4786                            editor
 4787                                .buffer
 4788                                .read(cx)
 4789                                .buffer(buffer_snapshot.remote_id())
 4790                                .map(|buffer| (buffer, range.start.row))
 4791                        })?;
 4792                    let (_, code_actions) = editor
 4793                        .available_code_actions
 4794                        .clone()
 4795                        .and_then(|(location, code_actions)| {
 4796                            let snapshot = location.buffer.read(cx).snapshot();
 4797                            let point_range = location.range.to_point(&snapshot);
 4798                            let point_range = point_range.start.row..=point_range.end.row;
 4799                            if point_range.contains(&buffer_row) {
 4800                                Some((location, code_actions))
 4801                            } else {
 4802                                None
 4803                            }
 4804                        })
 4805                        .unzip();
 4806                    let buffer_id = buffer.read(cx).remote_id();
 4807                    let tasks = editor
 4808                        .tasks
 4809                        .get(&(buffer_id, buffer_row))
 4810                        .map(|t| Arc::new(t.to_owned()));
 4811                    if tasks.is_none() && code_actions.is_none() {
 4812                        return None;
 4813                    }
 4814
 4815                    editor.completion_tasks.clear();
 4816                    editor.discard_inline_completion(false, cx);
 4817                    let task_context =
 4818                        tasks
 4819                            .as_ref()
 4820                            .zip(editor.project.clone())
 4821                            .map(|(tasks, project)| {
 4822                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4823                            });
 4824
 4825                    Some(cx.spawn(|editor, mut cx| async move {
 4826                        let task_context = match task_context {
 4827                            Some(task_context) => task_context.await,
 4828                            None => None,
 4829                        };
 4830                        let resolved_tasks =
 4831                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4832                                Arc::new(ResolvedTasks {
 4833                                    templates: tasks.resolve(&task_context).collect(),
 4834                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4835                                        multibuffer_point.row,
 4836                                        tasks.column,
 4837                                    )),
 4838                                })
 4839                            });
 4840                        let spawn_straight_away = resolved_tasks
 4841                            .as_ref()
 4842                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4843                            && code_actions
 4844                                .as_ref()
 4845                                .map_or(true, |actions| actions.is_empty());
 4846                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4847                            *editor.context_menu.write() =
 4848                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4849                                    buffer,
 4850                                    actions: CodeActionContents {
 4851                                        tasks: resolved_tasks,
 4852                                        actions: code_actions,
 4853                                    },
 4854                                    selected_item: Default::default(),
 4855                                    scroll_handle: UniformListScrollHandle::default(),
 4856                                    deployed_from_indicator,
 4857                                }));
 4858                            if spawn_straight_away {
 4859                                if let Some(task) = editor.confirm_code_action(
 4860                                    &ConfirmCodeAction { item_ix: Some(0) },
 4861                                    cx,
 4862                                ) {
 4863                                    cx.notify();
 4864                                    return task;
 4865                                }
 4866                            }
 4867                            cx.notify();
 4868                            Task::ready(Ok(()))
 4869                        }) {
 4870                            task.await
 4871                        } else {
 4872                            Ok(())
 4873                        }
 4874                    }))
 4875                } else {
 4876                    Some(Task::ready(Ok(())))
 4877                }
 4878            })?;
 4879            if let Some(task) = spawned_test_task {
 4880                task.await?;
 4881            }
 4882
 4883            Ok::<_, anyhow::Error>(())
 4884        })
 4885        .detach_and_log_err(cx);
 4886    }
 4887
 4888    pub fn confirm_code_action(
 4889        &mut self,
 4890        action: &ConfirmCodeAction,
 4891        cx: &mut ViewContext<Self>,
 4892    ) -> Option<Task<Result<()>>> {
 4893        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4894            menu
 4895        } else {
 4896            return None;
 4897        };
 4898        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4899        let action = actions_menu.actions.get(action_ix)?;
 4900        let title = action.label();
 4901        let buffer = actions_menu.buffer;
 4902        let workspace = self.workspace()?;
 4903
 4904        match action {
 4905            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4906                workspace.update(cx, |workspace, cx| {
 4907                    workspace::tasks::schedule_resolved_task(
 4908                        workspace,
 4909                        task_source_kind,
 4910                        resolved_task,
 4911                        false,
 4912                        cx,
 4913                    );
 4914
 4915                    Some(Task::ready(Ok(())))
 4916                })
 4917            }
 4918            CodeActionsItem::CodeAction {
 4919                excerpt_id,
 4920                action,
 4921                provider,
 4922            } => {
 4923                let apply_code_action =
 4924                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4925                let workspace = workspace.downgrade();
 4926                Some(cx.spawn(|editor, cx| async move {
 4927                    let project_transaction = apply_code_action.await?;
 4928                    Self::open_project_transaction(
 4929                        &editor,
 4930                        workspace,
 4931                        project_transaction,
 4932                        title,
 4933                        cx,
 4934                    )
 4935                    .await
 4936                }))
 4937            }
 4938        }
 4939    }
 4940
 4941    pub async fn open_project_transaction(
 4942        this: &WeakView<Editor>,
 4943        workspace: WeakView<Workspace>,
 4944        transaction: ProjectTransaction,
 4945        title: String,
 4946        mut cx: AsyncWindowContext,
 4947    ) -> Result<()> {
 4948        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4949        cx.update(|cx| {
 4950            entries.sort_unstable_by_key(|(buffer, _)| {
 4951                buffer.read(cx).file().map(|f| f.path().clone())
 4952            });
 4953        })?;
 4954
 4955        // If the project transaction's edits are all contained within this editor, then
 4956        // avoid opening a new editor to display them.
 4957
 4958        if let Some((buffer, transaction)) = entries.first() {
 4959            if entries.len() == 1 {
 4960                let excerpt = this.update(&mut cx, |editor, cx| {
 4961                    editor
 4962                        .buffer()
 4963                        .read(cx)
 4964                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4965                })?;
 4966                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4967                    if excerpted_buffer == *buffer {
 4968                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4969                            let excerpt_range = excerpt_range.to_offset(buffer);
 4970                            buffer
 4971                                .edited_ranges_for_transaction::<usize>(transaction)
 4972                                .all(|range| {
 4973                                    excerpt_range.start <= range.start
 4974                                        && excerpt_range.end >= range.end
 4975                                })
 4976                        })?;
 4977
 4978                        if all_edits_within_excerpt {
 4979                            return Ok(());
 4980                        }
 4981                    }
 4982                }
 4983            }
 4984        } else {
 4985            return Ok(());
 4986        }
 4987
 4988        let mut ranges_to_highlight = Vec::new();
 4989        let excerpt_buffer = cx.new_model(|cx| {
 4990            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4991            for (buffer_handle, transaction) in &entries {
 4992                let buffer = buffer_handle.read(cx);
 4993                ranges_to_highlight.extend(
 4994                    multibuffer.push_excerpts_with_context_lines(
 4995                        buffer_handle.clone(),
 4996                        buffer
 4997                            .edited_ranges_for_transaction::<usize>(transaction)
 4998                            .collect(),
 4999                        DEFAULT_MULTIBUFFER_CONTEXT,
 5000                        cx,
 5001                    ),
 5002                );
 5003            }
 5004            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5005            multibuffer
 5006        })?;
 5007
 5008        workspace.update(&mut cx, |workspace, cx| {
 5009            let project = workspace.project().clone();
 5010            let editor =
 5011                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5012            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5013            editor.update(cx, |editor, cx| {
 5014                editor.highlight_background::<Self>(
 5015                    &ranges_to_highlight,
 5016                    |theme| theme.editor_highlighted_line_background,
 5017                    cx,
 5018                );
 5019            });
 5020        })?;
 5021
 5022        Ok(())
 5023    }
 5024
 5025    pub fn clear_code_action_providers(&mut self) {
 5026        self.code_action_providers.clear();
 5027        self.available_code_actions.take();
 5028    }
 5029
 5030    pub fn push_code_action_provider(
 5031        &mut self,
 5032        provider: Arc<dyn CodeActionProvider>,
 5033        cx: &mut ViewContext<Self>,
 5034    ) {
 5035        self.code_action_providers.push(provider);
 5036        self.refresh_code_actions(cx);
 5037    }
 5038
 5039    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5040        let buffer = self.buffer.read(cx);
 5041        let newest_selection = self.selections.newest_anchor().clone();
 5042        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5043        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5044        if start_buffer != end_buffer {
 5045            return None;
 5046        }
 5047
 5048        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5049            cx.background_executor()
 5050                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5051                .await;
 5052
 5053            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5054                let providers = this.code_action_providers.clone();
 5055                let tasks = this
 5056                    .code_action_providers
 5057                    .iter()
 5058                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5059                    .collect::<Vec<_>>();
 5060                (providers, tasks)
 5061            })?;
 5062
 5063            let mut actions = Vec::new();
 5064            for (provider, provider_actions) in
 5065                providers.into_iter().zip(future::join_all(tasks).await)
 5066            {
 5067                if let Some(provider_actions) = provider_actions.log_err() {
 5068                    actions.extend(provider_actions.into_iter().map(|action| {
 5069                        AvailableCodeAction {
 5070                            excerpt_id: newest_selection.start.excerpt_id,
 5071                            action,
 5072                            provider: provider.clone(),
 5073                        }
 5074                    }));
 5075                }
 5076            }
 5077
 5078            this.update(&mut cx, |this, cx| {
 5079                this.available_code_actions = if actions.is_empty() {
 5080                    None
 5081                } else {
 5082                    Some((
 5083                        Location {
 5084                            buffer: start_buffer,
 5085                            range: start..end,
 5086                        },
 5087                        actions.into(),
 5088                    ))
 5089                };
 5090                cx.notify();
 5091            })
 5092        }));
 5093        None
 5094    }
 5095
 5096    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5097        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5098            self.show_git_blame_inline = false;
 5099
 5100            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5101                cx.background_executor().timer(delay).await;
 5102
 5103                this.update(&mut cx, |this, cx| {
 5104                    this.show_git_blame_inline = true;
 5105                    cx.notify();
 5106                })
 5107                .log_err();
 5108            }));
 5109        }
 5110    }
 5111
 5112    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5113        if self.pending_rename.is_some() {
 5114            return None;
 5115        }
 5116
 5117        let provider = self.semantics_provider.clone()?;
 5118        let buffer = self.buffer.read(cx);
 5119        let newest_selection = self.selections.newest_anchor().clone();
 5120        let cursor_position = newest_selection.head();
 5121        let (cursor_buffer, cursor_buffer_position) =
 5122            buffer.text_anchor_for_position(cursor_position, cx)?;
 5123        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5124        if cursor_buffer != tail_buffer {
 5125            return None;
 5126        }
 5127
 5128        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5129            cx.background_executor()
 5130                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5131                .await;
 5132
 5133            let highlights = if let Some(highlights) = cx
 5134                .update(|cx| {
 5135                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5136                })
 5137                .ok()
 5138                .flatten()
 5139            {
 5140                highlights.await.log_err()
 5141            } else {
 5142                None
 5143            };
 5144
 5145            if let Some(highlights) = highlights {
 5146                this.update(&mut cx, |this, cx| {
 5147                    if this.pending_rename.is_some() {
 5148                        return;
 5149                    }
 5150
 5151                    let buffer_id = cursor_position.buffer_id;
 5152                    let buffer = this.buffer.read(cx);
 5153                    if !buffer
 5154                        .text_anchor_for_position(cursor_position, cx)
 5155                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5156                    {
 5157                        return;
 5158                    }
 5159
 5160                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5161                    let mut write_ranges = Vec::new();
 5162                    let mut read_ranges = Vec::new();
 5163                    for highlight in highlights {
 5164                        for (excerpt_id, excerpt_range) in
 5165                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5166                        {
 5167                            let start = highlight
 5168                                .range
 5169                                .start
 5170                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5171                            let end = highlight
 5172                                .range
 5173                                .end
 5174                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5175                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5176                                continue;
 5177                            }
 5178
 5179                            let range = Anchor {
 5180                                buffer_id,
 5181                                excerpt_id,
 5182                                text_anchor: start,
 5183                            }..Anchor {
 5184                                buffer_id,
 5185                                excerpt_id,
 5186                                text_anchor: end,
 5187                            };
 5188                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5189                                write_ranges.push(range);
 5190                            } else {
 5191                                read_ranges.push(range);
 5192                            }
 5193                        }
 5194                    }
 5195
 5196                    this.highlight_background::<DocumentHighlightRead>(
 5197                        &read_ranges,
 5198                        |theme| theme.editor_document_highlight_read_background,
 5199                        cx,
 5200                    );
 5201                    this.highlight_background::<DocumentHighlightWrite>(
 5202                        &write_ranges,
 5203                        |theme| theme.editor_document_highlight_write_background,
 5204                        cx,
 5205                    );
 5206                    cx.notify();
 5207                })
 5208                .log_err();
 5209            }
 5210        }));
 5211        None
 5212    }
 5213
 5214    pub fn refresh_inline_completion(
 5215        &mut self,
 5216        debounce: bool,
 5217        user_requested: bool,
 5218        cx: &mut ViewContext<Self>,
 5219    ) -> Option<()> {
 5220        let provider = self.inline_completion_provider()?;
 5221        let cursor = self.selections.newest_anchor().head();
 5222        let (buffer, cursor_buffer_position) =
 5223            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5224
 5225        if !user_requested
 5226            && (!self.enable_inline_completions
 5227                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5228        {
 5229            self.discard_inline_completion(false, cx);
 5230            return None;
 5231        }
 5232
 5233        self.update_visible_inline_completion(cx);
 5234        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5235        Some(())
 5236    }
 5237
 5238    fn cycle_inline_completion(
 5239        &mut self,
 5240        direction: Direction,
 5241        cx: &mut ViewContext<Self>,
 5242    ) -> Option<()> {
 5243        let provider = self.inline_completion_provider()?;
 5244        let cursor = self.selections.newest_anchor().head();
 5245        let (buffer, cursor_buffer_position) =
 5246            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5247        if !self.enable_inline_completions
 5248            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5249        {
 5250            return None;
 5251        }
 5252
 5253        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5254        self.update_visible_inline_completion(cx);
 5255
 5256        Some(())
 5257    }
 5258
 5259    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5260        if !self.has_active_inline_completion(cx) {
 5261            self.refresh_inline_completion(false, true, cx);
 5262            return;
 5263        }
 5264
 5265        self.update_visible_inline_completion(cx);
 5266    }
 5267
 5268    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5269        self.show_cursor_names(cx);
 5270    }
 5271
 5272    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5273        self.show_cursor_names = true;
 5274        cx.notify();
 5275        cx.spawn(|this, mut cx| async move {
 5276            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5277            this.update(&mut cx, |this, cx| {
 5278                this.show_cursor_names = false;
 5279                cx.notify()
 5280            })
 5281            .ok()
 5282        })
 5283        .detach();
 5284    }
 5285
 5286    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5287        if self.has_active_inline_completion(cx) {
 5288            self.cycle_inline_completion(Direction::Next, cx);
 5289        } else {
 5290            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5291            if is_copilot_disabled {
 5292                cx.propagate();
 5293            }
 5294        }
 5295    }
 5296
 5297    pub fn previous_inline_completion(
 5298        &mut self,
 5299        _: &PreviousInlineCompletion,
 5300        cx: &mut ViewContext<Self>,
 5301    ) {
 5302        if self.has_active_inline_completion(cx) {
 5303            self.cycle_inline_completion(Direction::Prev, cx);
 5304        } else {
 5305            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5306            if is_copilot_disabled {
 5307                cx.propagate();
 5308            }
 5309        }
 5310    }
 5311
 5312    pub fn accept_inline_completion(
 5313        &mut self,
 5314        _: &AcceptInlineCompletion,
 5315        cx: &mut ViewContext<Self>,
 5316    ) {
 5317        let Some(completion) = self.take_active_inline_completion(cx) else {
 5318            return;
 5319        };
 5320        if let Some(provider) = self.inline_completion_provider() {
 5321            provider.accept(cx);
 5322        }
 5323
 5324        cx.emit(EditorEvent::InputHandled {
 5325            utf16_range_to_replace: None,
 5326            text: completion.text.to_string().into(),
 5327        });
 5328
 5329        if let Some(range) = completion.delete_range {
 5330            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5331        }
 5332        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5333        self.refresh_inline_completion(true, true, cx);
 5334        cx.notify();
 5335    }
 5336
 5337    pub fn accept_partial_inline_completion(
 5338        &mut self,
 5339        _: &AcceptPartialInlineCompletion,
 5340        cx: &mut ViewContext<Self>,
 5341    ) {
 5342        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5343            if let Some(completion) = self.take_active_inline_completion(cx) {
 5344                let mut partial_completion = completion
 5345                    .text
 5346                    .chars()
 5347                    .by_ref()
 5348                    .take_while(|c| c.is_alphabetic())
 5349                    .collect::<String>();
 5350                if partial_completion.is_empty() {
 5351                    partial_completion = completion
 5352                        .text
 5353                        .chars()
 5354                        .by_ref()
 5355                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5356                        .collect::<String>();
 5357                }
 5358
 5359                cx.emit(EditorEvent::InputHandled {
 5360                    utf16_range_to_replace: None,
 5361                    text: partial_completion.clone().into(),
 5362                });
 5363
 5364                if let Some(range) = completion.delete_range {
 5365                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5366                }
 5367                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5368
 5369                self.refresh_inline_completion(true, true, cx);
 5370                cx.notify();
 5371            }
 5372        }
 5373    }
 5374
 5375    fn discard_inline_completion(
 5376        &mut self,
 5377        should_report_inline_completion_event: bool,
 5378        cx: &mut ViewContext<Self>,
 5379    ) -> bool {
 5380        if let Some(provider) = self.inline_completion_provider() {
 5381            provider.discard(should_report_inline_completion_event, cx);
 5382        }
 5383
 5384        self.take_active_inline_completion(cx).is_some()
 5385    }
 5386
 5387    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5388        if let Some(completion) = self.active_inline_completion.as_ref() {
 5389            let buffer = self.buffer.read(cx).read(cx);
 5390            completion.position.is_valid(&buffer)
 5391        } else {
 5392            false
 5393        }
 5394    }
 5395
 5396    fn take_active_inline_completion(
 5397        &mut self,
 5398        cx: &mut ViewContext<Self>,
 5399    ) -> Option<CompletionState> {
 5400        let completion = self.active_inline_completion.take()?;
 5401        let render_inlay_ids = completion.render_inlay_ids.clone();
 5402        self.display_map.update(cx, |map, cx| {
 5403            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5404        });
 5405        let buffer = self.buffer.read(cx).read(cx);
 5406
 5407        if completion.position.is_valid(&buffer) {
 5408            Some(completion)
 5409        } else {
 5410            None
 5411        }
 5412    }
 5413
 5414    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5415        let selection = self.selections.newest_anchor();
 5416        let cursor = selection.head();
 5417
 5418        let excerpt_id = cursor.excerpt_id;
 5419
 5420        if self.context_menu.read().is_none()
 5421            && self.completion_tasks.is_empty()
 5422            && selection.start == selection.end
 5423        {
 5424            if let Some(provider) = self.inline_completion_provider() {
 5425                if let Some((buffer, cursor_buffer_position)) =
 5426                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5427                {
 5428                    if let Some(proposal) =
 5429                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5430                    {
 5431                        let mut to_remove = Vec::new();
 5432                        if let Some(completion) = self.active_inline_completion.take() {
 5433                            to_remove.extend(completion.render_inlay_ids.iter());
 5434                        }
 5435
 5436                        let to_add = proposal
 5437                            .inlays
 5438                            .iter()
 5439                            .filter_map(|inlay| {
 5440                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5441                                let id = post_inc(&mut self.next_inlay_id);
 5442                                match inlay {
 5443                                    InlayProposal::Hint(position, hint) => {
 5444                                        let position =
 5445                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5446                                        Some(Inlay::hint(id, position, hint))
 5447                                    }
 5448                                    InlayProposal::Suggestion(position, text) => {
 5449                                        let position =
 5450                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5451                                        Some(Inlay::suggestion(id, position, text.clone()))
 5452                                    }
 5453                                }
 5454                            })
 5455                            .collect_vec();
 5456
 5457                        self.active_inline_completion = Some(CompletionState {
 5458                            position: cursor,
 5459                            text: proposal.text,
 5460                            delete_range: proposal.delete_range.and_then(|range| {
 5461                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5462                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5463                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5464                                Some(start?..end?)
 5465                            }),
 5466                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5467                        });
 5468
 5469                        self.display_map
 5470                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5471
 5472                        cx.notify();
 5473                        return;
 5474                    }
 5475                }
 5476            }
 5477        }
 5478
 5479        self.discard_inline_completion(false, cx);
 5480    }
 5481
 5482    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5483        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5484    }
 5485
 5486    fn render_code_actions_indicator(
 5487        &self,
 5488        _style: &EditorStyle,
 5489        row: DisplayRow,
 5490        is_active: bool,
 5491        cx: &mut ViewContext<Self>,
 5492    ) -> Option<IconButton> {
 5493        if self.available_code_actions.is_some() {
 5494            Some(
 5495                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5496                    .shape(ui::IconButtonShape::Square)
 5497                    .icon_size(IconSize::XSmall)
 5498                    .icon_color(Color::Muted)
 5499                    .selected(is_active)
 5500                    .tooltip({
 5501                        let focus_handle = self.focus_handle.clone();
 5502                        move |cx| {
 5503                            Tooltip::for_action_in(
 5504                                "Toggle Code Actions",
 5505                                &ToggleCodeActions {
 5506                                    deployed_from_indicator: None,
 5507                                },
 5508                                &focus_handle,
 5509                                cx,
 5510                            )
 5511                        }
 5512                    })
 5513                    .on_click(cx.listener(move |editor, _e, cx| {
 5514                        editor.focus(cx);
 5515                        editor.toggle_code_actions(
 5516                            &ToggleCodeActions {
 5517                                deployed_from_indicator: Some(row),
 5518                            },
 5519                            cx,
 5520                        );
 5521                    })),
 5522            )
 5523        } else {
 5524            None
 5525        }
 5526    }
 5527
 5528    fn clear_tasks(&mut self) {
 5529        self.tasks.clear()
 5530    }
 5531
 5532    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5533        if self.tasks.insert(key, value).is_some() {
 5534            // This case should hopefully be rare, but just in case...
 5535            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5536        }
 5537    }
 5538
 5539    fn build_tasks_context(
 5540        project: &Model<Project>,
 5541        buffer: &Model<Buffer>,
 5542        buffer_row: u32,
 5543        tasks: &Arc<RunnableTasks>,
 5544        cx: &mut ViewContext<Self>,
 5545    ) -> Task<Option<task::TaskContext>> {
 5546        let position = Point::new(buffer_row, tasks.column);
 5547        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5548        let location = Location {
 5549            buffer: buffer.clone(),
 5550            range: range_start..range_start,
 5551        };
 5552        // Fill in the environmental variables from the tree-sitter captures
 5553        let mut captured_task_variables = TaskVariables::default();
 5554        for (capture_name, value) in tasks.extra_variables.clone() {
 5555            captured_task_variables.insert(
 5556                task::VariableName::Custom(capture_name.into()),
 5557                value.clone(),
 5558            );
 5559        }
 5560        project.update(cx, |project, cx| {
 5561            project.task_store().update(cx, |task_store, cx| {
 5562                task_store.task_context_for_location(captured_task_variables, location, cx)
 5563            })
 5564        })
 5565    }
 5566
 5567    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5568        let Some((workspace, _)) = self.workspace.clone() else {
 5569            return;
 5570        };
 5571        let Some(project) = self.project.clone() else {
 5572            return;
 5573        };
 5574
 5575        // Try to find a closest, enclosing node using tree-sitter that has a
 5576        // task
 5577        let Some((buffer, buffer_row, tasks)) = self
 5578            .find_enclosing_node_task(cx)
 5579            // Or find the task that's closest in row-distance.
 5580            .or_else(|| self.find_closest_task(cx))
 5581        else {
 5582            return;
 5583        };
 5584
 5585        let reveal_strategy = action.reveal;
 5586        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5587        cx.spawn(|_, mut cx| async move {
 5588            let context = task_context.await?;
 5589            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5590
 5591            let resolved = resolved_task.resolved.as_mut()?;
 5592            resolved.reveal = reveal_strategy;
 5593
 5594            workspace
 5595                .update(&mut cx, |workspace, cx| {
 5596                    workspace::tasks::schedule_resolved_task(
 5597                        workspace,
 5598                        task_source_kind,
 5599                        resolved_task,
 5600                        false,
 5601                        cx,
 5602                    );
 5603                })
 5604                .ok()
 5605        })
 5606        .detach();
 5607    }
 5608
 5609    fn find_closest_task(
 5610        &mut self,
 5611        cx: &mut ViewContext<Self>,
 5612    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5613        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5614
 5615        let ((buffer_id, row), tasks) = self
 5616            .tasks
 5617            .iter()
 5618            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5619
 5620        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5621        let tasks = Arc::new(tasks.to_owned());
 5622        Some((buffer, *row, tasks))
 5623    }
 5624
 5625    fn find_enclosing_node_task(
 5626        &mut self,
 5627        cx: &mut ViewContext<Self>,
 5628    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5629        let snapshot = self.buffer.read(cx).snapshot(cx);
 5630        let offset = self.selections.newest::<usize>(cx).head();
 5631        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5632        let buffer_id = excerpt.buffer().remote_id();
 5633
 5634        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5635        let mut cursor = layer.node().walk();
 5636
 5637        while cursor.goto_first_child_for_byte(offset).is_some() {
 5638            if cursor.node().end_byte() == offset {
 5639                cursor.goto_next_sibling();
 5640            }
 5641        }
 5642
 5643        // Ascend to the smallest ancestor that contains the range and has a task.
 5644        loop {
 5645            let node = cursor.node();
 5646            let node_range = node.byte_range();
 5647            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5648
 5649            // Check if this node contains our offset
 5650            if node_range.start <= offset && node_range.end >= offset {
 5651                // If it contains offset, check for task
 5652                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5653                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5654                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5655                }
 5656            }
 5657
 5658            if !cursor.goto_parent() {
 5659                break;
 5660            }
 5661        }
 5662        None
 5663    }
 5664
 5665    fn render_run_indicator(
 5666        &self,
 5667        _style: &EditorStyle,
 5668        is_active: bool,
 5669        row: DisplayRow,
 5670        cx: &mut ViewContext<Self>,
 5671    ) -> IconButton {
 5672        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5673            .shape(ui::IconButtonShape::Square)
 5674            .icon_size(IconSize::XSmall)
 5675            .icon_color(Color::Muted)
 5676            .selected(is_active)
 5677            .on_click(cx.listener(move |editor, _e, cx| {
 5678                editor.focus(cx);
 5679                editor.toggle_code_actions(
 5680                    &ToggleCodeActions {
 5681                        deployed_from_indicator: Some(row),
 5682                    },
 5683                    cx,
 5684                );
 5685            }))
 5686    }
 5687
 5688    pub fn context_menu_visible(&self) -> bool {
 5689        self.context_menu
 5690            .read()
 5691            .as_ref()
 5692            .map_or(false, |menu| menu.visible())
 5693    }
 5694
 5695    fn render_context_menu(
 5696        &self,
 5697        cursor_position: DisplayPoint,
 5698        style: &EditorStyle,
 5699        max_height: Pixels,
 5700        cx: &mut ViewContext<Editor>,
 5701    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5702        self.context_menu.read().as_ref().map(|menu| {
 5703            menu.render(
 5704                cursor_position,
 5705                style,
 5706                max_height,
 5707                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5708                cx,
 5709            )
 5710        })
 5711    }
 5712
 5713    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5714        cx.notify();
 5715        self.completion_tasks.clear();
 5716        let context_menu = self.context_menu.write().take();
 5717        if context_menu.is_some() {
 5718            self.update_visible_inline_completion(cx);
 5719        }
 5720        context_menu
 5721    }
 5722
 5723    fn show_snippet_choices(
 5724        &mut self,
 5725        choices: &Vec<String>,
 5726        selection: Range<Anchor>,
 5727        cx: &mut ViewContext<Self>,
 5728    ) {
 5729        if selection.start.buffer_id.is_none() {
 5730            return;
 5731        }
 5732        let buffer_id = selection.start.buffer_id.unwrap();
 5733        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5734        let id = post_inc(&mut self.next_completion_id);
 5735
 5736        if let Some(buffer) = buffer {
 5737            *self.context_menu.write() = Some(ContextMenu::Completions(
 5738                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
 5739                    .suppress_documentation_resolution(),
 5740            ));
 5741        }
 5742    }
 5743
 5744    pub fn insert_snippet(
 5745        &mut self,
 5746        insertion_ranges: &[Range<usize>],
 5747        snippet: Snippet,
 5748        cx: &mut ViewContext<Self>,
 5749    ) -> Result<()> {
 5750        struct Tabstop<T> {
 5751            is_end_tabstop: bool,
 5752            ranges: Vec<Range<T>>,
 5753            choices: Option<Vec<String>>,
 5754        }
 5755
 5756        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5757            let snippet_text: Arc<str> = snippet.text.clone().into();
 5758            buffer.edit(
 5759                insertion_ranges
 5760                    .iter()
 5761                    .cloned()
 5762                    .map(|range| (range, snippet_text.clone())),
 5763                Some(AutoindentMode::EachLine),
 5764                cx,
 5765            );
 5766
 5767            let snapshot = &*buffer.read(cx);
 5768            let snippet = &snippet;
 5769            snippet
 5770                .tabstops
 5771                .iter()
 5772                .map(|tabstop| {
 5773                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5774                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5775                    });
 5776                    let mut tabstop_ranges = tabstop
 5777                        .ranges
 5778                        .iter()
 5779                        .flat_map(|tabstop_range| {
 5780                            let mut delta = 0_isize;
 5781                            insertion_ranges.iter().map(move |insertion_range| {
 5782                                let insertion_start = insertion_range.start as isize + delta;
 5783                                delta +=
 5784                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5785
 5786                                let start = ((insertion_start + tabstop_range.start) as usize)
 5787                                    .min(snapshot.len());
 5788                                let end = ((insertion_start + tabstop_range.end) as usize)
 5789                                    .min(snapshot.len());
 5790                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5791                            })
 5792                        })
 5793                        .collect::<Vec<_>>();
 5794                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5795
 5796                    Tabstop {
 5797                        is_end_tabstop,
 5798                        ranges: tabstop_ranges,
 5799                        choices: tabstop.choices.clone(),
 5800                    }
 5801                })
 5802                .collect::<Vec<_>>()
 5803        });
 5804        if let Some(tabstop) = tabstops.first() {
 5805            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5806                s.select_ranges(tabstop.ranges.iter().cloned());
 5807            });
 5808
 5809            if let Some(choices) = &tabstop.choices {
 5810                if let Some(selection) = tabstop.ranges.first() {
 5811                    self.show_snippet_choices(choices, selection.clone(), cx)
 5812                }
 5813            }
 5814
 5815            // If we're already at the last tabstop and it's at the end of the snippet,
 5816            // we're done, we don't need to keep the state around.
 5817            if !tabstop.is_end_tabstop {
 5818                let choices = tabstops
 5819                    .iter()
 5820                    .map(|tabstop| tabstop.choices.clone())
 5821                    .collect();
 5822
 5823                let ranges = tabstops
 5824                    .into_iter()
 5825                    .map(|tabstop| tabstop.ranges)
 5826                    .collect::<Vec<_>>();
 5827
 5828                self.snippet_stack.push(SnippetState {
 5829                    active_index: 0,
 5830                    ranges,
 5831                    choices,
 5832                });
 5833            }
 5834
 5835            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5836            if self.autoclose_regions.is_empty() {
 5837                let snapshot = self.buffer.read(cx).snapshot(cx);
 5838                for selection in &mut self.selections.all::<Point>(cx) {
 5839                    let selection_head = selection.head();
 5840                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5841                        continue;
 5842                    };
 5843
 5844                    let mut bracket_pair = None;
 5845                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5846                    let prev_chars = snapshot
 5847                        .reversed_chars_at(selection_head)
 5848                        .collect::<String>();
 5849                    for (pair, enabled) in scope.brackets() {
 5850                        if enabled
 5851                            && pair.close
 5852                            && prev_chars.starts_with(pair.start.as_str())
 5853                            && next_chars.starts_with(pair.end.as_str())
 5854                        {
 5855                            bracket_pair = Some(pair.clone());
 5856                            break;
 5857                        }
 5858                    }
 5859                    if let Some(pair) = bracket_pair {
 5860                        let start = snapshot.anchor_after(selection_head);
 5861                        let end = snapshot.anchor_after(selection_head);
 5862                        self.autoclose_regions.push(AutocloseRegion {
 5863                            selection_id: selection.id,
 5864                            range: start..end,
 5865                            pair,
 5866                        });
 5867                    }
 5868                }
 5869            }
 5870        }
 5871        Ok(())
 5872    }
 5873
 5874    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5875        self.move_to_snippet_tabstop(Bias::Right, cx)
 5876    }
 5877
 5878    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5879        self.move_to_snippet_tabstop(Bias::Left, cx)
 5880    }
 5881
 5882    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5883        if let Some(mut snippet) = self.snippet_stack.pop() {
 5884            match bias {
 5885                Bias::Left => {
 5886                    if snippet.active_index > 0 {
 5887                        snippet.active_index -= 1;
 5888                    } else {
 5889                        self.snippet_stack.push(snippet);
 5890                        return false;
 5891                    }
 5892                }
 5893                Bias::Right => {
 5894                    if snippet.active_index + 1 < snippet.ranges.len() {
 5895                        snippet.active_index += 1;
 5896                    } else {
 5897                        self.snippet_stack.push(snippet);
 5898                        return false;
 5899                    }
 5900                }
 5901            }
 5902            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5903                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5904                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5905                });
 5906
 5907                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5908                    if let Some(selection) = current_ranges.first() {
 5909                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5910                    }
 5911                }
 5912
 5913                // If snippet state is not at the last tabstop, push it back on the stack
 5914                if snippet.active_index + 1 < snippet.ranges.len() {
 5915                    self.snippet_stack.push(snippet);
 5916                }
 5917                return true;
 5918            }
 5919        }
 5920
 5921        false
 5922    }
 5923
 5924    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5925        self.transact(cx, |this, cx| {
 5926            this.select_all(&SelectAll, cx);
 5927            this.insert("", cx);
 5928        });
 5929    }
 5930
 5931    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5932        self.transact(cx, |this, cx| {
 5933            this.select_autoclose_pair(cx);
 5934            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5935            if !this.linked_edit_ranges.is_empty() {
 5936                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5937                let snapshot = this.buffer.read(cx).snapshot(cx);
 5938
 5939                for selection in selections.iter() {
 5940                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5941                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5942                    if selection_start.buffer_id != selection_end.buffer_id {
 5943                        continue;
 5944                    }
 5945                    if let Some(ranges) =
 5946                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5947                    {
 5948                        for (buffer, entries) in ranges {
 5949                            linked_ranges.entry(buffer).or_default().extend(entries);
 5950                        }
 5951                    }
 5952                }
 5953            }
 5954
 5955            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5956            if !this.selections.line_mode {
 5957                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5958                for selection in &mut selections {
 5959                    if selection.is_empty() {
 5960                        let old_head = selection.head();
 5961                        let mut new_head =
 5962                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5963                                .to_point(&display_map);
 5964                        if let Some((buffer, line_buffer_range)) = display_map
 5965                            .buffer_snapshot
 5966                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5967                        {
 5968                            let indent_size =
 5969                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5970                            let indent_len = match indent_size.kind {
 5971                                IndentKind::Space => {
 5972                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5973                                }
 5974                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5975                            };
 5976                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5977                                let indent_len = indent_len.get();
 5978                                new_head = cmp::min(
 5979                                    new_head,
 5980                                    MultiBufferPoint::new(
 5981                                        old_head.row,
 5982                                        ((old_head.column - 1) / indent_len) * indent_len,
 5983                                    ),
 5984                                );
 5985                            }
 5986                        }
 5987
 5988                        selection.set_head(new_head, SelectionGoal::None);
 5989                    }
 5990                }
 5991            }
 5992
 5993            this.signature_help_state.set_backspace_pressed(true);
 5994            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5995            this.insert("", cx);
 5996            let empty_str: Arc<str> = Arc::from("");
 5997            for (buffer, edits) in linked_ranges {
 5998                let snapshot = buffer.read(cx).snapshot();
 5999                use text::ToPoint as TP;
 6000
 6001                let edits = edits
 6002                    .into_iter()
 6003                    .map(|range| {
 6004                        let end_point = TP::to_point(&range.end, &snapshot);
 6005                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6006
 6007                        if end_point == start_point {
 6008                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6009                                .saturating_sub(1);
 6010                            start_point = TP::to_point(&offset, &snapshot);
 6011                        };
 6012
 6013                        (start_point..end_point, empty_str.clone())
 6014                    })
 6015                    .sorted_by_key(|(range, _)| range.start)
 6016                    .collect::<Vec<_>>();
 6017                buffer.update(cx, |this, cx| {
 6018                    this.edit(edits, None, cx);
 6019                })
 6020            }
 6021            this.refresh_inline_completion(true, false, cx);
 6022            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6023        });
 6024    }
 6025
 6026    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6027        self.transact(cx, |this, cx| {
 6028            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6029                let line_mode = s.line_mode;
 6030                s.move_with(|map, selection| {
 6031                    if selection.is_empty() && !line_mode {
 6032                        let cursor = movement::right(map, selection.head());
 6033                        selection.end = cursor;
 6034                        selection.reversed = true;
 6035                        selection.goal = SelectionGoal::None;
 6036                    }
 6037                })
 6038            });
 6039            this.insert("", cx);
 6040            this.refresh_inline_completion(true, false, cx);
 6041        });
 6042    }
 6043
 6044    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6045        if self.move_to_prev_snippet_tabstop(cx) {
 6046            return;
 6047        }
 6048
 6049        self.outdent(&Outdent, cx);
 6050    }
 6051
 6052    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6053        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6054            return;
 6055        }
 6056
 6057        let mut selections = self.selections.all_adjusted(cx);
 6058        let buffer = self.buffer.read(cx);
 6059        let snapshot = buffer.snapshot(cx);
 6060        let rows_iter = selections.iter().map(|s| s.head().row);
 6061        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6062
 6063        let mut edits = Vec::new();
 6064        let mut prev_edited_row = 0;
 6065        let mut row_delta = 0;
 6066        for selection in &mut selections {
 6067            if selection.start.row != prev_edited_row {
 6068                row_delta = 0;
 6069            }
 6070            prev_edited_row = selection.end.row;
 6071
 6072            // If the selection is non-empty, then increase the indentation of the selected lines.
 6073            if !selection.is_empty() {
 6074                row_delta =
 6075                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6076                continue;
 6077            }
 6078
 6079            // If the selection is empty and the cursor is in the leading whitespace before the
 6080            // suggested indentation, then auto-indent the line.
 6081            let cursor = selection.head();
 6082            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6083            if let Some(suggested_indent) =
 6084                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6085            {
 6086                if cursor.column < suggested_indent.len
 6087                    && cursor.column <= current_indent.len
 6088                    && current_indent.len <= suggested_indent.len
 6089                {
 6090                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6091                    selection.end = selection.start;
 6092                    if row_delta == 0 {
 6093                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6094                            cursor.row,
 6095                            current_indent,
 6096                            suggested_indent,
 6097                        ));
 6098                        row_delta = suggested_indent.len - current_indent.len;
 6099                    }
 6100                    continue;
 6101                }
 6102            }
 6103
 6104            // Otherwise, insert a hard or soft tab.
 6105            let settings = buffer.settings_at(cursor, cx);
 6106            let tab_size = if settings.hard_tabs {
 6107                IndentSize::tab()
 6108            } else {
 6109                let tab_size = settings.tab_size.get();
 6110                let char_column = snapshot
 6111                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6112                    .flat_map(str::chars)
 6113                    .count()
 6114                    + row_delta as usize;
 6115                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6116                IndentSize::spaces(chars_to_next_tab_stop)
 6117            };
 6118            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6119            selection.end = selection.start;
 6120            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6121            row_delta += tab_size.len;
 6122        }
 6123
 6124        self.transact(cx, |this, cx| {
 6125            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6126            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6127            this.refresh_inline_completion(true, false, cx);
 6128        });
 6129    }
 6130
 6131    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6132        if self.read_only(cx) {
 6133            return;
 6134        }
 6135        let mut selections = self.selections.all::<Point>(cx);
 6136        let mut prev_edited_row = 0;
 6137        let mut row_delta = 0;
 6138        let mut edits = Vec::new();
 6139        let buffer = self.buffer.read(cx);
 6140        let snapshot = buffer.snapshot(cx);
 6141        for selection in &mut selections {
 6142            if selection.start.row != prev_edited_row {
 6143                row_delta = 0;
 6144            }
 6145            prev_edited_row = selection.end.row;
 6146
 6147            row_delta =
 6148                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6149        }
 6150
 6151        self.transact(cx, |this, cx| {
 6152            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6153            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6154        });
 6155    }
 6156
 6157    fn indent_selection(
 6158        buffer: &MultiBuffer,
 6159        snapshot: &MultiBufferSnapshot,
 6160        selection: &mut Selection<Point>,
 6161        edits: &mut Vec<(Range<Point>, String)>,
 6162        delta_for_start_row: u32,
 6163        cx: &AppContext,
 6164    ) -> u32 {
 6165        let settings = buffer.settings_at(selection.start, cx);
 6166        let tab_size = settings.tab_size.get();
 6167        let indent_kind = if settings.hard_tabs {
 6168            IndentKind::Tab
 6169        } else {
 6170            IndentKind::Space
 6171        };
 6172        let mut start_row = selection.start.row;
 6173        let mut end_row = selection.end.row + 1;
 6174
 6175        // If a selection ends at the beginning of a line, don't indent
 6176        // that last line.
 6177        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6178            end_row -= 1;
 6179        }
 6180
 6181        // Avoid re-indenting a row that has already been indented by a
 6182        // previous selection, but still update this selection's column
 6183        // to reflect that indentation.
 6184        if delta_for_start_row > 0 {
 6185            start_row += 1;
 6186            selection.start.column += delta_for_start_row;
 6187            if selection.end.row == selection.start.row {
 6188                selection.end.column += delta_for_start_row;
 6189            }
 6190        }
 6191
 6192        let mut delta_for_end_row = 0;
 6193        let has_multiple_rows = start_row + 1 != end_row;
 6194        for row in start_row..end_row {
 6195            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6196            let indent_delta = match (current_indent.kind, indent_kind) {
 6197                (IndentKind::Space, IndentKind::Space) => {
 6198                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6199                    IndentSize::spaces(columns_to_next_tab_stop)
 6200                }
 6201                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6202                (_, IndentKind::Tab) => IndentSize::tab(),
 6203            };
 6204
 6205            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6206                0
 6207            } else {
 6208                selection.start.column
 6209            };
 6210            let row_start = Point::new(row, start);
 6211            edits.push((
 6212                row_start..row_start,
 6213                indent_delta.chars().collect::<String>(),
 6214            ));
 6215
 6216            // Update this selection's endpoints to reflect the indentation.
 6217            if row == selection.start.row {
 6218                selection.start.column += indent_delta.len;
 6219            }
 6220            if row == selection.end.row {
 6221                selection.end.column += indent_delta.len;
 6222                delta_for_end_row = indent_delta.len;
 6223            }
 6224        }
 6225
 6226        if selection.start.row == selection.end.row {
 6227            delta_for_start_row + delta_for_end_row
 6228        } else {
 6229            delta_for_end_row
 6230        }
 6231    }
 6232
 6233    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6234        if self.read_only(cx) {
 6235            return;
 6236        }
 6237        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6238        let selections = self.selections.all::<Point>(cx);
 6239        let mut deletion_ranges = Vec::new();
 6240        let mut last_outdent = None;
 6241        {
 6242            let buffer = self.buffer.read(cx);
 6243            let snapshot = buffer.snapshot(cx);
 6244            for selection in &selections {
 6245                let settings = buffer.settings_at(selection.start, cx);
 6246                let tab_size = settings.tab_size.get();
 6247                let mut rows = selection.spanned_rows(false, &display_map);
 6248
 6249                // Avoid re-outdenting a row that has already been outdented by a
 6250                // previous selection.
 6251                if let Some(last_row) = last_outdent {
 6252                    if last_row == rows.start {
 6253                        rows.start = rows.start.next_row();
 6254                    }
 6255                }
 6256                let has_multiple_rows = rows.len() > 1;
 6257                for row in rows.iter_rows() {
 6258                    let indent_size = snapshot.indent_size_for_line(row);
 6259                    if indent_size.len > 0 {
 6260                        let deletion_len = match indent_size.kind {
 6261                            IndentKind::Space => {
 6262                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6263                                if columns_to_prev_tab_stop == 0 {
 6264                                    tab_size
 6265                                } else {
 6266                                    columns_to_prev_tab_stop
 6267                                }
 6268                            }
 6269                            IndentKind::Tab => 1,
 6270                        };
 6271                        let start = if has_multiple_rows
 6272                            || deletion_len > selection.start.column
 6273                            || indent_size.len < selection.start.column
 6274                        {
 6275                            0
 6276                        } else {
 6277                            selection.start.column - deletion_len
 6278                        };
 6279                        deletion_ranges.push(
 6280                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6281                        );
 6282                        last_outdent = Some(row);
 6283                    }
 6284                }
 6285            }
 6286        }
 6287
 6288        self.transact(cx, |this, cx| {
 6289            this.buffer.update(cx, |buffer, cx| {
 6290                let empty_str: Arc<str> = Arc::default();
 6291                buffer.edit(
 6292                    deletion_ranges
 6293                        .into_iter()
 6294                        .map(|range| (range, empty_str.clone())),
 6295                    None,
 6296                    cx,
 6297                );
 6298            });
 6299            let selections = this.selections.all::<usize>(cx);
 6300            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6301        });
 6302    }
 6303
 6304    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 6305        if self.read_only(cx) {
 6306            return;
 6307        }
 6308        let selections = self
 6309            .selections
 6310            .all::<usize>(cx)
 6311            .into_iter()
 6312            .map(|s| s.range());
 6313
 6314        self.transact(cx, |this, cx| {
 6315            this.buffer.update(cx, |buffer, cx| {
 6316                buffer.autoindent_ranges(selections, cx);
 6317            });
 6318            let selections = this.selections.all::<usize>(cx);
 6319            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6320        });
 6321    }
 6322
 6323    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6324        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6325        let selections = self.selections.all::<Point>(cx);
 6326
 6327        let mut new_cursors = Vec::new();
 6328        let mut edit_ranges = Vec::new();
 6329        let mut selections = selections.iter().peekable();
 6330        while let Some(selection) = selections.next() {
 6331            let mut rows = selection.spanned_rows(false, &display_map);
 6332            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6333
 6334            // Accumulate contiguous regions of rows that we want to delete.
 6335            while let Some(next_selection) = selections.peek() {
 6336                let next_rows = next_selection.spanned_rows(false, &display_map);
 6337                if next_rows.start <= rows.end {
 6338                    rows.end = next_rows.end;
 6339                    selections.next().unwrap();
 6340                } else {
 6341                    break;
 6342                }
 6343            }
 6344
 6345            let buffer = &display_map.buffer_snapshot;
 6346            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6347            let edit_end;
 6348            let cursor_buffer_row;
 6349            if buffer.max_point().row >= rows.end.0 {
 6350                // If there's a line after the range, delete the \n from the end of the row range
 6351                // and position the cursor on the next line.
 6352                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6353                cursor_buffer_row = rows.end;
 6354            } else {
 6355                // If there isn't a line after the range, delete the \n from the line before the
 6356                // start of the row range and position the cursor there.
 6357                edit_start = edit_start.saturating_sub(1);
 6358                edit_end = buffer.len();
 6359                cursor_buffer_row = rows.start.previous_row();
 6360            }
 6361
 6362            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6363            *cursor.column_mut() =
 6364                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6365
 6366            new_cursors.push((
 6367                selection.id,
 6368                buffer.anchor_after(cursor.to_point(&display_map)),
 6369            ));
 6370            edit_ranges.push(edit_start..edit_end);
 6371        }
 6372
 6373        self.transact(cx, |this, cx| {
 6374            let buffer = this.buffer.update(cx, |buffer, cx| {
 6375                let empty_str: Arc<str> = Arc::default();
 6376                buffer.edit(
 6377                    edit_ranges
 6378                        .into_iter()
 6379                        .map(|range| (range, empty_str.clone())),
 6380                    None,
 6381                    cx,
 6382                );
 6383                buffer.snapshot(cx)
 6384            });
 6385            let new_selections = new_cursors
 6386                .into_iter()
 6387                .map(|(id, cursor)| {
 6388                    let cursor = cursor.to_point(&buffer);
 6389                    Selection {
 6390                        id,
 6391                        start: cursor,
 6392                        end: cursor,
 6393                        reversed: false,
 6394                        goal: SelectionGoal::None,
 6395                    }
 6396                })
 6397                .collect();
 6398
 6399            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6400                s.select(new_selections);
 6401            });
 6402        });
 6403    }
 6404
 6405    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6406        if self.read_only(cx) {
 6407            return;
 6408        }
 6409        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6410        for selection in self.selections.all::<Point>(cx) {
 6411            let start = MultiBufferRow(selection.start.row);
 6412            // Treat single line selections as if they include the next line. Otherwise this action
 6413            // would do nothing for single line selections individual cursors.
 6414            let end = if selection.start.row == selection.end.row {
 6415                MultiBufferRow(selection.start.row + 1)
 6416            } else {
 6417                MultiBufferRow(selection.end.row)
 6418            };
 6419
 6420            if let Some(last_row_range) = row_ranges.last_mut() {
 6421                if start <= last_row_range.end {
 6422                    last_row_range.end = end;
 6423                    continue;
 6424                }
 6425            }
 6426            row_ranges.push(start..end);
 6427        }
 6428
 6429        let snapshot = self.buffer.read(cx).snapshot(cx);
 6430        let mut cursor_positions = Vec::new();
 6431        for row_range in &row_ranges {
 6432            let anchor = snapshot.anchor_before(Point::new(
 6433                row_range.end.previous_row().0,
 6434                snapshot.line_len(row_range.end.previous_row()),
 6435            ));
 6436            cursor_positions.push(anchor..anchor);
 6437        }
 6438
 6439        self.transact(cx, |this, cx| {
 6440            for row_range in row_ranges.into_iter().rev() {
 6441                for row in row_range.iter_rows().rev() {
 6442                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6443                    let next_line_row = row.next_row();
 6444                    let indent = snapshot.indent_size_for_line(next_line_row);
 6445                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6446
 6447                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6448                        " "
 6449                    } else {
 6450                        ""
 6451                    };
 6452
 6453                    this.buffer.update(cx, |buffer, cx| {
 6454                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6455                    });
 6456                }
 6457            }
 6458
 6459            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6460                s.select_anchor_ranges(cursor_positions)
 6461            });
 6462        });
 6463    }
 6464
 6465    pub fn sort_lines_case_sensitive(
 6466        &mut self,
 6467        _: &SortLinesCaseSensitive,
 6468        cx: &mut ViewContext<Self>,
 6469    ) {
 6470        self.manipulate_lines(cx, |lines| lines.sort())
 6471    }
 6472
 6473    pub fn sort_lines_case_insensitive(
 6474        &mut self,
 6475        _: &SortLinesCaseInsensitive,
 6476        cx: &mut ViewContext<Self>,
 6477    ) {
 6478        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6479    }
 6480
 6481    pub fn unique_lines_case_insensitive(
 6482        &mut self,
 6483        _: &UniqueLinesCaseInsensitive,
 6484        cx: &mut ViewContext<Self>,
 6485    ) {
 6486        self.manipulate_lines(cx, |lines| {
 6487            let mut seen = HashSet::default();
 6488            lines.retain(|line| seen.insert(line.to_lowercase()));
 6489        })
 6490    }
 6491
 6492    pub fn unique_lines_case_sensitive(
 6493        &mut self,
 6494        _: &UniqueLinesCaseSensitive,
 6495        cx: &mut ViewContext<Self>,
 6496    ) {
 6497        self.manipulate_lines(cx, |lines| {
 6498            let mut seen = HashSet::default();
 6499            lines.retain(|line| seen.insert(*line));
 6500        })
 6501    }
 6502
 6503    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6504        let mut revert_changes = HashMap::default();
 6505        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6506        for hunk in hunks_for_rows(
 6507            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_row()).into_iter(),
 6508            &multi_buffer_snapshot,
 6509        ) {
 6510            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6511        }
 6512        if !revert_changes.is_empty() {
 6513            self.transact(cx, |editor, cx| {
 6514                editor.revert(revert_changes, cx);
 6515            });
 6516        }
 6517    }
 6518
 6519    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6520        let Some(project) = self.project.clone() else {
 6521            return;
 6522        };
 6523        self.reload(project, cx).detach_and_notify_err(cx);
 6524    }
 6525
 6526    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6527        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6528        if !revert_changes.is_empty() {
 6529            self.transact(cx, |editor, cx| {
 6530                editor.revert(revert_changes, cx);
 6531            });
 6532        }
 6533    }
 6534
 6535    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6536        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6537            let project_path = buffer.read(cx).project_path(cx)?;
 6538            let project = self.project.as_ref()?.read(cx);
 6539            let entry = project.entry_for_path(&project_path, cx)?;
 6540            let parent = match &entry.canonical_path {
 6541                Some(canonical_path) => canonical_path.to_path_buf(),
 6542                None => project.absolute_path(&project_path, cx)?,
 6543            }
 6544            .parent()?
 6545            .to_path_buf();
 6546            Some(parent)
 6547        }) {
 6548            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6549        }
 6550    }
 6551
 6552    fn gather_revert_changes(
 6553        &mut self,
 6554        selections: &[Selection<Anchor>],
 6555        cx: &mut ViewContext<'_, Editor>,
 6556    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6557        let mut revert_changes = HashMap::default();
 6558        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6559        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6560            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6561        }
 6562        revert_changes
 6563    }
 6564
 6565    pub fn prepare_revert_change(
 6566        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6567        multi_buffer: &Model<MultiBuffer>,
 6568        hunk: &MultiBufferDiffHunk,
 6569        cx: &AppContext,
 6570    ) -> Option<()> {
 6571        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6572        let buffer = buffer.read(cx);
 6573        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6574        let buffer_snapshot = buffer.snapshot();
 6575        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6576        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6577            probe
 6578                .0
 6579                .start
 6580                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6581                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6582        }) {
 6583            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6584            Some(())
 6585        } else {
 6586            None
 6587        }
 6588    }
 6589
 6590    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6591        self.manipulate_lines(cx, |lines| lines.reverse())
 6592    }
 6593
 6594    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6595        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6596    }
 6597
 6598    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6599    where
 6600        Fn: FnMut(&mut Vec<&str>),
 6601    {
 6602        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6603        let buffer = self.buffer.read(cx).snapshot(cx);
 6604
 6605        let mut edits = Vec::new();
 6606
 6607        let selections = self.selections.all::<Point>(cx);
 6608        let mut selections = selections.iter().peekable();
 6609        let mut contiguous_row_selections = Vec::new();
 6610        let mut new_selections = Vec::new();
 6611        let mut added_lines = 0;
 6612        let mut removed_lines = 0;
 6613
 6614        while let Some(selection) = selections.next() {
 6615            let (start_row, end_row) = consume_contiguous_rows(
 6616                &mut contiguous_row_selections,
 6617                selection,
 6618                &display_map,
 6619                &mut selections,
 6620            );
 6621
 6622            let start_point = Point::new(start_row.0, 0);
 6623            let end_point = Point::new(
 6624                end_row.previous_row().0,
 6625                buffer.line_len(end_row.previous_row()),
 6626            );
 6627            let text = buffer
 6628                .text_for_range(start_point..end_point)
 6629                .collect::<String>();
 6630
 6631            let mut lines = text.split('\n').collect_vec();
 6632
 6633            let lines_before = lines.len();
 6634            callback(&mut lines);
 6635            let lines_after = lines.len();
 6636
 6637            edits.push((start_point..end_point, lines.join("\n")));
 6638
 6639            // Selections must change based on added and removed line count
 6640            let start_row =
 6641                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6642            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6643            new_selections.push(Selection {
 6644                id: selection.id,
 6645                start: start_row,
 6646                end: end_row,
 6647                goal: SelectionGoal::None,
 6648                reversed: selection.reversed,
 6649            });
 6650
 6651            if lines_after > lines_before {
 6652                added_lines += lines_after - lines_before;
 6653            } else if lines_before > lines_after {
 6654                removed_lines += lines_before - lines_after;
 6655            }
 6656        }
 6657
 6658        self.transact(cx, |this, cx| {
 6659            let buffer = this.buffer.update(cx, |buffer, cx| {
 6660                buffer.edit(edits, None, cx);
 6661                buffer.snapshot(cx)
 6662            });
 6663
 6664            // Recalculate offsets on newly edited buffer
 6665            let new_selections = new_selections
 6666                .iter()
 6667                .map(|s| {
 6668                    let start_point = Point::new(s.start.0, 0);
 6669                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6670                    Selection {
 6671                        id: s.id,
 6672                        start: buffer.point_to_offset(start_point),
 6673                        end: buffer.point_to_offset(end_point),
 6674                        goal: s.goal,
 6675                        reversed: s.reversed,
 6676                    }
 6677                })
 6678                .collect();
 6679
 6680            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6681                s.select(new_selections);
 6682            });
 6683
 6684            this.request_autoscroll(Autoscroll::fit(), cx);
 6685        });
 6686    }
 6687
 6688    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6689        self.manipulate_text(cx, |text| text.to_uppercase())
 6690    }
 6691
 6692    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6693        self.manipulate_text(cx, |text| text.to_lowercase())
 6694    }
 6695
 6696    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6697        self.manipulate_text(cx, |text| {
 6698            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6699            // https://github.com/rutrum/convert-case/issues/16
 6700            text.split('\n')
 6701                .map(|line| line.to_case(Case::Title))
 6702                .join("\n")
 6703        })
 6704    }
 6705
 6706    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6707        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6708    }
 6709
 6710    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6711        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6712    }
 6713
 6714    pub fn convert_to_upper_camel_case(
 6715        &mut self,
 6716        _: &ConvertToUpperCamelCase,
 6717        cx: &mut ViewContext<Self>,
 6718    ) {
 6719        self.manipulate_text(cx, |text| {
 6720            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6721            // https://github.com/rutrum/convert-case/issues/16
 6722            text.split('\n')
 6723                .map(|line| line.to_case(Case::UpperCamel))
 6724                .join("\n")
 6725        })
 6726    }
 6727
 6728    pub fn convert_to_lower_camel_case(
 6729        &mut self,
 6730        _: &ConvertToLowerCamelCase,
 6731        cx: &mut ViewContext<Self>,
 6732    ) {
 6733        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6734    }
 6735
 6736    pub fn convert_to_opposite_case(
 6737        &mut self,
 6738        _: &ConvertToOppositeCase,
 6739        cx: &mut ViewContext<Self>,
 6740    ) {
 6741        self.manipulate_text(cx, |text| {
 6742            text.chars()
 6743                .fold(String::with_capacity(text.len()), |mut t, c| {
 6744                    if c.is_uppercase() {
 6745                        t.extend(c.to_lowercase());
 6746                    } else {
 6747                        t.extend(c.to_uppercase());
 6748                    }
 6749                    t
 6750                })
 6751        })
 6752    }
 6753
 6754    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6755    where
 6756        Fn: FnMut(&str) -> String,
 6757    {
 6758        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6759        let buffer = self.buffer.read(cx).snapshot(cx);
 6760
 6761        let mut new_selections = Vec::new();
 6762        let mut edits = Vec::new();
 6763        let mut selection_adjustment = 0i32;
 6764
 6765        for selection in self.selections.all::<usize>(cx) {
 6766            let selection_is_empty = selection.is_empty();
 6767
 6768            let (start, end) = if selection_is_empty {
 6769                let word_range = movement::surrounding_word(
 6770                    &display_map,
 6771                    selection.start.to_display_point(&display_map),
 6772                );
 6773                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6774                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6775                (start, end)
 6776            } else {
 6777                (selection.start, selection.end)
 6778            };
 6779
 6780            let text = buffer.text_for_range(start..end).collect::<String>();
 6781            let old_length = text.len() as i32;
 6782            let text = callback(&text);
 6783
 6784            new_selections.push(Selection {
 6785                start: (start as i32 - selection_adjustment) as usize,
 6786                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6787                goal: SelectionGoal::None,
 6788                ..selection
 6789            });
 6790
 6791            selection_adjustment += old_length - text.len() as i32;
 6792
 6793            edits.push((start..end, text));
 6794        }
 6795
 6796        self.transact(cx, |this, cx| {
 6797            this.buffer.update(cx, |buffer, cx| {
 6798                buffer.edit(edits, None, cx);
 6799            });
 6800
 6801            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6802                s.select(new_selections);
 6803            });
 6804
 6805            this.request_autoscroll(Autoscroll::fit(), cx);
 6806        });
 6807    }
 6808
 6809    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6810        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6811        let buffer = &display_map.buffer_snapshot;
 6812        let selections = self.selections.all::<Point>(cx);
 6813
 6814        let mut edits = Vec::new();
 6815        let mut selections_iter = selections.iter().peekable();
 6816        while let Some(selection) = selections_iter.next() {
 6817            // Avoid duplicating the same lines twice.
 6818            let mut rows = selection.spanned_rows(false, &display_map);
 6819
 6820            while let Some(next_selection) = selections_iter.peek() {
 6821                let next_rows = next_selection.spanned_rows(false, &display_map);
 6822                if next_rows.start < rows.end {
 6823                    rows.end = next_rows.end;
 6824                    selections_iter.next().unwrap();
 6825                } else {
 6826                    break;
 6827                }
 6828            }
 6829
 6830            // Copy the text from the selected row region and splice it either at the start
 6831            // or end of the region.
 6832            let start = Point::new(rows.start.0, 0);
 6833            let end = Point::new(
 6834                rows.end.previous_row().0,
 6835                buffer.line_len(rows.end.previous_row()),
 6836            );
 6837            let text = buffer
 6838                .text_for_range(start..end)
 6839                .chain(Some("\n"))
 6840                .collect::<String>();
 6841            let insert_location = if upwards {
 6842                Point::new(rows.end.0, 0)
 6843            } else {
 6844                start
 6845            };
 6846            edits.push((insert_location..insert_location, text));
 6847        }
 6848
 6849        self.transact(cx, |this, cx| {
 6850            this.buffer.update(cx, |buffer, cx| {
 6851                buffer.edit(edits, None, cx);
 6852            });
 6853
 6854            this.request_autoscroll(Autoscroll::fit(), cx);
 6855        });
 6856    }
 6857
 6858    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6859        self.duplicate_line(true, cx);
 6860    }
 6861
 6862    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6863        self.duplicate_line(false, cx);
 6864    }
 6865
 6866    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6867        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6868        let buffer = self.buffer.read(cx).snapshot(cx);
 6869
 6870        let mut edits = Vec::new();
 6871        let mut unfold_ranges = Vec::new();
 6872        let mut refold_creases = Vec::new();
 6873
 6874        let selections = self.selections.all::<Point>(cx);
 6875        let mut selections = selections.iter().peekable();
 6876        let mut contiguous_row_selections = Vec::new();
 6877        let mut new_selections = Vec::new();
 6878
 6879        while let Some(selection) = selections.next() {
 6880            // Find all the selections that span a contiguous row range
 6881            let (start_row, end_row) = consume_contiguous_rows(
 6882                &mut contiguous_row_selections,
 6883                selection,
 6884                &display_map,
 6885                &mut selections,
 6886            );
 6887
 6888            // Move the text spanned by the row range to be before the line preceding the row range
 6889            if start_row.0 > 0 {
 6890                let range_to_move = Point::new(
 6891                    start_row.previous_row().0,
 6892                    buffer.line_len(start_row.previous_row()),
 6893                )
 6894                    ..Point::new(
 6895                        end_row.previous_row().0,
 6896                        buffer.line_len(end_row.previous_row()),
 6897                    );
 6898                let insertion_point = display_map
 6899                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6900                    .0;
 6901
 6902                // Don't move lines across excerpts
 6903                if buffer
 6904                    .excerpt_boundaries_in_range((
 6905                        Bound::Excluded(insertion_point),
 6906                        Bound::Included(range_to_move.end),
 6907                    ))
 6908                    .next()
 6909                    .is_none()
 6910                {
 6911                    let text = buffer
 6912                        .text_for_range(range_to_move.clone())
 6913                        .flat_map(|s| s.chars())
 6914                        .skip(1)
 6915                        .chain(['\n'])
 6916                        .collect::<String>();
 6917
 6918                    edits.push((
 6919                        buffer.anchor_after(range_to_move.start)
 6920                            ..buffer.anchor_before(range_to_move.end),
 6921                        String::new(),
 6922                    ));
 6923                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6924                    edits.push((insertion_anchor..insertion_anchor, text));
 6925
 6926                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6927
 6928                    // Move selections up
 6929                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6930                        |mut selection| {
 6931                            selection.start.row -= row_delta;
 6932                            selection.end.row -= row_delta;
 6933                            selection
 6934                        },
 6935                    ));
 6936
 6937                    // Move folds up
 6938                    unfold_ranges.push(range_to_move.clone());
 6939                    for fold in display_map.folds_in_range(
 6940                        buffer.anchor_before(range_to_move.start)
 6941                            ..buffer.anchor_after(range_to_move.end),
 6942                    ) {
 6943                        let mut start = fold.range.start.to_point(&buffer);
 6944                        let mut end = fold.range.end.to_point(&buffer);
 6945                        start.row -= row_delta;
 6946                        end.row -= row_delta;
 6947                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6948                    }
 6949                }
 6950            }
 6951
 6952            // If we didn't move line(s), preserve the existing selections
 6953            new_selections.append(&mut contiguous_row_selections);
 6954        }
 6955
 6956        self.transact(cx, |this, cx| {
 6957            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6958            this.buffer.update(cx, |buffer, cx| {
 6959                for (range, text) in edits {
 6960                    buffer.edit([(range, text)], None, cx);
 6961                }
 6962            });
 6963            this.fold_creases(refold_creases, true, cx);
 6964            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6965                s.select(new_selections);
 6966            })
 6967        });
 6968    }
 6969
 6970    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6971        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6972        let buffer = self.buffer.read(cx).snapshot(cx);
 6973
 6974        let mut edits = Vec::new();
 6975        let mut unfold_ranges = Vec::new();
 6976        let mut refold_creases = Vec::new();
 6977
 6978        let selections = self.selections.all::<Point>(cx);
 6979        let mut selections = selections.iter().peekable();
 6980        let mut contiguous_row_selections = Vec::new();
 6981        let mut new_selections = Vec::new();
 6982
 6983        while let Some(selection) = selections.next() {
 6984            // Find all the selections that span a contiguous row range
 6985            let (start_row, end_row) = consume_contiguous_rows(
 6986                &mut contiguous_row_selections,
 6987                selection,
 6988                &display_map,
 6989                &mut selections,
 6990            );
 6991
 6992            // Move the text spanned by the row range to be after the last line of the row range
 6993            if end_row.0 <= buffer.max_point().row {
 6994                let range_to_move =
 6995                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6996                let insertion_point = display_map
 6997                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6998                    .0;
 6999
 7000                // Don't move lines across excerpt boundaries
 7001                if buffer
 7002                    .excerpt_boundaries_in_range((
 7003                        Bound::Excluded(range_to_move.start),
 7004                        Bound::Included(insertion_point),
 7005                    ))
 7006                    .next()
 7007                    .is_none()
 7008                {
 7009                    let mut text = String::from("\n");
 7010                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7011                    text.pop(); // Drop trailing newline
 7012                    edits.push((
 7013                        buffer.anchor_after(range_to_move.start)
 7014                            ..buffer.anchor_before(range_to_move.end),
 7015                        String::new(),
 7016                    ));
 7017                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7018                    edits.push((insertion_anchor..insertion_anchor, text));
 7019
 7020                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7021
 7022                    // Move selections down
 7023                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7024                        |mut selection| {
 7025                            selection.start.row += row_delta;
 7026                            selection.end.row += row_delta;
 7027                            selection
 7028                        },
 7029                    ));
 7030
 7031                    // Move folds down
 7032                    unfold_ranges.push(range_to_move.clone());
 7033                    for fold in display_map.folds_in_range(
 7034                        buffer.anchor_before(range_to_move.start)
 7035                            ..buffer.anchor_after(range_to_move.end),
 7036                    ) {
 7037                        let mut start = fold.range.start.to_point(&buffer);
 7038                        let mut end = fold.range.end.to_point(&buffer);
 7039                        start.row += row_delta;
 7040                        end.row += row_delta;
 7041                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7042                    }
 7043                }
 7044            }
 7045
 7046            // If we didn't move line(s), preserve the existing selections
 7047            new_selections.append(&mut contiguous_row_selections);
 7048        }
 7049
 7050        self.transact(cx, |this, cx| {
 7051            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7052            this.buffer.update(cx, |buffer, cx| {
 7053                for (range, text) in edits {
 7054                    buffer.edit([(range, text)], None, cx);
 7055                }
 7056            });
 7057            this.fold_creases(refold_creases, true, cx);
 7058            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7059        });
 7060    }
 7061
 7062    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7063        let text_layout_details = &self.text_layout_details(cx);
 7064        self.transact(cx, |this, cx| {
 7065            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7066                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7067                let line_mode = s.line_mode;
 7068                s.move_with(|display_map, selection| {
 7069                    if !selection.is_empty() || line_mode {
 7070                        return;
 7071                    }
 7072
 7073                    let mut head = selection.head();
 7074                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7075                    if head.column() == display_map.line_len(head.row()) {
 7076                        transpose_offset = display_map
 7077                            .buffer_snapshot
 7078                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7079                    }
 7080
 7081                    if transpose_offset == 0 {
 7082                        return;
 7083                    }
 7084
 7085                    *head.column_mut() += 1;
 7086                    head = display_map.clip_point(head, Bias::Right);
 7087                    let goal = SelectionGoal::HorizontalPosition(
 7088                        display_map
 7089                            .x_for_display_point(head, text_layout_details)
 7090                            .into(),
 7091                    );
 7092                    selection.collapse_to(head, goal);
 7093
 7094                    let transpose_start = display_map
 7095                        .buffer_snapshot
 7096                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7097                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7098                        let transpose_end = display_map
 7099                            .buffer_snapshot
 7100                            .clip_offset(transpose_offset + 1, Bias::Right);
 7101                        if let Some(ch) =
 7102                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7103                        {
 7104                            edits.push((transpose_start..transpose_offset, String::new()));
 7105                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7106                        }
 7107                    }
 7108                });
 7109                edits
 7110            });
 7111            this.buffer
 7112                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7113            let selections = this.selections.all::<usize>(cx);
 7114            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7115                s.select(selections);
 7116            });
 7117        });
 7118    }
 7119
 7120    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7121        self.rewrap_impl(IsVimMode::No, cx)
 7122    }
 7123
 7124    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7125        let buffer = self.buffer.read(cx).snapshot(cx);
 7126        let selections = self.selections.all::<Point>(cx);
 7127        let mut selections = selections.iter().peekable();
 7128
 7129        let mut edits = Vec::new();
 7130        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7131
 7132        while let Some(selection) = selections.next() {
 7133            let mut start_row = selection.start.row;
 7134            let mut end_row = selection.end.row;
 7135
 7136            // Skip selections that overlap with a range that has already been rewrapped.
 7137            let selection_range = start_row..end_row;
 7138            if rewrapped_row_ranges
 7139                .iter()
 7140                .any(|range| range.overlaps(&selection_range))
 7141            {
 7142                continue;
 7143            }
 7144
 7145            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7146
 7147            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7148                match language_scope.language_name().0.as_ref() {
 7149                    "Markdown" | "Plain Text" => {
 7150                        should_rewrap = true;
 7151                    }
 7152                    _ => {}
 7153                }
 7154            }
 7155
 7156            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7157
 7158            // Since not all lines in the selection may be at the same indent
 7159            // level, choose the indent size that is the most common between all
 7160            // of the lines.
 7161            //
 7162            // If there is a tie, we use the deepest indent.
 7163            let (indent_size, indent_end) = {
 7164                let mut indent_size_occurrences = HashMap::default();
 7165                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7166
 7167                for row in start_row..=end_row {
 7168                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7169                    rows_by_indent_size.entry(indent).or_default().push(row);
 7170                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7171                }
 7172
 7173                let indent_size = indent_size_occurrences
 7174                    .into_iter()
 7175                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7176                    .map(|(indent, _)| indent)
 7177                    .unwrap_or_default();
 7178                let row = rows_by_indent_size[&indent_size][0];
 7179                let indent_end = Point::new(row, indent_size.len);
 7180
 7181                (indent_size, indent_end)
 7182            };
 7183
 7184            let mut line_prefix = indent_size.chars().collect::<String>();
 7185
 7186            if let Some(comment_prefix) =
 7187                buffer
 7188                    .language_scope_at(selection.head())
 7189                    .and_then(|language| {
 7190                        language
 7191                            .line_comment_prefixes()
 7192                            .iter()
 7193                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7194                            .cloned()
 7195                    })
 7196            {
 7197                line_prefix.push_str(&comment_prefix);
 7198                should_rewrap = true;
 7199            }
 7200
 7201            if !should_rewrap {
 7202                continue;
 7203            }
 7204
 7205            if selection.is_empty() {
 7206                'expand_upwards: while start_row > 0 {
 7207                    let prev_row = start_row - 1;
 7208                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7209                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7210                    {
 7211                        start_row = prev_row;
 7212                    } else {
 7213                        break 'expand_upwards;
 7214                    }
 7215                }
 7216
 7217                'expand_downwards: while end_row < buffer.max_point().row {
 7218                    let next_row = end_row + 1;
 7219                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7220                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7221                    {
 7222                        end_row = next_row;
 7223                    } else {
 7224                        break 'expand_downwards;
 7225                    }
 7226                }
 7227            }
 7228
 7229            let start = Point::new(start_row, 0);
 7230            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7231            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7232            let Some(lines_without_prefixes) = selection_text
 7233                .lines()
 7234                .map(|line| {
 7235                    line.strip_prefix(&line_prefix)
 7236                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7237                        .ok_or_else(|| {
 7238                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7239                        })
 7240                })
 7241                .collect::<Result<Vec<_>, _>>()
 7242                .log_err()
 7243            else {
 7244                continue;
 7245            };
 7246
 7247            let wrap_column = buffer
 7248                .settings_at(Point::new(start_row, 0), cx)
 7249                .preferred_line_length as usize;
 7250            let wrapped_text = wrap_with_prefix(
 7251                line_prefix,
 7252                lines_without_prefixes.join(" "),
 7253                wrap_column,
 7254                tab_size,
 7255            );
 7256
 7257            // TODO: should always use char-based diff while still supporting cursor behavior that
 7258            // matches vim.
 7259            let diff = match is_vim_mode {
 7260                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7261                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7262            };
 7263            let mut offset = start.to_offset(&buffer);
 7264            let mut moved_since_edit = true;
 7265
 7266            for change in diff.iter_all_changes() {
 7267                let value = change.value();
 7268                match change.tag() {
 7269                    ChangeTag::Equal => {
 7270                        offset += value.len();
 7271                        moved_since_edit = true;
 7272                    }
 7273                    ChangeTag::Delete => {
 7274                        let start = buffer.anchor_after(offset);
 7275                        let end = buffer.anchor_before(offset + value.len());
 7276
 7277                        if moved_since_edit {
 7278                            edits.push((start..end, String::new()));
 7279                        } else {
 7280                            edits.last_mut().unwrap().0.end = end;
 7281                        }
 7282
 7283                        offset += value.len();
 7284                        moved_since_edit = false;
 7285                    }
 7286                    ChangeTag::Insert => {
 7287                        if moved_since_edit {
 7288                            let anchor = buffer.anchor_after(offset);
 7289                            edits.push((anchor..anchor, value.to_string()));
 7290                        } else {
 7291                            edits.last_mut().unwrap().1.push_str(value);
 7292                        }
 7293
 7294                        moved_since_edit = false;
 7295                    }
 7296                }
 7297            }
 7298
 7299            rewrapped_row_ranges.push(start_row..=end_row);
 7300        }
 7301
 7302        self.buffer
 7303            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7304    }
 7305
 7306    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 7307        let mut text = String::new();
 7308        let buffer = self.buffer.read(cx).snapshot(cx);
 7309        let mut selections = self.selections.all::<Point>(cx);
 7310        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7311        {
 7312            let max_point = buffer.max_point();
 7313            let mut is_first = true;
 7314            for selection in &mut selections {
 7315                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7316                if is_entire_line {
 7317                    selection.start = Point::new(selection.start.row, 0);
 7318                    if !selection.is_empty() && selection.end.column == 0 {
 7319                        selection.end = cmp::min(max_point, selection.end);
 7320                    } else {
 7321                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7322                    }
 7323                    selection.goal = SelectionGoal::None;
 7324                }
 7325                if is_first {
 7326                    is_first = false;
 7327                } else {
 7328                    text += "\n";
 7329                }
 7330                let mut len = 0;
 7331                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7332                    text.push_str(chunk);
 7333                    len += chunk.len();
 7334                }
 7335                clipboard_selections.push(ClipboardSelection {
 7336                    len,
 7337                    is_entire_line,
 7338                    first_line_indent: buffer
 7339                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7340                        .len,
 7341                });
 7342            }
 7343        }
 7344
 7345        self.transact(cx, |this, cx| {
 7346            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7347                s.select(selections);
 7348            });
 7349            this.insert("", cx);
 7350        });
 7351        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7352    }
 7353
 7354    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7355        let item = self.cut_common(cx);
 7356        cx.write_to_clipboard(item);
 7357    }
 7358
 7359    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 7360        self.change_selections(None, cx, |s| {
 7361            s.move_with(|snapshot, sel| {
 7362                if sel.is_empty() {
 7363                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7364                }
 7365            });
 7366        });
 7367        let item = self.cut_common(cx);
 7368        cx.set_global(KillRing(item))
 7369    }
 7370
 7371    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 7372        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7373            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7374                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7375            } else {
 7376                return;
 7377            }
 7378        } else {
 7379            return;
 7380        };
 7381        self.do_paste(&text, metadata, false, cx);
 7382    }
 7383
 7384    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7385        let selections = self.selections.all::<Point>(cx);
 7386        let buffer = self.buffer.read(cx).read(cx);
 7387        let mut text = String::new();
 7388
 7389        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7390        {
 7391            let max_point = buffer.max_point();
 7392            let mut is_first = true;
 7393            for selection in selections.iter() {
 7394                let mut start = selection.start;
 7395                let mut end = selection.end;
 7396                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7397                if is_entire_line {
 7398                    start = Point::new(start.row, 0);
 7399                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7400                }
 7401                if is_first {
 7402                    is_first = false;
 7403                } else {
 7404                    text += "\n";
 7405                }
 7406                let mut len = 0;
 7407                for chunk in buffer.text_for_range(start..end) {
 7408                    text.push_str(chunk);
 7409                    len += chunk.len();
 7410                }
 7411                clipboard_selections.push(ClipboardSelection {
 7412                    len,
 7413                    is_entire_line,
 7414                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7415                });
 7416            }
 7417        }
 7418
 7419        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7420            text,
 7421            clipboard_selections,
 7422        ));
 7423    }
 7424
 7425    pub fn do_paste(
 7426        &mut self,
 7427        text: &String,
 7428        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7429        handle_entire_lines: bool,
 7430        cx: &mut ViewContext<Self>,
 7431    ) {
 7432        if self.read_only(cx) {
 7433            return;
 7434        }
 7435
 7436        let clipboard_text = Cow::Borrowed(text);
 7437
 7438        self.transact(cx, |this, cx| {
 7439            if let Some(mut clipboard_selections) = clipboard_selections {
 7440                let old_selections = this.selections.all::<usize>(cx);
 7441                let all_selections_were_entire_line =
 7442                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7443                let first_selection_indent_column =
 7444                    clipboard_selections.first().map(|s| s.first_line_indent);
 7445                if clipboard_selections.len() != old_selections.len() {
 7446                    clipboard_selections.drain(..);
 7447                }
 7448                let cursor_offset = this.selections.last::<usize>(cx).head();
 7449                let mut auto_indent_on_paste = true;
 7450
 7451                this.buffer.update(cx, |buffer, cx| {
 7452                    let snapshot = buffer.read(cx);
 7453                    auto_indent_on_paste =
 7454                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7455
 7456                    let mut start_offset = 0;
 7457                    let mut edits = Vec::new();
 7458                    let mut original_indent_columns = Vec::new();
 7459                    for (ix, selection) in old_selections.iter().enumerate() {
 7460                        let to_insert;
 7461                        let entire_line;
 7462                        let original_indent_column;
 7463                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7464                            let end_offset = start_offset + clipboard_selection.len;
 7465                            to_insert = &clipboard_text[start_offset..end_offset];
 7466                            entire_line = clipboard_selection.is_entire_line;
 7467                            start_offset = end_offset + 1;
 7468                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7469                        } else {
 7470                            to_insert = clipboard_text.as_str();
 7471                            entire_line = all_selections_were_entire_line;
 7472                            original_indent_column = first_selection_indent_column
 7473                        }
 7474
 7475                        // If the corresponding selection was empty when this slice of the
 7476                        // clipboard text was written, then the entire line containing the
 7477                        // selection was copied. If this selection is also currently empty,
 7478                        // then paste the line before the current line of the buffer.
 7479                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7480                            let column = selection.start.to_point(&snapshot).column as usize;
 7481                            let line_start = selection.start - column;
 7482                            line_start..line_start
 7483                        } else {
 7484                            selection.range()
 7485                        };
 7486
 7487                        edits.push((range, to_insert));
 7488                        original_indent_columns.extend(original_indent_column);
 7489                    }
 7490                    drop(snapshot);
 7491
 7492                    buffer.edit(
 7493                        edits,
 7494                        if auto_indent_on_paste {
 7495                            Some(AutoindentMode::Block {
 7496                                original_indent_columns,
 7497                            })
 7498                        } else {
 7499                            None
 7500                        },
 7501                        cx,
 7502                    );
 7503                });
 7504
 7505                let selections = this.selections.all::<usize>(cx);
 7506                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7507            } else {
 7508                this.insert(&clipboard_text, cx);
 7509            }
 7510        });
 7511    }
 7512
 7513    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7514        if let Some(item) = cx.read_from_clipboard() {
 7515            let entries = item.entries();
 7516
 7517            match entries.first() {
 7518                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7519                // of all the pasted entries.
 7520                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7521                    .do_paste(
 7522                        clipboard_string.text(),
 7523                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7524                        true,
 7525                        cx,
 7526                    ),
 7527                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7528            }
 7529        }
 7530    }
 7531
 7532    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7533        if self.read_only(cx) {
 7534            return;
 7535        }
 7536
 7537        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7538            if let Some((selections, _)) =
 7539                self.selection_history.transaction(transaction_id).cloned()
 7540            {
 7541                self.change_selections(None, cx, |s| {
 7542                    s.select_anchors(selections.to_vec());
 7543                });
 7544            }
 7545            self.request_autoscroll(Autoscroll::fit(), cx);
 7546            self.unmark_text(cx);
 7547            self.refresh_inline_completion(true, false, cx);
 7548            cx.emit(EditorEvent::Edited { transaction_id });
 7549            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7550        }
 7551    }
 7552
 7553    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7554        if self.read_only(cx) {
 7555            return;
 7556        }
 7557
 7558        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7559            if let Some((_, Some(selections))) =
 7560                self.selection_history.transaction(transaction_id).cloned()
 7561            {
 7562                self.change_selections(None, cx, |s| {
 7563                    s.select_anchors(selections.to_vec());
 7564                });
 7565            }
 7566            self.request_autoscroll(Autoscroll::fit(), cx);
 7567            self.unmark_text(cx);
 7568            self.refresh_inline_completion(true, false, cx);
 7569            cx.emit(EditorEvent::Edited { transaction_id });
 7570        }
 7571    }
 7572
 7573    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7574        self.buffer
 7575            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7576    }
 7577
 7578    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7579        self.buffer
 7580            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7581    }
 7582
 7583    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7584        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7585            let line_mode = s.line_mode;
 7586            s.move_with(|map, selection| {
 7587                let cursor = if selection.is_empty() && !line_mode {
 7588                    movement::left(map, selection.start)
 7589                } else {
 7590                    selection.start
 7591                };
 7592                selection.collapse_to(cursor, SelectionGoal::None);
 7593            });
 7594        })
 7595    }
 7596
 7597    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7598        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7599            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7600        })
 7601    }
 7602
 7603    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7604        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7605            let line_mode = s.line_mode;
 7606            s.move_with(|map, selection| {
 7607                let cursor = if selection.is_empty() && !line_mode {
 7608                    movement::right(map, selection.end)
 7609                } else {
 7610                    selection.end
 7611                };
 7612                selection.collapse_to(cursor, SelectionGoal::None)
 7613            });
 7614        })
 7615    }
 7616
 7617    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7618        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7619            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7620        })
 7621    }
 7622
 7623    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7624        if self.take_rename(true, cx).is_some() {
 7625            return;
 7626        }
 7627
 7628        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7629            cx.propagate();
 7630            return;
 7631        }
 7632
 7633        let text_layout_details = &self.text_layout_details(cx);
 7634        let selection_count = self.selections.count();
 7635        let first_selection = self.selections.first_anchor();
 7636
 7637        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7638            let line_mode = s.line_mode;
 7639            s.move_with(|map, selection| {
 7640                if !selection.is_empty() && !line_mode {
 7641                    selection.goal = SelectionGoal::None;
 7642                }
 7643                let (cursor, goal) = movement::up(
 7644                    map,
 7645                    selection.start,
 7646                    selection.goal,
 7647                    false,
 7648                    text_layout_details,
 7649                );
 7650                selection.collapse_to(cursor, goal);
 7651            });
 7652        });
 7653
 7654        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7655        {
 7656            cx.propagate();
 7657        }
 7658    }
 7659
 7660    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7661        if self.take_rename(true, cx).is_some() {
 7662            return;
 7663        }
 7664
 7665        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7666            cx.propagate();
 7667            return;
 7668        }
 7669
 7670        let text_layout_details = &self.text_layout_details(cx);
 7671
 7672        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7673            let line_mode = s.line_mode;
 7674            s.move_with(|map, selection| {
 7675                if !selection.is_empty() && !line_mode {
 7676                    selection.goal = SelectionGoal::None;
 7677                }
 7678                let (cursor, goal) = movement::up_by_rows(
 7679                    map,
 7680                    selection.start,
 7681                    action.lines,
 7682                    selection.goal,
 7683                    false,
 7684                    text_layout_details,
 7685                );
 7686                selection.collapse_to(cursor, goal);
 7687            });
 7688        })
 7689    }
 7690
 7691    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7692        if self.take_rename(true, cx).is_some() {
 7693            return;
 7694        }
 7695
 7696        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7697            cx.propagate();
 7698            return;
 7699        }
 7700
 7701        let text_layout_details = &self.text_layout_details(cx);
 7702
 7703        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7704            let line_mode = s.line_mode;
 7705            s.move_with(|map, selection| {
 7706                if !selection.is_empty() && !line_mode {
 7707                    selection.goal = SelectionGoal::None;
 7708                }
 7709                let (cursor, goal) = movement::down_by_rows(
 7710                    map,
 7711                    selection.start,
 7712                    action.lines,
 7713                    selection.goal,
 7714                    false,
 7715                    text_layout_details,
 7716                );
 7717                selection.collapse_to(cursor, goal);
 7718            });
 7719        })
 7720    }
 7721
 7722    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7723        let text_layout_details = &self.text_layout_details(cx);
 7724        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7725            s.move_heads_with(|map, head, goal| {
 7726                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7727            })
 7728        })
 7729    }
 7730
 7731    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7732        let text_layout_details = &self.text_layout_details(cx);
 7733        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7734            s.move_heads_with(|map, head, goal| {
 7735                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7736            })
 7737        })
 7738    }
 7739
 7740    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7741        let Some(row_count) = self.visible_row_count() else {
 7742            return;
 7743        };
 7744
 7745        let text_layout_details = &self.text_layout_details(cx);
 7746
 7747        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7748            s.move_heads_with(|map, head, goal| {
 7749                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7750            })
 7751        })
 7752    }
 7753
 7754    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7755        if self.take_rename(true, cx).is_some() {
 7756            return;
 7757        }
 7758
 7759        if self
 7760            .context_menu
 7761            .write()
 7762            .as_mut()
 7763            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7764            .unwrap_or(false)
 7765        {
 7766            return;
 7767        }
 7768
 7769        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7770            cx.propagate();
 7771            return;
 7772        }
 7773
 7774        let Some(row_count) = self.visible_row_count() else {
 7775            return;
 7776        };
 7777
 7778        let autoscroll = if action.center_cursor {
 7779            Autoscroll::center()
 7780        } else {
 7781            Autoscroll::fit()
 7782        };
 7783
 7784        let text_layout_details = &self.text_layout_details(cx);
 7785
 7786        self.change_selections(Some(autoscroll), cx, |s| {
 7787            let line_mode = s.line_mode;
 7788            s.move_with(|map, selection| {
 7789                if !selection.is_empty() && !line_mode {
 7790                    selection.goal = SelectionGoal::None;
 7791                }
 7792                let (cursor, goal) = movement::up_by_rows(
 7793                    map,
 7794                    selection.end,
 7795                    row_count,
 7796                    selection.goal,
 7797                    false,
 7798                    text_layout_details,
 7799                );
 7800                selection.collapse_to(cursor, goal);
 7801            });
 7802        });
 7803    }
 7804
 7805    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7806        let text_layout_details = &self.text_layout_details(cx);
 7807        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7808            s.move_heads_with(|map, head, goal| {
 7809                movement::up(map, head, goal, false, text_layout_details)
 7810            })
 7811        })
 7812    }
 7813
 7814    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7815        self.take_rename(true, cx);
 7816
 7817        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7818            cx.propagate();
 7819            return;
 7820        }
 7821
 7822        let text_layout_details = &self.text_layout_details(cx);
 7823        let selection_count = self.selections.count();
 7824        let first_selection = self.selections.first_anchor();
 7825
 7826        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7827            let line_mode = s.line_mode;
 7828            s.move_with(|map, selection| {
 7829                if !selection.is_empty() && !line_mode {
 7830                    selection.goal = SelectionGoal::None;
 7831                }
 7832                let (cursor, goal) = movement::down(
 7833                    map,
 7834                    selection.end,
 7835                    selection.goal,
 7836                    false,
 7837                    text_layout_details,
 7838                );
 7839                selection.collapse_to(cursor, goal);
 7840            });
 7841        });
 7842
 7843        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7844        {
 7845            cx.propagate();
 7846        }
 7847    }
 7848
 7849    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7850        let Some(row_count) = self.visible_row_count() else {
 7851            return;
 7852        };
 7853
 7854        let text_layout_details = &self.text_layout_details(cx);
 7855
 7856        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7857            s.move_heads_with(|map, head, goal| {
 7858                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7859            })
 7860        })
 7861    }
 7862
 7863    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7864        if self.take_rename(true, cx).is_some() {
 7865            return;
 7866        }
 7867
 7868        if self
 7869            .context_menu
 7870            .write()
 7871            .as_mut()
 7872            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7873            .unwrap_or(false)
 7874        {
 7875            return;
 7876        }
 7877
 7878        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7879            cx.propagate();
 7880            return;
 7881        }
 7882
 7883        let Some(row_count) = self.visible_row_count() else {
 7884            return;
 7885        };
 7886
 7887        let autoscroll = if action.center_cursor {
 7888            Autoscroll::center()
 7889        } else {
 7890            Autoscroll::fit()
 7891        };
 7892
 7893        let text_layout_details = &self.text_layout_details(cx);
 7894        self.change_selections(Some(autoscroll), cx, |s| {
 7895            let line_mode = s.line_mode;
 7896            s.move_with(|map, selection| {
 7897                if !selection.is_empty() && !line_mode {
 7898                    selection.goal = SelectionGoal::None;
 7899                }
 7900                let (cursor, goal) = movement::down_by_rows(
 7901                    map,
 7902                    selection.end,
 7903                    row_count,
 7904                    selection.goal,
 7905                    false,
 7906                    text_layout_details,
 7907                );
 7908                selection.collapse_to(cursor, goal);
 7909            });
 7910        });
 7911    }
 7912
 7913    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7914        let text_layout_details = &self.text_layout_details(cx);
 7915        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7916            s.move_heads_with(|map, head, goal| {
 7917                movement::down(map, head, goal, false, text_layout_details)
 7918            })
 7919        });
 7920    }
 7921
 7922    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7923        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7924            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7925        }
 7926    }
 7927
 7928    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7929        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7930            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7931        }
 7932    }
 7933
 7934    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7935        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7936            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7937        }
 7938    }
 7939
 7940    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7941        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7942            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7943        }
 7944    }
 7945
 7946    pub fn move_to_previous_word_start(
 7947        &mut self,
 7948        _: &MoveToPreviousWordStart,
 7949        cx: &mut ViewContext<Self>,
 7950    ) {
 7951        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7952            s.move_cursors_with(|map, head, _| {
 7953                (
 7954                    movement::previous_word_start(map, head),
 7955                    SelectionGoal::None,
 7956                )
 7957            });
 7958        })
 7959    }
 7960
 7961    pub fn move_to_previous_subword_start(
 7962        &mut self,
 7963        _: &MoveToPreviousSubwordStart,
 7964        cx: &mut ViewContext<Self>,
 7965    ) {
 7966        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7967            s.move_cursors_with(|map, head, _| {
 7968                (
 7969                    movement::previous_subword_start(map, head),
 7970                    SelectionGoal::None,
 7971                )
 7972            });
 7973        })
 7974    }
 7975
 7976    pub fn select_to_previous_word_start(
 7977        &mut self,
 7978        _: &SelectToPreviousWordStart,
 7979        cx: &mut ViewContext<Self>,
 7980    ) {
 7981        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7982            s.move_heads_with(|map, head, _| {
 7983                (
 7984                    movement::previous_word_start(map, head),
 7985                    SelectionGoal::None,
 7986                )
 7987            });
 7988        })
 7989    }
 7990
 7991    pub fn select_to_previous_subword_start(
 7992        &mut self,
 7993        _: &SelectToPreviousSubwordStart,
 7994        cx: &mut ViewContext<Self>,
 7995    ) {
 7996        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7997            s.move_heads_with(|map, head, _| {
 7998                (
 7999                    movement::previous_subword_start(map, head),
 8000                    SelectionGoal::None,
 8001                )
 8002            });
 8003        })
 8004    }
 8005
 8006    pub fn delete_to_previous_word_start(
 8007        &mut self,
 8008        action: &DeleteToPreviousWordStart,
 8009        cx: &mut ViewContext<Self>,
 8010    ) {
 8011        self.transact(cx, |this, cx| {
 8012            this.select_autoclose_pair(cx);
 8013            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8014                let line_mode = s.line_mode;
 8015                s.move_with(|map, selection| {
 8016                    if selection.is_empty() && !line_mode {
 8017                        let cursor = if action.ignore_newlines {
 8018                            movement::previous_word_start(map, selection.head())
 8019                        } else {
 8020                            movement::previous_word_start_or_newline(map, selection.head())
 8021                        };
 8022                        selection.set_head(cursor, SelectionGoal::None);
 8023                    }
 8024                });
 8025            });
 8026            this.insert("", cx);
 8027        });
 8028    }
 8029
 8030    pub fn delete_to_previous_subword_start(
 8031        &mut self,
 8032        _: &DeleteToPreviousSubwordStart,
 8033        cx: &mut ViewContext<Self>,
 8034    ) {
 8035        self.transact(cx, |this, cx| {
 8036            this.select_autoclose_pair(cx);
 8037            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8038                let line_mode = s.line_mode;
 8039                s.move_with(|map, selection| {
 8040                    if selection.is_empty() && !line_mode {
 8041                        let cursor = movement::previous_subword_start(map, selection.head());
 8042                        selection.set_head(cursor, SelectionGoal::None);
 8043                    }
 8044                });
 8045            });
 8046            this.insert("", cx);
 8047        });
 8048    }
 8049
 8050    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8051        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8052            s.move_cursors_with(|map, head, _| {
 8053                (movement::next_word_end(map, head), SelectionGoal::None)
 8054            });
 8055        })
 8056    }
 8057
 8058    pub fn move_to_next_subword_end(
 8059        &mut self,
 8060        _: &MoveToNextSubwordEnd,
 8061        cx: &mut ViewContext<Self>,
 8062    ) {
 8063        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8064            s.move_cursors_with(|map, head, _| {
 8065                (movement::next_subword_end(map, head), SelectionGoal::None)
 8066            });
 8067        })
 8068    }
 8069
 8070    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8071        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8072            s.move_heads_with(|map, head, _| {
 8073                (movement::next_word_end(map, head), SelectionGoal::None)
 8074            });
 8075        })
 8076    }
 8077
 8078    pub fn select_to_next_subword_end(
 8079        &mut self,
 8080        _: &SelectToNextSubwordEnd,
 8081        cx: &mut ViewContext<Self>,
 8082    ) {
 8083        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8084            s.move_heads_with(|map, head, _| {
 8085                (movement::next_subword_end(map, head), SelectionGoal::None)
 8086            });
 8087        })
 8088    }
 8089
 8090    pub fn delete_to_next_word_end(
 8091        &mut self,
 8092        action: &DeleteToNextWordEnd,
 8093        cx: &mut ViewContext<Self>,
 8094    ) {
 8095        self.transact(cx, |this, cx| {
 8096            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8097                let line_mode = s.line_mode;
 8098                s.move_with(|map, selection| {
 8099                    if selection.is_empty() && !line_mode {
 8100                        let cursor = if action.ignore_newlines {
 8101                            movement::next_word_end(map, selection.head())
 8102                        } else {
 8103                            movement::next_word_end_or_newline(map, selection.head())
 8104                        };
 8105                        selection.set_head(cursor, SelectionGoal::None);
 8106                    }
 8107                });
 8108            });
 8109            this.insert("", cx);
 8110        });
 8111    }
 8112
 8113    pub fn delete_to_next_subword_end(
 8114        &mut self,
 8115        _: &DeleteToNextSubwordEnd,
 8116        cx: &mut ViewContext<Self>,
 8117    ) {
 8118        self.transact(cx, |this, cx| {
 8119            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8120                s.move_with(|map, selection| {
 8121                    if selection.is_empty() {
 8122                        let cursor = movement::next_subword_end(map, selection.head());
 8123                        selection.set_head(cursor, SelectionGoal::None);
 8124                    }
 8125                });
 8126            });
 8127            this.insert("", cx);
 8128        });
 8129    }
 8130
 8131    pub fn move_to_beginning_of_line(
 8132        &mut self,
 8133        action: &MoveToBeginningOfLine,
 8134        cx: &mut ViewContext<Self>,
 8135    ) {
 8136        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8137            s.move_cursors_with(|map, head, _| {
 8138                (
 8139                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8140                    SelectionGoal::None,
 8141                )
 8142            });
 8143        })
 8144    }
 8145
 8146    pub fn select_to_beginning_of_line(
 8147        &mut self,
 8148        action: &SelectToBeginningOfLine,
 8149        cx: &mut ViewContext<Self>,
 8150    ) {
 8151        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8152            s.move_heads_with(|map, head, _| {
 8153                (
 8154                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8155                    SelectionGoal::None,
 8156                )
 8157            });
 8158        });
 8159    }
 8160
 8161    pub fn delete_to_beginning_of_line(
 8162        &mut self,
 8163        _: &DeleteToBeginningOfLine,
 8164        cx: &mut ViewContext<Self>,
 8165    ) {
 8166        self.transact(cx, |this, cx| {
 8167            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8168                s.move_with(|_, selection| {
 8169                    selection.reversed = true;
 8170                });
 8171            });
 8172
 8173            this.select_to_beginning_of_line(
 8174                &SelectToBeginningOfLine {
 8175                    stop_at_soft_wraps: false,
 8176                },
 8177                cx,
 8178            );
 8179            this.backspace(&Backspace, cx);
 8180        });
 8181    }
 8182
 8183    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8184        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8185            s.move_cursors_with(|map, head, _| {
 8186                (
 8187                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8188                    SelectionGoal::None,
 8189                )
 8190            });
 8191        })
 8192    }
 8193
 8194    pub fn select_to_end_of_line(
 8195        &mut self,
 8196        action: &SelectToEndOfLine,
 8197        cx: &mut ViewContext<Self>,
 8198    ) {
 8199        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8200            s.move_heads_with(|map, head, _| {
 8201                (
 8202                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8203                    SelectionGoal::None,
 8204                )
 8205            });
 8206        })
 8207    }
 8208
 8209    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8210        self.transact(cx, |this, cx| {
 8211            this.select_to_end_of_line(
 8212                &SelectToEndOfLine {
 8213                    stop_at_soft_wraps: false,
 8214                },
 8215                cx,
 8216            );
 8217            this.delete(&Delete, cx);
 8218        });
 8219    }
 8220
 8221    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8222        self.transact(cx, |this, cx| {
 8223            this.select_to_end_of_line(
 8224                &SelectToEndOfLine {
 8225                    stop_at_soft_wraps: false,
 8226                },
 8227                cx,
 8228            );
 8229            this.cut(&Cut, cx);
 8230        });
 8231    }
 8232
 8233    pub fn move_to_start_of_paragraph(
 8234        &mut self,
 8235        _: &MoveToStartOfParagraph,
 8236        cx: &mut ViewContext<Self>,
 8237    ) {
 8238        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8239            cx.propagate();
 8240            return;
 8241        }
 8242
 8243        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8244            s.move_with(|map, selection| {
 8245                selection.collapse_to(
 8246                    movement::start_of_paragraph(map, selection.head(), 1),
 8247                    SelectionGoal::None,
 8248                )
 8249            });
 8250        })
 8251    }
 8252
 8253    pub fn move_to_end_of_paragraph(
 8254        &mut self,
 8255        _: &MoveToEndOfParagraph,
 8256        cx: &mut ViewContext<Self>,
 8257    ) {
 8258        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8259            cx.propagate();
 8260            return;
 8261        }
 8262
 8263        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8264            s.move_with(|map, selection| {
 8265                selection.collapse_to(
 8266                    movement::end_of_paragraph(map, selection.head(), 1),
 8267                    SelectionGoal::None,
 8268                )
 8269            });
 8270        })
 8271    }
 8272
 8273    pub fn select_to_start_of_paragraph(
 8274        &mut self,
 8275        _: &SelectToStartOfParagraph,
 8276        cx: &mut ViewContext<Self>,
 8277    ) {
 8278        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8279            cx.propagate();
 8280            return;
 8281        }
 8282
 8283        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8284            s.move_heads_with(|map, head, _| {
 8285                (
 8286                    movement::start_of_paragraph(map, head, 1),
 8287                    SelectionGoal::None,
 8288                )
 8289            });
 8290        })
 8291    }
 8292
 8293    pub fn select_to_end_of_paragraph(
 8294        &mut self,
 8295        _: &SelectToEndOfParagraph,
 8296        cx: &mut ViewContext<Self>,
 8297    ) {
 8298        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8299            cx.propagate();
 8300            return;
 8301        }
 8302
 8303        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8304            s.move_heads_with(|map, head, _| {
 8305                (
 8306                    movement::end_of_paragraph(map, head, 1),
 8307                    SelectionGoal::None,
 8308                )
 8309            });
 8310        })
 8311    }
 8312
 8313    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8314        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8315            cx.propagate();
 8316            return;
 8317        }
 8318
 8319        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8320            s.select_ranges(vec![0..0]);
 8321        });
 8322    }
 8323
 8324    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8325        let mut selection = self.selections.last::<Point>(cx);
 8326        selection.set_head(Point::zero(), SelectionGoal::None);
 8327
 8328        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8329            s.select(vec![selection]);
 8330        });
 8331    }
 8332
 8333    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8334        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8335            cx.propagate();
 8336            return;
 8337        }
 8338
 8339        let cursor = self.buffer.read(cx).read(cx).len();
 8340        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8341            s.select_ranges(vec![cursor..cursor])
 8342        });
 8343    }
 8344
 8345    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8346        self.nav_history = nav_history;
 8347    }
 8348
 8349    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8350        self.nav_history.as_ref()
 8351    }
 8352
 8353    fn push_to_nav_history(
 8354        &mut self,
 8355        cursor_anchor: Anchor,
 8356        new_position: Option<Point>,
 8357        cx: &mut ViewContext<Self>,
 8358    ) {
 8359        if let Some(nav_history) = self.nav_history.as_mut() {
 8360            let buffer = self.buffer.read(cx).read(cx);
 8361            let cursor_position = cursor_anchor.to_point(&buffer);
 8362            let scroll_state = self.scroll_manager.anchor();
 8363            let scroll_top_row = scroll_state.top_row(&buffer);
 8364            drop(buffer);
 8365
 8366            if let Some(new_position) = new_position {
 8367                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8368                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8369                    return;
 8370                }
 8371            }
 8372
 8373            nav_history.push(
 8374                Some(NavigationData {
 8375                    cursor_anchor,
 8376                    cursor_position,
 8377                    scroll_anchor: scroll_state,
 8378                    scroll_top_row,
 8379                }),
 8380                cx,
 8381            );
 8382        }
 8383    }
 8384
 8385    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8386        let buffer = self.buffer.read(cx).snapshot(cx);
 8387        let mut selection = self.selections.first::<usize>(cx);
 8388        selection.set_head(buffer.len(), SelectionGoal::None);
 8389        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8390            s.select(vec![selection]);
 8391        });
 8392    }
 8393
 8394    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8395        let end = self.buffer.read(cx).read(cx).len();
 8396        self.change_selections(None, cx, |s| {
 8397            s.select_ranges(vec![0..end]);
 8398        });
 8399    }
 8400
 8401    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8402        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8403        let mut selections = self.selections.all::<Point>(cx);
 8404        let max_point = display_map.buffer_snapshot.max_point();
 8405        for selection in &mut selections {
 8406            let rows = selection.spanned_rows(true, &display_map);
 8407            selection.start = Point::new(rows.start.0, 0);
 8408            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8409            selection.reversed = false;
 8410        }
 8411        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8412            s.select(selections);
 8413        });
 8414    }
 8415
 8416    pub fn split_selection_into_lines(
 8417        &mut self,
 8418        _: &SplitSelectionIntoLines,
 8419        cx: &mut ViewContext<Self>,
 8420    ) {
 8421        let mut to_unfold = Vec::new();
 8422        let mut new_selection_ranges = Vec::new();
 8423        {
 8424            let selections = self.selections.all::<Point>(cx);
 8425            let buffer = self.buffer.read(cx).read(cx);
 8426            for selection in selections {
 8427                for row in selection.start.row..selection.end.row {
 8428                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8429                    new_selection_ranges.push(cursor..cursor);
 8430                }
 8431                new_selection_ranges.push(selection.end..selection.end);
 8432                to_unfold.push(selection.start..selection.end);
 8433            }
 8434        }
 8435        self.unfold_ranges(&to_unfold, true, true, cx);
 8436        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8437            s.select_ranges(new_selection_ranges);
 8438        });
 8439    }
 8440
 8441    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8442        self.add_selection(true, cx);
 8443    }
 8444
 8445    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8446        self.add_selection(false, cx);
 8447    }
 8448
 8449    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8450        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8451        let mut selections = self.selections.all::<Point>(cx);
 8452        let text_layout_details = self.text_layout_details(cx);
 8453        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8454            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8455            let range = oldest_selection.display_range(&display_map).sorted();
 8456
 8457            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8458            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8459            let positions = start_x.min(end_x)..start_x.max(end_x);
 8460
 8461            selections.clear();
 8462            let mut stack = Vec::new();
 8463            for row in range.start.row().0..=range.end.row().0 {
 8464                if let Some(selection) = self.selections.build_columnar_selection(
 8465                    &display_map,
 8466                    DisplayRow(row),
 8467                    &positions,
 8468                    oldest_selection.reversed,
 8469                    &text_layout_details,
 8470                ) {
 8471                    stack.push(selection.id);
 8472                    selections.push(selection);
 8473                }
 8474            }
 8475
 8476            if above {
 8477                stack.reverse();
 8478            }
 8479
 8480            AddSelectionsState { above, stack }
 8481        });
 8482
 8483        let last_added_selection = *state.stack.last().unwrap();
 8484        let mut new_selections = Vec::new();
 8485        if above == state.above {
 8486            let end_row = if above {
 8487                DisplayRow(0)
 8488            } else {
 8489                display_map.max_point().row()
 8490            };
 8491
 8492            'outer: for selection in selections {
 8493                if selection.id == last_added_selection {
 8494                    let range = selection.display_range(&display_map).sorted();
 8495                    debug_assert_eq!(range.start.row(), range.end.row());
 8496                    let mut row = range.start.row();
 8497                    let positions =
 8498                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8499                            px(start)..px(end)
 8500                        } else {
 8501                            let start_x =
 8502                                display_map.x_for_display_point(range.start, &text_layout_details);
 8503                            let end_x =
 8504                                display_map.x_for_display_point(range.end, &text_layout_details);
 8505                            start_x.min(end_x)..start_x.max(end_x)
 8506                        };
 8507
 8508                    while row != end_row {
 8509                        if above {
 8510                            row.0 -= 1;
 8511                        } else {
 8512                            row.0 += 1;
 8513                        }
 8514
 8515                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8516                            &display_map,
 8517                            row,
 8518                            &positions,
 8519                            selection.reversed,
 8520                            &text_layout_details,
 8521                        ) {
 8522                            state.stack.push(new_selection.id);
 8523                            if above {
 8524                                new_selections.push(new_selection);
 8525                                new_selections.push(selection);
 8526                            } else {
 8527                                new_selections.push(selection);
 8528                                new_selections.push(new_selection);
 8529                            }
 8530
 8531                            continue 'outer;
 8532                        }
 8533                    }
 8534                }
 8535
 8536                new_selections.push(selection);
 8537            }
 8538        } else {
 8539            new_selections = selections;
 8540            new_selections.retain(|s| s.id != last_added_selection);
 8541            state.stack.pop();
 8542        }
 8543
 8544        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8545            s.select(new_selections);
 8546        });
 8547        if state.stack.len() > 1 {
 8548            self.add_selections_state = Some(state);
 8549        }
 8550    }
 8551
 8552    pub fn select_next_match_internal(
 8553        &mut self,
 8554        display_map: &DisplaySnapshot,
 8555        replace_newest: bool,
 8556        autoscroll: Option<Autoscroll>,
 8557        cx: &mut ViewContext<Self>,
 8558    ) -> Result<()> {
 8559        fn select_next_match_ranges(
 8560            this: &mut Editor,
 8561            range: Range<usize>,
 8562            replace_newest: bool,
 8563            auto_scroll: Option<Autoscroll>,
 8564            cx: &mut ViewContext<Editor>,
 8565        ) {
 8566            this.unfold_ranges(&[range.clone()], false, true, cx);
 8567            this.change_selections(auto_scroll, cx, |s| {
 8568                if replace_newest {
 8569                    s.delete(s.newest_anchor().id);
 8570                }
 8571                s.insert_range(range.clone());
 8572            });
 8573        }
 8574
 8575        let buffer = &display_map.buffer_snapshot;
 8576        let mut selections = self.selections.all::<usize>(cx);
 8577        if let Some(mut select_next_state) = self.select_next_state.take() {
 8578            let query = &select_next_state.query;
 8579            if !select_next_state.done {
 8580                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8581                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8582                let mut next_selected_range = None;
 8583
 8584                let bytes_after_last_selection =
 8585                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8586                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8587                let query_matches = query
 8588                    .stream_find_iter(bytes_after_last_selection)
 8589                    .map(|result| (last_selection.end, result))
 8590                    .chain(
 8591                        query
 8592                            .stream_find_iter(bytes_before_first_selection)
 8593                            .map(|result| (0, result)),
 8594                    );
 8595
 8596                for (start_offset, query_match) in query_matches {
 8597                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8598                    let offset_range =
 8599                        start_offset + query_match.start()..start_offset + query_match.end();
 8600                    let display_range = offset_range.start.to_display_point(display_map)
 8601                        ..offset_range.end.to_display_point(display_map);
 8602
 8603                    if !select_next_state.wordwise
 8604                        || (!movement::is_inside_word(display_map, display_range.start)
 8605                            && !movement::is_inside_word(display_map, display_range.end))
 8606                    {
 8607                        // TODO: This is n^2, because we might check all the selections
 8608                        if !selections
 8609                            .iter()
 8610                            .any(|selection| selection.range().overlaps(&offset_range))
 8611                        {
 8612                            next_selected_range = Some(offset_range);
 8613                            break;
 8614                        }
 8615                    }
 8616                }
 8617
 8618                if let Some(next_selected_range) = next_selected_range {
 8619                    select_next_match_ranges(
 8620                        self,
 8621                        next_selected_range,
 8622                        replace_newest,
 8623                        autoscroll,
 8624                        cx,
 8625                    );
 8626                } else {
 8627                    select_next_state.done = true;
 8628                }
 8629            }
 8630
 8631            self.select_next_state = Some(select_next_state);
 8632        } else {
 8633            let mut only_carets = true;
 8634            let mut same_text_selected = true;
 8635            let mut selected_text = None;
 8636
 8637            let mut selections_iter = selections.iter().peekable();
 8638            while let Some(selection) = selections_iter.next() {
 8639                if selection.start != selection.end {
 8640                    only_carets = false;
 8641                }
 8642
 8643                if same_text_selected {
 8644                    if selected_text.is_none() {
 8645                        selected_text =
 8646                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8647                    }
 8648
 8649                    if let Some(next_selection) = selections_iter.peek() {
 8650                        if next_selection.range().len() == selection.range().len() {
 8651                            let next_selected_text = buffer
 8652                                .text_for_range(next_selection.range())
 8653                                .collect::<String>();
 8654                            if Some(next_selected_text) != selected_text {
 8655                                same_text_selected = false;
 8656                                selected_text = None;
 8657                            }
 8658                        } else {
 8659                            same_text_selected = false;
 8660                            selected_text = None;
 8661                        }
 8662                    }
 8663                }
 8664            }
 8665
 8666            if only_carets {
 8667                for selection in &mut selections {
 8668                    let word_range = movement::surrounding_word(
 8669                        display_map,
 8670                        selection.start.to_display_point(display_map),
 8671                    );
 8672                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8673                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8674                    selection.goal = SelectionGoal::None;
 8675                    selection.reversed = false;
 8676                    select_next_match_ranges(
 8677                        self,
 8678                        selection.start..selection.end,
 8679                        replace_newest,
 8680                        autoscroll,
 8681                        cx,
 8682                    );
 8683                }
 8684
 8685                if selections.len() == 1 {
 8686                    let selection = selections
 8687                        .last()
 8688                        .expect("ensured that there's only one selection");
 8689                    let query = buffer
 8690                        .text_for_range(selection.start..selection.end)
 8691                        .collect::<String>();
 8692                    let is_empty = query.is_empty();
 8693                    let select_state = SelectNextState {
 8694                        query: AhoCorasick::new(&[query])?,
 8695                        wordwise: true,
 8696                        done: is_empty,
 8697                    };
 8698                    self.select_next_state = Some(select_state);
 8699                } else {
 8700                    self.select_next_state = None;
 8701                }
 8702            } else if let Some(selected_text) = selected_text {
 8703                self.select_next_state = Some(SelectNextState {
 8704                    query: AhoCorasick::new(&[selected_text])?,
 8705                    wordwise: false,
 8706                    done: false,
 8707                });
 8708                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8709            }
 8710        }
 8711        Ok(())
 8712    }
 8713
 8714    pub fn select_all_matches(
 8715        &mut self,
 8716        _action: &SelectAllMatches,
 8717        cx: &mut ViewContext<Self>,
 8718    ) -> Result<()> {
 8719        self.push_to_selection_history();
 8720        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8721
 8722        self.select_next_match_internal(&display_map, false, None, cx)?;
 8723        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8724            return Ok(());
 8725        };
 8726        if select_next_state.done {
 8727            return Ok(());
 8728        }
 8729
 8730        let mut new_selections = self.selections.all::<usize>(cx);
 8731
 8732        let buffer = &display_map.buffer_snapshot;
 8733        let query_matches = select_next_state
 8734            .query
 8735            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8736
 8737        for query_match in query_matches {
 8738            let query_match = query_match.unwrap(); // can only fail due to I/O
 8739            let offset_range = query_match.start()..query_match.end();
 8740            let display_range = offset_range.start.to_display_point(&display_map)
 8741                ..offset_range.end.to_display_point(&display_map);
 8742
 8743            if !select_next_state.wordwise
 8744                || (!movement::is_inside_word(&display_map, display_range.start)
 8745                    && !movement::is_inside_word(&display_map, display_range.end))
 8746            {
 8747                self.selections.change_with(cx, |selections| {
 8748                    new_selections.push(Selection {
 8749                        id: selections.new_selection_id(),
 8750                        start: offset_range.start,
 8751                        end: offset_range.end,
 8752                        reversed: false,
 8753                        goal: SelectionGoal::None,
 8754                    });
 8755                });
 8756            }
 8757        }
 8758
 8759        new_selections.sort_by_key(|selection| selection.start);
 8760        let mut ix = 0;
 8761        while ix + 1 < new_selections.len() {
 8762            let current_selection = &new_selections[ix];
 8763            let next_selection = &new_selections[ix + 1];
 8764            if current_selection.range().overlaps(&next_selection.range()) {
 8765                if current_selection.id < next_selection.id {
 8766                    new_selections.remove(ix + 1);
 8767                } else {
 8768                    new_selections.remove(ix);
 8769                }
 8770            } else {
 8771                ix += 1;
 8772            }
 8773        }
 8774
 8775        select_next_state.done = true;
 8776        self.unfold_ranges(
 8777            &new_selections
 8778                .iter()
 8779                .map(|selection| selection.range())
 8780                .collect::<Vec<_>>(),
 8781            false,
 8782            false,
 8783            cx,
 8784        );
 8785        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8786            selections.select(new_selections)
 8787        });
 8788
 8789        Ok(())
 8790    }
 8791
 8792    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8793        self.push_to_selection_history();
 8794        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8795        self.select_next_match_internal(
 8796            &display_map,
 8797            action.replace_newest,
 8798            Some(Autoscroll::newest()),
 8799            cx,
 8800        )?;
 8801        Ok(())
 8802    }
 8803
 8804    pub fn select_previous(
 8805        &mut self,
 8806        action: &SelectPrevious,
 8807        cx: &mut ViewContext<Self>,
 8808    ) -> Result<()> {
 8809        self.push_to_selection_history();
 8810        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8811        let buffer = &display_map.buffer_snapshot;
 8812        let mut selections = self.selections.all::<usize>(cx);
 8813        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8814            let query = &select_prev_state.query;
 8815            if !select_prev_state.done {
 8816                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8817                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8818                let mut next_selected_range = None;
 8819                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8820                let bytes_before_last_selection =
 8821                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8822                let bytes_after_first_selection =
 8823                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8824                let query_matches = query
 8825                    .stream_find_iter(bytes_before_last_selection)
 8826                    .map(|result| (last_selection.start, result))
 8827                    .chain(
 8828                        query
 8829                            .stream_find_iter(bytes_after_first_selection)
 8830                            .map(|result| (buffer.len(), result)),
 8831                    );
 8832                for (end_offset, query_match) in query_matches {
 8833                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8834                    let offset_range =
 8835                        end_offset - query_match.end()..end_offset - query_match.start();
 8836                    let display_range = offset_range.start.to_display_point(&display_map)
 8837                        ..offset_range.end.to_display_point(&display_map);
 8838
 8839                    if !select_prev_state.wordwise
 8840                        || (!movement::is_inside_word(&display_map, display_range.start)
 8841                            && !movement::is_inside_word(&display_map, display_range.end))
 8842                    {
 8843                        next_selected_range = Some(offset_range);
 8844                        break;
 8845                    }
 8846                }
 8847
 8848                if let Some(next_selected_range) = next_selected_range {
 8849                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8850                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8851                        if action.replace_newest {
 8852                            s.delete(s.newest_anchor().id);
 8853                        }
 8854                        s.insert_range(next_selected_range);
 8855                    });
 8856                } else {
 8857                    select_prev_state.done = true;
 8858                }
 8859            }
 8860
 8861            self.select_prev_state = Some(select_prev_state);
 8862        } else {
 8863            let mut only_carets = true;
 8864            let mut same_text_selected = true;
 8865            let mut selected_text = None;
 8866
 8867            let mut selections_iter = selections.iter().peekable();
 8868            while let Some(selection) = selections_iter.next() {
 8869                if selection.start != selection.end {
 8870                    only_carets = false;
 8871                }
 8872
 8873                if same_text_selected {
 8874                    if selected_text.is_none() {
 8875                        selected_text =
 8876                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8877                    }
 8878
 8879                    if let Some(next_selection) = selections_iter.peek() {
 8880                        if next_selection.range().len() == selection.range().len() {
 8881                            let next_selected_text = buffer
 8882                                .text_for_range(next_selection.range())
 8883                                .collect::<String>();
 8884                            if Some(next_selected_text) != selected_text {
 8885                                same_text_selected = false;
 8886                                selected_text = None;
 8887                            }
 8888                        } else {
 8889                            same_text_selected = false;
 8890                            selected_text = None;
 8891                        }
 8892                    }
 8893                }
 8894            }
 8895
 8896            if only_carets {
 8897                for selection in &mut selections {
 8898                    let word_range = movement::surrounding_word(
 8899                        &display_map,
 8900                        selection.start.to_display_point(&display_map),
 8901                    );
 8902                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8903                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8904                    selection.goal = SelectionGoal::None;
 8905                    selection.reversed = false;
 8906                }
 8907                if selections.len() == 1 {
 8908                    let selection = selections
 8909                        .last()
 8910                        .expect("ensured that there's only one selection");
 8911                    let query = buffer
 8912                        .text_for_range(selection.start..selection.end)
 8913                        .collect::<String>();
 8914                    let is_empty = query.is_empty();
 8915                    let select_state = SelectNextState {
 8916                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8917                        wordwise: true,
 8918                        done: is_empty,
 8919                    };
 8920                    self.select_prev_state = Some(select_state);
 8921                } else {
 8922                    self.select_prev_state = None;
 8923                }
 8924
 8925                self.unfold_ranges(
 8926                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8927                    false,
 8928                    true,
 8929                    cx,
 8930                );
 8931                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8932                    s.select(selections);
 8933                });
 8934            } else if let Some(selected_text) = selected_text {
 8935                self.select_prev_state = Some(SelectNextState {
 8936                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8937                    wordwise: false,
 8938                    done: false,
 8939                });
 8940                self.select_previous(action, cx)?;
 8941            }
 8942        }
 8943        Ok(())
 8944    }
 8945
 8946    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8947        if self.read_only(cx) {
 8948            return;
 8949        }
 8950        let text_layout_details = &self.text_layout_details(cx);
 8951        self.transact(cx, |this, cx| {
 8952            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8953            let mut edits = Vec::new();
 8954            let mut selection_edit_ranges = Vec::new();
 8955            let mut last_toggled_row = None;
 8956            let snapshot = this.buffer.read(cx).read(cx);
 8957            let empty_str: Arc<str> = Arc::default();
 8958            let mut suffixes_inserted = Vec::new();
 8959            let ignore_indent = action.ignore_indent;
 8960
 8961            fn comment_prefix_range(
 8962                snapshot: &MultiBufferSnapshot,
 8963                row: MultiBufferRow,
 8964                comment_prefix: &str,
 8965                comment_prefix_whitespace: &str,
 8966                ignore_indent: bool,
 8967            ) -> Range<Point> {
 8968                let indent_size = if ignore_indent {
 8969                    0
 8970                } else {
 8971                    snapshot.indent_size_for_line(row).len
 8972                };
 8973
 8974                let start = Point::new(row.0, indent_size);
 8975
 8976                let mut line_bytes = snapshot
 8977                    .bytes_in_range(start..snapshot.max_point())
 8978                    .flatten()
 8979                    .copied();
 8980
 8981                // If this line currently begins with the line comment prefix, then record
 8982                // the range containing the prefix.
 8983                if line_bytes
 8984                    .by_ref()
 8985                    .take(comment_prefix.len())
 8986                    .eq(comment_prefix.bytes())
 8987                {
 8988                    // Include any whitespace that matches the comment prefix.
 8989                    let matching_whitespace_len = line_bytes
 8990                        .zip(comment_prefix_whitespace.bytes())
 8991                        .take_while(|(a, b)| a == b)
 8992                        .count() as u32;
 8993                    let end = Point::new(
 8994                        start.row,
 8995                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8996                    );
 8997                    start..end
 8998                } else {
 8999                    start..start
 9000                }
 9001            }
 9002
 9003            fn comment_suffix_range(
 9004                snapshot: &MultiBufferSnapshot,
 9005                row: MultiBufferRow,
 9006                comment_suffix: &str,
 9007                comment_suffix_has_leading_space: bool,
 9008            ) -> Range<Point> {
 9009                let end = Point::new(row.0, snapshot.line_len(row));
 9010                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9011
 9012                let mut line_end_bytes = snapshot
 9013                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9014                    .flatten()
 9015                    .copied();
 9016
 9017                let leading_space_len = if suffix_start_column > 0
 9018                    && line_end_bytes.next() == Some(b' ')
 9019                    && comment_suffix_has_leading_space
 9020                {
 9021                    1
 9022                } else {
 9023                    0
 9024                };
 9025
 9026                // If this line currently begins with the line comment prefix, then record
 9027                // the range containing the prefix.
 9028                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9029                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9030                    start..end
 9031                } else {
 9032                    end..end
 9033                }
 9034            }
 9035
 9036            // TODO: Handle selections that cross excerpts
 9037            for selection in &mut selections {
 9038                let start_column = snapshot
 9039                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9040                    .len;
 9041                let language = if let Some(language) =
 9042                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9043                {
 9044                    language
 9045                } else {
 9046                    continue;
 9047                };
 9048
 9049                selection_edit_ranges.clear();
 9050
 9051                // If multiple selections contain a given row, avoid processing that
 9052                // row more than once.
 9053                let mut start_row = MultiBufferRow(selection.start.row);
 9054                if last_toggled_row == Some(start_row) {
 9055                    start_row = start_row.next_row();
 9056                }
 9057                let end_row =
 9058                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9059                        MultiBufferRow(selection.end.row - 1)
 9060                    } else {
 9061                        MultiBufferRow(selection.end.row)
 9062                    };
 9063                last_toggled_row = Some(end_row);
 9064
 9065                if start_row > end_row {
 9066                    continue;
 9067                }
 9068
 9069                // If the language has line comments, toggle those.
 9070                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9071
 9072                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9073                if ignore_indent {
 9074                    full_comment_prefixes = full_comment_prefixes
 9075                        .into_iter()
 9076                        .map(|s| Arc::from(s.trim_end()))
 9077                        .collect();
 9078                }
 9079
 9080                if !full_comment_prefixes.is_empty() {
 9081                    let first_prefix = full_comment_prefixes
 9082                        .first()
 9083                        .expect("prefixes is non-empty");
 9084                    let prefix_trimmed_lengths = full_comment_prefixes
 9085                        .iter()
 9086                        .map(|p| p.trim_end_matches(' ').len())
 9087                        .collect::<SmallVec<[usize; 4]>>();
 9088
 9089                    let mut all_selection_lines_are_comments = true;
 9090
 9091                    for row in start_row.0..=end_row.0 {
 9092                        let row = MultiBufferRow(row);
 9093                        if start_row < end_row && snapshot.is_line_blank(row) {
 9094                            continue;
 9095                        }
 9096
 9097                        let prefix_range = full_comment_prefixes
 9098                            .iter()
 9099                            .zip(prefix_trimmed_lengths.iter().copied())
 9100                            .map(|(prefix, trimmed_prefix_len)| {
 9101                                comment_prefix_range(
 9102                                    snapshot.deref(),
 9103                                    row,
 9104                                    &prefix[..trimmed_prefix_len],
 9105                                    &prefix[trimmed_prefix_len..],
 9106                                    ignore_indent,
 9107                                )
 9108                            })
 9109                            .max_by_key(|range| range.end.column - range.start.column)
 9110                            .expect("prefixes is non-empty");
 9111
 9112                        if prefix_range.is_empty() {
 9113                            all_selection_lines_are_comments = false;
 9114                        }
 9115
 9116                        selection_edit_ranges.push(prefix_range);
 9117                    }
 9118
 9119                    if all_selection_lines_are_comments {
 9120                        edits.extend(
 9121                            selection_edit_ranges
 9122                                .iter()
 9123                                .cloned()
 9124                                .map(|range| (range, empty_str.clone())),
 9125                        );
 9126                    } else {
 9127                        let min_column = selection_edit_ranges
 9128                            .iter()
 9129                            .map(|range| range.start.column)
 9130                            .min()
 9131                            .unwrap_or(0);
 9132                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9133                            let position = Point::new(range.start.row, min_column);
 9134                            (position..position, first_prefix.clone())
 9135                        }));
 9136                    }
 9137                } else if let Some((full_comment_prefix, comment_suffix)) =
 9138                    language.block_comment_delimiters()
 9139                {
 9140                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9141                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9142                    let prefix_range = comment_prefix_range(
 9143                        snapshot.deref(),
 9144                        start_row,
 9145                        comment_prefix,
 9146                        comment_prefix_whitespace,
 9147                        ignore_indent,
 9148                    );
 9149                    let suffix_range = comment_suffix_range(
 9150                        snapshot.deref(),
 9151                        end_row,
 9152                        comment_suffix.trim_start_matches(' '),
 9153                        comment_suffix.starts_with(' '),
 9154                    );
 9155
 9156                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9157                        edits.push((
 9158                            prefix_range.start..prefix_range.start,
 9159                            full_comment_prefix.clone(),
 9160                        ));
 9161                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9162                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9163                    } else {
 9164                        edits.push((prefix_range, empty_str.clone()));
 9165                        edits.push((suffix_range, empty_str.clone()));
 9166                    }
 9167                } else {
 9168                    continue;
 9169                }
 9170            }
 9171
 9172            drop(snapshot);
 9173            this.buffer.update(cx, |buffer, cx| {
 9174                buffer.edit(edits, None, cx);
 9175            });
 9176
 9177            // Adjust selections so that they end before any comment suffixes that
 9178            // were inserted.
 9179            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9180            let mut selections = this.selections.all::<Point>(cx);
 9181            let snapshot = this.buffer.read(cx).read(cx);
 9182            for selection in &mut selections {
 9183                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9184                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9185                        Ordering::Less => {
 9186                            suffixes_inserted.next();
 9187                            continue;
 9188                        }
 9189                        Ordering::Greater => break,
 9190                        Ordering::Equal => {
 9191                            if selection.end.column == snapshot.line_len(row) {
 9192                                if selection.is_empty() {
 9193                                    selection.start.column -= suffix_len as u32;
 9194                                }
 9195                                selection.end.column -= suffix_len as u32;
 9196                            }
 9197                            break;
 9198                        }
 9199                    }
 9200                }
 9201            }
 9202
 9203            drop(snapshot);
 9204            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9205
 9206            let selections = this.selections.all::<Point>(cx);
 9207            let selections_on_single_row = selections.windows(2).all(|selections| {
 9208                selections[0].start.row == selections[1].start.row
 9209                    && selections[0].end.row == selections[1].end.row
 9210                    && selections[0].start.row == selections[0].end.row
 9211            });
 9212            let selections_selecting = selections
 9213                .iter()
 9214                .any(|selection| selection.start != selection.end);
 9215            let advance_downwards = action.advance_downwards
 9216                && selections_on_single_row
 9217                && !selections_selecting
 9218                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9219
 9220            if advance_downwards {
 9221                let snapshot = this.buffer.read(cx).snapshot(cx);
 9222
 9223                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9224                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9225                        let mut point = display_point.to_point(display_snapshot);
 9226                        point.row += 1;
 9227                        point = snapshot.clip_point(point, Bias::Left);
 9228                        let display_point = point.to_display_point(display_snapshot);
 9229                        let goal = SelectionGoal::HorizontalPosition(
 9230                            display_snapshot
 9231                                .x_for_display_point(display_point, text_layout_details)
 9232                                .into(),
 9233                        );
 9234                        (display_point, goal)
 9235                    })
 9236                });
 9237            }
 9238        });
 9239    }
 9240
 9241    pub fn select_enclosing_symbol(
 9242        &mut self,
 9243        _: &SelectEnclosingSymbol,
 9244        cx: &mut ViewContext<Self>,
 9245    ) {
 9246        let buffer = self.buffer.read(cx).snapshot(cx);
 9247        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9248
 9249        fn update_selection(
 9250            selection: &Selection<usize>,
 9251            buffer_snap: &MultiBufferSnapshot,
 9252        ) -> Option<Selection<usize>> {
 9253            let cursor = selection.head();
 9254            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9255            for symbol in symbols.iter().rev() {
 9256                let start = symbol.range.start.to_offset(buffer_snap);
 9257                let end = symbol.range.end.to_offset(buffer_snap);
 9258                let new_range = start..end;
 9259                if start < selection.start || end > selection.end {
 9260                    return Some(Selection {
 9261                        id: selection.id,
 9262                        start: new_range.start,
 9263                        end: new_range.end,
 9264                        goal: SelectionGoal::None,
 9265                        reversed: selection.reversed,
 9266                    });
 9267                }
 9268            }
 9269            None
 9270        }
 9271
 9272        let mut selected_larger_symbol = false;
 9273        let new_selections = old_selections
 9274            .iter()
 9275            .map(|selection| match update_selection(selection, &buffer) {
 9276                Some(new_selection) => {
 9277                    if new_selection.range() != selection.range() {
 9278                        selected_larger_symbol = true;
 9279                    }
 9280                    new_selection
 9281                }
 9282                None => selection.clone(),
 9283            })
 9284            .collect::<Vec<_>>();
 9285
 9286        if selected_larger_symbol {
 9287            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9288                s.select(new_selections);
 9289            });
 9290        }
 9291    }
 9292
 9293    pub fn select_larger_syntax_node(
 9294        &mut self,
 9295        _: &SelectLargerSyntaxNode,
 9296        cx: &mut ViewContext<Self>,
 9297    ) {
 9298        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9299        let buffer = self.buffer.read(cx).snapshot(cx);
 9300        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9301
 9302        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9303        let mut selected_larger_node = false;
 9304        let new_selections = old_selections
 9305            .iter()
 9306            .map(|selection| {
 9307                let old_range = selection.start..selection.end;
 9308                let mut new_range = old_range.clone();
 9309                while let Some(containing_range) =
 9310                    buffer.range_for_syntax_ancestor(new_range.clone())
 9311                {
 9312                    new_range = containing_range;
 9313                    if !display_map.intersects_fold(new_range.start)
 9314                        && !display_map.intersects_fold(new_range.end)
 9315                    {
 9316                        break;
 9317                    }
 9318                }
 9319
 9320                selected_larger_node |= new_range != old_range;
 9321                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            .collect::<Vec<_>>();
 9330
 9331        if selected_larger_node {
 9332            stack.push(old_selections);
 9333            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9334                s.select(new_selections);
 9335            });
 9336        }
 9337        self.select_larger_syntax_node_stack = stack;
 9338    }
 9339
 9340    pub fn select_smaller_syntax_node(
 9341        &mut self,
 9342        _: &SelectSmallerSyntaxNode,
 9343        cx: &mut ViewContext<Self>,
 9344    ) {
 9345        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9346        if let Some(selections) = stack.pop() {
 9347            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9348                s.select(selections.to_vec());
 9349            });
 9350        }
 9351        self.select_larger_syntax_node_stack = stack;
 9352    }
 9353
 9354    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9355        if !EditorSettings::get_global(cx).gutter.runnables {
 9356            self.clear_tasks();
 9357            return Task::ready(());
 9358        }
 9359        let project = self.project.as_ref().map(Model::downgrade);
 9360        cx.spawn(|this, mut cx| async move {
 9361            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9362            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9363                return;
 9364            };
 9365            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9366                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9367            }) else {
 9368                return;
 9369            };
 9370
 9371            let hide_runnables = project
 9372                .update(&mut cx, |project, cx| {
 9373                    // Do not display any test indicators in non-dev server remote projects.
 9374                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9375                })
 9376                .unwrap_or(true);
 9377            if hide_runnables {
 9378                return;
 9379            }
 9380            let new_rows =
 9381                cx.background_executor()
 9382                    .spawn({
 9383                        let snapshot = display_snapshot.clone();
 9384                        async move {
 9385                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9386                        }
 9387                    })
 9388                    .await;
 9389            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9390
 9391            this.update(&mut cx, |this, _| {
 9392                this.clear_tasks();
 9393                for (key, value) in rows {
 9394                    this.insert_tasks(key, value);
 9395                }
 9396            })
 9397            .ok();
 9398        })
 9399    }
 9400    fn fetch_runnable_ranges(
 9401        snapshot: &DisplaySnapshot,
 9402        range: Range<Anchor>,
 9403    ) -> Vec<language::RunnableRange> {
 9404        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9405    }
 9406
 9407    fn runnable_rows(
 9408        project: Model<Project>,
 9409        snapshot: DisplaySnapshot,
 9410        runnable_ranges: Vec<RunnableRange>,
 9411        mut cx: AsyncWindowContext,
 9412    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9413        runnable_ranges
 9414            .into_iter()
 9415            .filter_map(|mut runnable| {
 9416                let tasks = cx
 9417                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9418                    .ok()?;
 9419                if tasks.is_empty() {
 9420                    return None;
 9421                }
 9422
 9423                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9424
 9425                let row = snapshot
 9426                    .buffer_snapshot
 9427                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9428                    .1
 9429                    .start
 9430                    .row;
 9431
 9432                let context_range =
 9433                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9434                Some((
 9435                    (runnable.buffer_id, row),
 9436                    RunnableTasks {
 9437                        templates: tasks,
 9438                        offset: MultiBufferOffset(runnable.run_range.start),
 9439                        context_range,
 9440                        column: point.column,
 9441                        extra_variables: runnable.extra_captures,
 9442                    },
 9443                ))
 9444            })
 9445            .collect()
 9446    }
 9447
 9448    fn templates_with_tags(
 9449        project: &Model<Project>,
 9450        runnable: &mut Runnable,
 9451        cx: &WindowContext<'_>,
 9452    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9453        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9454            let (worktree_id, file) = project
 9455                .buffer_for_id(runnable.buffer, cx)
 9456                .and_then(|buffer| buffer.read(cx).file())
 9457                .map(|file| (file.worktree_id(cx), file.clone()))
 9458                .unzip();
 9459
 9460            (
 9461                project.task_store().read(cx).task_inventory().cloned(),
 9462                worktree_id,
 9463                file,
 9464            )
 9465        });
 9466
 9467        let tags = mem::take(&mut runnable.tags);
 9468        let mut tags: Vec<_> = tags
 9469            .into_iter()
 9470            .flat_map(|tag| {
 9471                let tag = tag.0.clone();
 9472                inventory
 9473                    .as_ref()
 9474                    .into_iter()
 9475                    .flat_map(|inventory| {
 9476                        inventory.read(cx).list_tasks(
 9477                            file.clone(),
 9478                            Some(runnable.language.clone()),
 9479                            worktree_id,
 9480                            cx,
 9481                        )
 9482                    })
 9483                    .filter(move |(_, template)| {
 9484                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9485                    })
 9486            })
 9487            .sorted_by_key(|(kind, _)| kind.to_owned())
 9488            .collect();
 9489        if let Some((leading_tag_source, _)) = tags.first() {
 9490            // Strongest source wins; if we have worktree tag binding, prefer that to
 9491            // global and language bindings;
 9492            // if we have a global binding, prefer that to language binding.
 9493            let first_mismatch = tags
 9494                .iter()
 9495                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9496            if let Some(index) = first_mismatch {
 9497                tags.truncate(index);
 9498            }
 9499        }
 9500
 9501        tags
 9502    }
 9503
 9504    pub fn move_to_enclosing_bracket(
 9505        &mut self,
 9506        _: &MoveToEnclosingBracket,
 9507        cx: &mut ViewContext<Self>,
 9508    ) {
 9509        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9510            s.move_offsets_with(|snapshot, selection| {
 9511                let Some(enclosing_bracket_ranges) =
 9512                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9513                else {
 9514                    return;
 9515                };
 9516
 9517                let mut best_length = usize::MAX;
 9518                let mut best_inside = false;
 9519                let mut best_in_bracket_range = false;
 9520                let mut best_destination = None;
 9521                for (open, close) in enclosing_bracket_ranges {
 9522                    let close = close.to_inclusive();
 9523                    let length = close.end() - open.start;
 9524                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9525                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9526                        || close.contains(&selection.head());
 9527
 9528                    // If best is next to a bracket and current isn't, skip
 9529                    if !in_bracket_range && best_in_bracket_range {
 9530                        continue;
 9531                    }
 9532
 9533                    // Prefer smaller lengths unless best is inside and current isn't
 9534                    if length > best_length && (best_inside || !inside) {
 9535                        continue;
 9536                    }
 9537
 9538                    best_length = length;
 9539                    best_inside = inside;
 9540                    best_in_bracket_range = in_bracket_range;
 9541                    best_destination = Some(
 9542                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9543                            if inside {
 9544                                open.end
 9545                            } else {
 9546                                open.start
 9547                            }
 9548                        } else if inside {
 9549                            *close.start()
 9550                        } else {
 9551                            *close.end()
 9552                        },
 9553                    );
 9554                }
 9555
 9556                if let Some(destination) = best_destination {
 9557                    selection.collapse_to(destination, SelectionGoal::None);
 9558                }
 9559            })
 9560        });
 9561    }
 9562
 9563    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9564        self.end_selection(cx);
 9565        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9566        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9567            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9568            self.select_next_state = entry.select_next_state;
 9569            self.select_prev_state = entry.select_prev_state;
 9570            self.add_selections_state = entry.add_selections_state;
 9571            self.request_autoscroll(Autoscroll::newest(), cx);
 9572        }
 9573        self.selection_history.mode = SelectionHistoryMode::Normal;
 9574    }
 9575
 9576    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9577        self.end_selection(cx);
 9578        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9579        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9580            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9581            self.select_next_state = entry.select_next_state;
 9582            self.select_prev_state = entry.select_prev_state;
 9583            self.add_selections_state = entry.add_selections_state;
 9584            self.request_autoscroll(Autoscroll::newest(), cx);
 9585        }
 9586        self.selection_history.mode = SelectionHistoryMode::Normal;
 9587    }
 9588
 9589    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9590        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9591    }
 9592
 9593    pub fn expand_excerpts_down(
 9594        &mut self,
 9595        action: &ExpandExcerptsDown,
 9596        cx: &mut ViewContext<Self>,
 9597    ) {
 9598        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9599    }
 9600
 9601    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9602        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9603    }
 9604
 9605    pub fn expand_excerpts_for_direction(
 9606        &mut self,
 9607        lines: u32,
 9608        direction: ExpandExcerptDirection,
 9609        cx: &mut ViewContext<Self>,
 9610    ) {
 9611        let selections = self.selections.disjoint_anchors();
 9612
 9613        let lines = if lines == 0 {
 9614            EditorSettings::get_global(cx).expand_excerpt_lines
 9615        } else {
 9616            lines
 9617        };
 9618
 9619        self.buffer.update(cx, |buffer, cx| {
 9620            buffer.expand_excerpts(
 9621                selections
 9622                    .iter()
 9623                    .map(|selection| selection.head().excerpt_id)
 9624                    .dedup(),
 9625                lines,
 9626                direction,
 9627                cx,
 9628            )
 9629        })
 9630    }
 9631
 9632    pub fn expand_excerpt(
 9633        &mut self,
 9634        excerpt: ExcerptId,
 9635        direction: ExpandExcerptDirection,
 9636        cx: &mut ViewContext<Self>,
 9637    ) {
 9638        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9639        self.buffer.update(cx, |buffer, cx| {
 9640            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9641        })
 9642    }
 9643
 9644    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9645        self.go_to_diagnostic_impl(Direction::Next, cx)
 9646    }
 9647
 9648    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9649        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9650    }
 9651
 9652    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9653        let buffer = self.buffer.read(cx).snapshot(cx);
 9654        let selection = self.selections.newest::<usize>(cx);
 9655
 9656        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9657        if direction == Direction::Next {
 9658            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9659                let (group_id, jump_to) = popover.activation_info();
 9660                if self.activate_diagnostics(group_id, cx) {
 9661                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9662                        let mut new_selection = s.newest_anchor().clone();
 9663                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9664                        s.select_anchors(vec![new_selection.clone()]);
 9665                    });
 9666                }
 9667                return;
 9668            }
 9669        }
 9670
 9671        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9672            active_diagnostics
 9673                .primary_range
 9674                .to_offset(&buffer)
 9675                .to_inclusive()
 9676        });
 9677        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9678            if active_primary_range.contains(&selection.head()) {
 9679                *active_primary_range.start()
 9680            } else {
 9681                selection.head()
 9682            }
 9683        } else {
 9684            selection.head()
 9685        };
 9686        let snapshot = self.snapshot(cx);
 9687        loop {
 9688            let diagnostics = if direction == Direction::Prev {
 9689                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9690            } else {
 9691                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9692            }
 9693            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9694            let group = diagnostics
 9695                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9696                // be sorted in a stable way
 9697                // skip until we are at current active diagnostic, if it exists
 9698                .skip_while(|entry| {
 9699                    (match direction {
 9700                        Direction::Prev => entry.range.start >= search_start,
 9701                        Direction::Next => entry.range.start <= search_start,
 9702                    }) && self
 9703                        .active_diagnostics
 9704                        .as_ref()
 9705                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9706                })
 9707                .find_map(|entry| {
 9708                    if entry.diagnostic.is_primary
 9709                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9710                        && !entry.range.is_empty()
 9711                        // if we match with the active diagnostic, skip it
 9712                        && Some(entry.diagnostic.group_id)
 9713                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9714                    {
 9715                        Some((entry.range, entry.diagnostic.group_id))
 9716                    } else {
 9717                        None
 9718                    }
 9719                });
 9720
 9721            if let Some((primary_range, group_id)) = group {
 9722                if self.activate_diagnostics(group_id, cx) {
 9723                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9724                        s.select(vec![Selection {
 9725                            id: selection.id,
 9726                            start: primary_range.start,
 9727                            end: primary_range.start,
 9728                            reversed: false,
 9729                            goal: SelectionGoal::None,
 9730                        }]);
 9731                    });
 9732                }
 9733                break;
 9734            } else {
 9735                // Cycle around to the start of the buffer, potentially moving back to the start of
 9736                // the currently active diagnostic.
 9737                active_primary_range.take();
 9738                if direction == Direction::Prev {
 9739                    if search_start == buffer.len() {
 9740                        break;
 9741                    } else {
 9742                        search_start = buffer.len();
 9743                    }
 9744                } else if search_start == 0 {
 9745                    break;
 9746                } else {
 9747                    search_start = 0;
 9748                }
 9749            }
 9750        }
 9751    }
 9752
 9753    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9754        let snapshot = self
 9755            .display_map
 9756            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9757        let selection = self.selections.newest::<Point>(cx);
 9758        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9759    }
 9760
 9761    fn go_to_hunk_after_position(
 9762        &mut self,
 9763        snapshot: &DisplaySnapshot,
 9764        position: Point,
 9765        cx: &mut ViewContext<'_, Editor>,
 9766    ) -> Option<MultiBufferDiffHunk> {
 9767        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9768            snapshot,
 9769            position,
 9770            false,
 9771            snapshot
 9772                .buffer_snapshot
 9773                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9774            cx,
 9775        ) {
 9776            return Some(hunk);
 9777        }
 9778
 9779        let wrapped_point = Point::zero();
 9780        self.go_to_next_hunk_in_direction(
 9781            snapshot,
 9782            wrapped_point,
 9783            true,
 9784            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9785                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9786            ),
 9787            cx,
 9788        )
 9789    }
 9790
 9791    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9792        let snapshot = self
 9793            .display_map
 9794            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9795        let selection = self.selections.newest::<Point>(cx);
 9796
 9797        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9798    }
 9799
 9800    fn go_to_hunk_before_position(
 9801        &mut self,
 9802        snapshot: &DisplaySnapshot,
 9803        position: Point,
 9804        cx: &mut ViewContext<'_, Editor>,
 9805    ) -> Option<MultiBufferDiffHunk> {
 9806        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9807            snapshot,
 9808            position,
 9809            false,
 9810            snapshot
 9811                .buffer_snapshot
 9812                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9813            cx,
 9814        ) {
 9815            return Some(hunk);
 9816        }
 9817
 9818        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9819        self.go_to_next_hunk_in_direction(
 9820            snapshot,
 9821            wrapped_point,
 9822            true,
 9823            snapshot
 9824                .buffer_snapshot
 9825                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9826            cx,
 9827        )
 9828    }
 9829
 9830    fn go_to_next_hunk_in_direction(
 9831        &mut self,
 9832        snapshot: &DisplaySnapshot,
 9833        initial_point: Point,
 9834        is_wrapped: bool,
 9835        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9836        cx: &mut ViewContext<Editor>,
 9837    ) -> Option<MultiBufferDiffHunk> {
 9838        let display_point = initial_point.to_display_point(snapshot);
 9839        let mut hunks = hunks
 9840            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9841            .filter(|(display_hunk, _)| {
 9842                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9843            })
 9844            .dedup();
 9845
 9846        if let Some((display_hunk, hunk)) = hunks.next() {
 9847            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9848                let row = display_hunk.start_display_row();
 9849                let point = DisplayPoint::new(row, 0);
 9850                s.select_display_ranges([point..point]);
 9851            });
 9852
 9853            Some(hunk)
 9854        } else {
 9855            None
 9856        }
 9857    }
 9858
 9859    pub fn go_to_definition(
 9860        &mut self,
 9861        _: &GoToDefinition,
 9862        cx: &mut ViewContext<Self>,
 9863    ) -> Task<Result<Navigated>> {
 9864        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9865        cx.spawn(|editor, mut cx| async move {
 9866            if definition.await? == Navigated::Yes {
 9867                return Ok(Navigated::Yes);
 9868            }
 9869            match editor.update(&mut cx, |editor, cx| {
 9870                editor.find_all_references(&FindAllReferences, cx)
 9871            })? {
 9872                Some(references) => references.await,
 9873                None => Ok(Navigated::No),
 9874            }
 9875        })
 9876    }
 9877
 9878    pub fn go_to_declaration(
 9879        &mut self,
 9880        _: &GoToDeclaration,
 9881        cx: &mut ViewContext<Self>,
 9882    ) -> Task<Result<Navigated>> {
 9883        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9884    }
 9885
 9886    pub fn go_to_declaration_split(
 9887        &mut self,
 9888        _: &GoToDeclaration,
 9889        cx: &mut ViewContext<Self>,
 9890    ) -> Task<Result<Navigated>> {
 9891        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9892    }
 9893
 9894    pub fn go_to_implementation(
 9895        &mut self,
 9896        _: &GoToImplementation,
 9897        cx: &mut ViewContext<Self>,
 9898    ) -> Task<Result<Navigated>> {
 9899        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9900    }
 9901
 9902    pub fn go_to_implementation_split(
 9903        &mut self,
 9904        _: &GoToImplementationSplit,
 9905        cx: &mut ViewContext<Self>,
 9906    ) -> Task<Result<Navigated>> {
 9907        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9908    }
 9909
 9910    pub fn go_to_type_definition(
 9911        &mut self,
 9912        _: &GoToTypeDefinition,
 9913        cx: &mut ViewContext<Self>,
 9914    ) -> Task<Result<Navigated>> {
 9915        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9916    }
 9917
 9918    pub fn go_to_definition_split(
 9919        &mut self,
 9920        _: &GoToDefinitionSplit,
 9921        cx: &mut ViewContext<Self>,
 9922    ) -> Task<Result<Navigated>> {
 9923        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9924    }
 9925
 9926    pub fn go_to_type_definition_split(
 9927        &mut self,
 9928        _: &GoToTypeDefinitionSplit,
 9929        cx: &mut ViewContext<Self>,
 9930    ) -> Task<Result<Navigated>> {
 9931        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9932    }
 9933
 9934    fn go_to_definition_of_kind(
 9935        &mut self,
 9936        kind: GotoDefinitionKind,
 9937        split: bool,
 9938        cx: &mut ViewContext<Self>,
 9939    ) -> Task<Result<Navigated>> {
 9940        let Some(provider) = self.semantics_provider.clone() else {
 9941            return Task::ready(Ok(Navigated::No));
 9942        };
 9943        let head = self.selections.newest::<usize>(cx).head();
 9944        let buffer = self.buffer.read(cx);
 9945        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9946            text_anchor
 9947        } else {
 9948            return Task::ready(Ok(Navigated::No));
 9949        };
 9950
 9951        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9952            return Task::ready(Ok(Navigated::No));
 9953        };
 9954
 9955        cx.spawn(|editor, mut cx| async move {
 9956            let definitions = definitions.await?;
 9957            let navigated = editor
 9958                .update(&mut cx, |editor, cx| {
 9959                    editor.navigate_to_hover_links(
 9960                        Some(kind),
 9961                        definitions
 9962                            .into_iter()
 9963                            .filter(|location| {
 9964                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9965                            })
 9966                            .map(HoverLink::Text)
 9967                            .collect::<Vec<_>>(),
 9968                        split,
 9969                        cx,
 9970                    )
 9971                })?
 9972                .await?;
 9973            anyhow::Ok(navigated)
 9974        })
 9975    }
 9976
 9977    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9978        let position = self.selections.newest_anchor().head();
 9979        let Some((buffer, buffer_position)) =
 9980            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9981        else {
 9982            return;
 9983        };
 9984
 9985        cx.spawn(|editor, mut cx| async move {
 9986            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9987                editor.update(&mut cx, |_, cx| {
 9988                    cx.open_url(&url);
 9989                })
 9990            } else {
 9991                Ok(())
 9992            }
 9993        })
 9994        .detach();
 9995    }
 9996
 9997    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9998        let Some(workspace) = self.workspace() else {
 9999            return;
10000        };
10001
10002        let position = self.selections.newest_anchor().head();
10003
10004        let Some((buffer, buffer_position)) =
10005            self.buffer.read(cx).text_anchor_for_position(position, cx)
10006        else {
10007            return;
10008        };
10009
10010        let project = self.project.clone();
10011
10012        cx.spawn(|_, mut cx| async move {
10013            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10014
10015            if let Some((_, path)) = result {
10016                workspace
10017                    .update(&mut cx, |workspace, cx| {
10018                        workspace.open_resolved_path(path, cx)
10019                    })?
10020                    .await?;
10021            }
10022            anyhow::Ok(())
10023        })
10024        .detach();
10025    }
10026
10027    pub(crate) fn navigate_to_hover_links(
10028        &mut self,
10029        kind: Option<GotoDefinitionKind>,
10030        mut definitions: Vec<HoverLink>,
10031        split: bool,
10032        cx: &mut ViewContext<Editor>,
10033    ) -> Task<Result<Navigated>> {
10034        // If there is one definition, just open it directly
10035        if definitions.len() == 1 {
10036            let definition = definitions.pop().unwrap();
10037
10038            enum TargetTaskResult {
10039                Location(Option<Location>),
10040                AlreadyNavigated,
10041            }
10042
10043            let target_task = match definition {
10044                HoverLink::Text(link) => {
10045                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10046                }
10047                HoverLink::InlayHint(lsp_location, server_id) => {
10048                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10049                    cx.background_executor().spawn(async move {
10050                        let location = computation.await?;
10051                        Ok(TargetTaskResult::Location(location))
10052                    })
10053                }
10054                HoverLink::Url(url) => {
10055                    cx.open_url(&url);
10056                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10057                }
10058                HoverLink::File(path) => {
10059                    if let Some(workspace) = self.workspace() {
10060                        cx.spawn(|_, mut cx| async move {
10061                            workspace
10062                                .update(&mut cx, |workspace, cx| {
10063                                    workspace.open_resolved_path(path, cx)
10064                                })?
10065                                .await
10066                                .map(|_| TargetTaskResult::AlreadyNavigated)
10067                        })
10068                    } else {
10069                        Task::ready(Ok(TargetTaskResult::Location(None)))
10070                    }
10071                }
10072            };
10073            cx.spawn(|editor, mut cx| async move {
10074                let target = match target_task.await.context("target resolution task")? {
10075                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10076                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10077                    TargetTaskResult::Location(Some(target)) => target,
10078                };
10079
10080                editor.update(&mut cx, |editor, cx| {
10081                    let Some(workspace) = editor.workspace() else {
10082                        return Navigated::No;
10083                    };
10084                    let pane = workspace.read(cx).active_pane().clone();
10085
10086                    let range = target.range.to_offset(target.buffer.read(cx));
10087                    let range = editor.range_for_match(&range);
10088
10089                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10090                        let buffer = target.buffer.read(cx);
10091                        let range = check_multiline_range(buffer, range);
10092                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10093                            s.select_ranges([range]);
10094                        });
10095                    } else {
10096                        cx.window_context().defer(move |cx| {
10097                            let target_editor: View<Self> =
10098                                workspace.update(cx, |workspace, cx| {
10099                                    let pane = if split {
10100                                        workspace.adjacent_pane(cx)
10101                                    } else {
10102                                        workspace.active_pane().clone()
10103                                    };
10104
10105                                    workspace.open_project_item(
10106                                        pane,
10107                                        target.buffer.clone(),
10108                                        true,
10109                                        true,
10110                                        cx,
10111                                    )
10112                                });
10113                            target_editor.update(cx, |target_editor, cx| {
10114                                // When selecting a definition in a different buffer, disable the nav history
10115                                // to avoid creating a history entry at the previous cursor location.
10116                                pane.update(cx, |pane, _| pane.disable_history());
10117                                let buffer = target.buffer.read(cx);
10118                                let range = check_multiline_range(buffer, range);
10119                                target_editor.change_selections(
10120                                    Some(Autoscroll::focused()),
10121                                    cx,
10122                                    |s| {
10123                                        s.select_ranges([range]);
10124                                    },
10125                                );
10126                                pane.update(cx, |pane, _| pane.enable_history());
10127                            });
10128                        });
10129                    }
10130                    Navigated::Yes
10131                })
10132            })
10133        } else if !definitions.is_empty() {
10134            cx.spawn(|editor, mut cx| async move {
10135                let (title, location_tasks, workspace) = editor
10136                    .update(&mut cx, |editor, cx| {
10137                        let tab_kind = match kind {
10138                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10139                            _ => "Definitions",
10140                        };
10141                        let title = definitions
10142                            .iter()
10143                            .find_map(|definition| match definition {
10144                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10145                                    let buffer = origin.buffer.read(cx);
10146                                    format!(
10147                                        "{} for {}",
10148                                        tab_kind,
10149                                        buffer
10150                                            .text_for_range(origin.range.clone())
10151                                            .collect::<String>()
10152                                    )
10153                                }),
10154                                HoverLink::InlayHint(_, _) => None,
10155                                HoverLink::Url(_) => None,
10156                                HoverLink::File(_) => None,
10157                            })
10158                            .unwrap_or(tab_kind.to_string());
10159                        let location_tasks = definitions
10160                            .into_iter()
10161                            .map(|definition| match definition {
10162                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10163                                HoverLink::InlayHint(lsp_location, server_id) => {
10164                                    editor.compute_target_location(lsp_location, server_id, cx)
10165                                }
10166                                HoverLink::Url(_) => Task::ready(Ok(None)),
10167                                HoverLink::File(_) => Task::ready(Ok(None)),
10168                            })
10169                            .collect::<Vec<_>>();
10170                        (title, location_tasks, editor.workspace().clone())
10171                    })
10172                    .context("location tasks preparation")?;
10173
10174                let locations = future::join_all(location_tasks)
10175                    .await
10176                    .into_iter()
10177                    .filter_map(|location| location.transpose())
10178                    .collect::<Result<_>>()
10179                    .context("location tasks")?;
10180
10181                let Some(workspace) = workspace else {
10182                    return Ok(Navigated::No);
10183                };
10184                let opened = workspace
10185                    .update(&mut cx, |workspace, cx| {
10186                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10187                    })
10188                    .ok();
10189
10190                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10191            })
10192        } else {
10193            Task::ready(Ok(Navigated::No))
10194        }
10195    }
10196
10197    fn compute_target_location(
10198        &self,
10199        lsp_location: lsp::Location,
10200        server_id: LanguageServerId,
10201        cx: &mut ViewContext<Self>,
10202    ) -> Task<anyhow::Result<Option<Location>>> {
10203        let Some(project) = self.project.clone() else {
10204            return Task::Ready(Some(Ok(None)));
10205        };
10206
10207        cx.spawn(move |editor, mut cx| async move {
10208            let location_task = editor.update(&mut cx, |_, cx| {
10209                project.update(cx, |project, cx| {
10210                    let language_server_name = project
10211                        .language_server_statuses(cx)
10212                        .find(|(id, _)| server_id == *id)
10213                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10214                    language_server_name.map(|language_server_name| {
10215                        project.open_local_buffer_via_lsp(
10216                            lsp_location.uri.clone(),
10217                            server_id,
10218                            language_server_name,
10219                            cx,
10220                        )
10221                    })
10222                })
10223            })?;
10224            let location = match location_task {
10225                Some(task) => Some({
10226                    let target_buffer_handle = task.await.context("open local buffer")?;
10227                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10228                        let target_start = target_buffer
10229                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10230                        let target_end = target_buffer
10231                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10232                        target_buffer.anchor_after(target_start)
10233                            ..target_buffer.anchor_before(target_end)
10234                    })?;
10235                    Location {
10236                        buffer: target_buffer_handle,
10237                        range,
10238                    }
10239                }),
10240                None => None,
10241            };
10242            Ok(location)
10243        })
10244    }
10245
10246    pub fn find_all_references(
10247        &mut self,
10248        _: &FindAllReferences,
10249        cx: &mut ViewContext<Self>,
10250    ) -> Option<Task<Result<Navigated>>> {
10251        let selection = self.selections.newest::<usize>(cx);
10252        let multi_buffer = self.buffer.read(cx);
10253        let head = selection.head();
10254
10255        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10256        let head_anchor = multi_buffer_snapshot.anchor_at(
10257            head,
10258            if head < selection.tail() {
10259                Bias::Right
10260            } else {
10261                Bias::Left
10262            },
10263        );
10264
10265        match self
10266            .find_all_references_task_sources
10267            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10268        {
10269            Ok(_) => {
10270                log::info!(
10271                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10272                );
10273                return None;
10274            }
10275            Err(i) => {
10276                self.find_all_references_task_sources.insert(i, head_anchor);
10277            }
10278        }
10279
10280        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10281        let workspace = self.workspace()?;
10282        let project = workspace.read(cx).project().clone();
10283        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10284        Some(cx.spawn(|editor, mut cx| async move {
10285            let _cleanup = defer({
10286                let mut cx = cx.clone();
10287                move || {
10288                    let _ = editor.update(&mut cx, |editor, _| {
10289                        if let Ok(i) =
10290                            editor
10291                                .find_all_references_task_sources
10292                                .binary_search_by(|anchor| {
10293                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10294                                })
10295                        {
10296                            editor.find_all_references_task_sources.remove(i);
10297                        }
10298                    });
10299                }
10300            });
10301
10302            let locations = references.await?;
10303            if locations.is_empty() {
10304                return anyhow::Ok(Navigated::No);
10305            }
10306
10307            workspace.update(&mut cx, |workspace, cx| {
10308                let title = locations
10309                    .first()
10310                    .as_ref()
10311                    .map(|location| {
10312                        let buffer = location.buffer.read(cx);
10313                        format!(
10314                            "References to `{}`",
10315                            buffer
10316                                .text_for_range(location.range.clone())
10317                                .collect::<String>()
10318                        )
10319                    })
10320                    .unwrap();
10321                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10322                Navigated::Yes
10323            })
10324        }))
10325    }
10326
10327    /// Opens a multibuffer with the given project locations in it
10328    pub fn open_locations_in_multibuffer(
10329        workspace: &mut Workspace,
10330        mut locations: Vec<Location>,
10331        title: String,
10332        split: bool,
10333        cx: &mut ViewContext<Workspace>,
10334    ) {
10335        // If there are multiple definitions, open them in a multibuffer
10336        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10337        let mut locations = locations.into_iter().peekable();
10338        let mut ranges_to_highlight = Vec::new();
10339        let capability = workspace.project().read(cx).capability();
10340
10341        let excerpt_buffer = cx.new_model(|cx| {
10342            let mut multibuffer = MultiBuffer::new(capability);
10343            while let Some(location) = locations.next() {
10344                let buffer = location.buffer.read(cx);
10345                let mut ranges_for_buffer = Vec::new();
10346                let range = location.range.to_offset(buffer);
10347                ranges_for_buffer.push(range.clone());
10348
10349                while let Some(next_location) = locations.peek() {
10350                    if next_location.buffer == location.buffer {
10351                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10352                        locations.next();
10353                    } else {
10354                        break;
10355                    }
10356                }
10357
10358                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10359                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10360                    location.buffer.clone(),
10361                    ranges_for_buffer,
10362                    DEFAULT_MULTIBUFFER_CONTEXT,
10363                    cx,
10364                ))
10365            }
10366
10367            multibuffer.with_title(title)
10368        });
10369
10370        let editor = cx.new_view(|cx| {
10371            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10372        });
10373        editor.update(cx, |editor, cx| {
10374            if let Some(first_range) = ranges_to_highlight.first() {
10375                editor.change_selections(None, cx, |selections| {
10376                    selections.clear_disjoint();
10377                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10378                });
10379            }
10380            editor.highlight_background::<Self>(
10381                &ranges_to_highlight,
10382                |theme| theme.editor_highlighted_line_background,
10383                cx,
10384            );
10385        });
10386
10387        let item = Box::new(editor);
10388        let item_id = item.item_id();
10389
10390        if split {
10391            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10392        } else {
10393            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10394                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10395                    pane.close_current_preview_item(cx)
10396                } else {
10397                    None
10398                }
10399            });
10400            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10401        }
10402        workspace.active_pane().update(cx, |pane, cx| {
10403            pane.set_preview_item_id(Some(item_id), cx);
10404        });
10405    }
10406
10407    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10408        use language::ToOffset as _;
10409
10410        let provider = self.semantics_provider.clone()?;
10411        let selection = self.selections.newest_anchor().clone();
10412        let (cursor_buffer, cursor_buffer_position) = self
10413            .buffer
10414            .read(cx)
10415            .text_anchor_for_position(selection.head(), cx)?;
10416        let (tail_buffer, cursor_buffer_position_end) = self
10417            .buffer
10418            .read(cx)
10419            .text_anchor_for_position(selection.tail(), cx)?;
10420        if tail_buffer != cursor_buffer {
10421            return None;
10422        }
10423
10424        let snapshot = cursor_buffer.read(cx).snapshot();
10425        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10426        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10427        let prepare_rename = provider
10428            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10429            .unwrap_or_else(|| Task::ready(Ok(None)));
10430        drop(snapshot);
10431
10432        Some(cx.spawn(|this, mut cx| async move {
10433            let rename_range = if let Some(range) = prepare_rename.await? {
10434                Some(range)
10435            } else {
10436                this.update(&mut cx, |this, cx| {
10437                    let buffer = this.buffer.read(cx).snapshot(cx);
10438                    let mut buffer_highlights = this
10439                        .document_highlights_for_position(selection.head(), &buffer)
10440                        .filter(|highlight| {
10441                            highlight.start.excerpt_id == selection.head().excerpt_id
10442                                && highlight.end.excerpt_id == selection.head().excerpt_id
10443                        });
10444                    buffer_highlights
10445                        .next()
10446                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10447                })?
10448            };
10449            if let Some(rename_range) = rename_range {
10450                this.update(&mut cx, |this, cx| {
10451                    let snapshot = cursor_buffer.read(cx).snapshot();
10452                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10453                    let cursor_offset_in_rename_range =
10454                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10455                    let cursor_offset_in_rename_range_end =
10456                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10457
10458                    this.take_rename(false, cx);
10459                    let buffer = this.buffer.read(cx).read(cx);
10460                    let cursor_offset = selection.head().to_offset(&buffer);
10461                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10462                    let rename_end = rename_start + rename_buffer_range.len();
10463                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10464                    let mut old_highlight_id = None;
10465                    let old_name: Arc<str> = buffer
10466                        .chunks(rename_start..rename_end, true)
10467                        .map(|chunk| {
10468                            if old_highlight_id.is_none() {
10469                                old_highlight_id = chunk.syntax_highlight_id;
10470                            }
10471                            chunk.text
10472                        })
10473                        .collect::<String>()
10474                        .into();
10475
10476                    drop(buffer);
10477
10478                    // Position the selection in the rename editor so that it matches the current selection.
10479                    this.show_local_selections = false;
10480                    let rename_editor = cx.new_view(|cx| {
10481                        let mut editor = Editor::single_line(cx);
10482                        editor.buffer.update(cx, |buffer, cx| {
10483                            buffer.edit([(0..0, old_name.clone())], None, cx)
10484                        });
10485                        let rename_selection_range = match cursor_offset_in_rename_range
10486                            .cmp(&cursor_offset_in_rename_range_end)
10487                        {
10488                            Ordering::Equal => {
10489                                editor.select_all(&SelectAll, cx);
10490                                return editor;
10491                            }
10492                            Ordering::Less => {
10493                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10494                            }
10495                            Ordering::Greater => {
10496                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10497                            }
10498                        };
10499                        if rename_selection_range.end > old_name.len() {
10500                            editor.select_all(&SelectAll, cx);
10501                        } else {
10502                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10503                                s.select_ranges([rename_selection_range]);
10504                            });
10505                        }
10506                        editor
10507                    });
10508                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10509                        if e == &EditorEvent::Focused {
10510                            cx.emit(EditorEvent::FocusedIn)
10511                        }
10512                    })
10513                    .detach();
10514
10515                    let write_highlights =
10516                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10517                    let read_highlights =
10518                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10519                    let ranges = write_highlights
10520                        .iter()
10521                        .flat_map(|(_, ranges)| ranges.iter())
10522                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10523                        .cloned()
10524                        .collect();
10525
10526                    this.highlight_text::<Rename>(
10527                        ranges,
10528                        HighlightStyle {
10529                            fade_out: Some(0.6),
10530                            ..Default::default()
10531                        },
10532                        cx,
10533                    );
10534                    let rename_focus_handle = rename_editor.focus_handle(cx);
10535                    cx.focus(&rename_focus_handle);
10536                    let block_id = this.insert_blocks(
10537                        [BlockProperties {
10538                            style: BlockStyle::Flex,
10539                            placement: BlockPlacement::Below(range.start),
10540                            height: 1,
10541                            render: Arc::new({
10542                                let rename_editor = rename_editor.clone();
10543                                move |cx: &mut BlockContext| {
10544                                    let mut text_style = cx.editor_style.text.clone();
10545                                    if let Some(highlight_style) = old_highlight_id
10546                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10547                                    {
10548                                        text_style = text_style.highlight(highlight_style);
10549                                    }
10550                                    div()
10551                                        .block_mouse_down()
10552                                        .pl(cx.anchor_x)
10553                                        .child(EditorElement::new(
10554                                            &rename_editor,
10555                                            EditorStyle {
10556                                                background: cx.theme().system().transparent,
10557                                                local_player: cx.editor_style.local_player,
10558                                                text: text_style,
10559                                                scrollbar_width: cx.editor_style.scrollbar_width,
10560                                                syntax: cx.editor_style.syntax.clone(),
10561                                                status: cx.editor_style.status.clone(),
10562                                                inlay_hints_style: HighlightStyle {
10563                                                    font_weight: Some(FontWeight::BOLD),
10564                                                    ..make_inlay_hints_style(cx)
10565                                                },
10566                                                suggestions_style: HighlightStyle {
10567                                                    color: Some(cx.theme().status().predictive),
10568                                                    ..HighlightStyle::default()
10569                                                },
10570                                                ..EditorStyle::default()
10571                                            },
10572                                        ))
10573                                        .into_any_element()
10574                                }
10575                            }),
10576                            priority: 0,
10577                        }],
10578                        Some(Autoscroll::fit()),
10579                        cx,
10580                    )[0];
10581                    this.pending_rename = Some(RenameState {
10582                        range,
10583                        old_name,
10584                        editor: rename_editor,
10585                        block_id,
10586                    });
10587                })?;
10588            }
10589
10590            Ok(())
10591        }))
10592    }
10593
10594    pub fn confirm_rename(
10595        &mut self,
10596        _: &ConfirmRename,
10597        cx: &mut ViewContext<Self>,
10598    ) -> Option<Task<Result<()>>> {
10599        let rename = self.take_rename(false, cx)?;
10600        let workspace = self.workspace()?.downgrade();
10601        let (buffer, start) = self
10602            .buffer
10603            .read(cx)
10604            .text_anchor_for_position(rename.range.start, cx)?;
10605        let (end_buffer, _) = self
10606            .buffer
10607            .read(cx)
10608            .text_anchor_for_position(rename.range.end, cx)?;
10609        if buffer != end_buffer {
10610            return None;
10611        }
10612
10613        let old_name = rename.old_name;
10614        let new_name = rename.editor.read(cx).text(cx);
10615
10616        let rename = self.semantics_provider.as_ref()?.perform_rename(
10617            &buffer,
10618            start,
10619            new_name.clone(),
10620            cx,
10621        )?;
10622
10623        Some(cx.spawn(|editor, mut cx| async move {
10624            let project_transaction = rename.await?;
10625            Self::open_project_transaction(
10626                &editor,
10627                workspace,
10628                project_transaction,
10629                format!("Rename: {}{}", old_name, new_name),
10630                cx.clone(),
10631            )
10632            .await?;
10633
10634            editor.update(&mut cx, |editor, cx| {
10635                editor.refresh_document_highlights(cx);
10636            })?;
10637            Ok(())
10638        }))
10639    }
10640
10641    fn take_rename(
10642        &mut self,
10643        moving_cursor: bool,
10644        cx: &mut ViewContext<Self>,
10645    ) -> Option<RenameState> {
10646        let rename = self.pending_rename.take()?;
10647        if rename.editor.focus_handle(cx).is_focused(cx) {
10648            cx.focus(&self.focus_handle);
10649        }
10650
10651        self.remove_blocks(
10652            [rename.block_id].into_iter().collect(),
10653            Some(Autoscroll::fit()),
10654            cx,
10655        );
10656        self.clear_highlights::<Rename>(cx);
10657        self.show_local_selections = true;
10658
10659        if moving_cursor {
10660            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10661                editor.selections.newest::<usize>(cx).head()
10662            });
10663
10664            // Update the selection to match the position of the selection inside
10665            // the rename editor.
10666            let snapshot = self.buffer.read(cx).read(cx);
10667            let rename_range = rename.range.to_offset(&snapshot);
10668            let cursor_in_editor = snapshot
10669                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10670                .min(rename_range.end);
10671            drop(snapshot);
10672
10673            self.change_selections(None, cx, |s| {
10674                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10675            });
10676        } else {
10677            self.refresh_document_highlights(cx);
10678        }
10679
10680        Some(rename)
10681    }
10682
10683    pub fn pending_rename(&self) -> Option<&RenameState> {
10684        self.pending_rename.as_ref()
10685    }
10686
10687    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10688        let project = match &self.project {
10689            Some(project) => project.clone(),
10690            None => return None,
10691        };
10692
10693        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10694    }
10695
10696    fn format_selections(
10697        &mut self,
10698        _: &FormatSelections,
10699        cx: &mut ViewContext<Self>,
10700    ) -> Option<Task<Result<()>>> {
10701        let project = match &self.project {
10702            Some(project) => project.clone(),
10703            None => return None,
10704        };
10705
10706        let selections = self
10707            .selections
10708            .all_adjusted(cx)
10709            .into_iter()
10710            .filter(|s| !s.is_empty())
10711            .collect_vec();
10712
10713        Some(self.perform_format(
10714            project,
10715            FormatTrigger::Manual,
10716            FormatTarget::Ranges(selections),
10717            cx,
10718        ))
10719    }
10720
10721    fn perform_format(
10722        &mut self,
10723        project: Model<Project>,
10724        trigger: FormatTrigger,
10725        target: FormatTarget,
10726        cx: &mut ViewContext<Self>,
10727    ) -> Task<Result<()>> {
10728        let buffer = self.buffer().clone();
10729        let mut buffers = buffer.read(cx).all_buffers();
10730        if trigger == FormatTrigger::Save {
10731            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10732        }
10733
10734        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10735        let format = project.update(cx, |project, cx| {
10736            project.format(buffers, true, trigger, target, cx)
10737        });
10738
10739        cx.spawn(|_, mut cx| async move {
10740            let transaction = futures::select_biased! {
10741                () = timeout => {
10742                    log::warn!("timed out waiting for formatting");
10743                    None
10744                }
10745                transaction = format.log_err().fuse() => transaction,
10746            };
10747
10748            buffer
10749                .update(&mut cx, |buffer, cx| {
10750                    if let Some(transaction) = transaction {
10751                        if !buffer.is_singleton() {
10752                            buffer.push_transaction(&transaction.0, cx);
10753                        }
10754                    }
10755
10756                    cx.notify();
10757                })
10758                .ok();
10759
10760            Ok(())
10761        })
10762    }
10763
10764    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10765        if let Some(project) = self.project.clone() {
10766            self.buffer.update(cx, |multi_buffer, cx| {
10767                project.update(cx, |project, cx| {
10768                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10769                });
10770            })
10771        }
10772    }
10773
10774    fn cancel_language_server_work(
10775        &mut self,
10776        _: &actions::CancelLanguageServerWork,
10777        cx: &mut ViewContext<Self>,
10778    ) {
10779        if let Some(project) = self.project.clone() {
10780            self.buffer.update(cx, |multi_buffer, cx| {
10781                project.update(cx, |project, cx| {
10782                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10783                });
10784            })
10785        }
10786    }
10787
10788    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10789        cx.show_character_palette();
10790    }
10791
10792    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10793        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10794            let buffer = self.buffer.read(cx).snapshot(cx);
10795            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10796            let is_valid = buffer
10797                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10798                .any(|entry| {
10799                    entry.diagnostic.is_primary
10800                        && !entry.range.is_empty()
10801                        && entry.range.start == primary_range_start
10802                        && entry.diagnostic.message == active_diagnostics.primary_message
10803                });
10804
10805            if is_valid != active_diagnostics.is_valid {
10806                active_diagnostics.is_valid = is_valid;
10807                let mut new_styles = HashMap::default();
10808                for (block_id, diagnostic) in &active_diagnostics.blocks {
10809                    new_styles.insert(
10810                        *block_id,
10811                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10812                    );
10813                }
10814                self.display_map.update(cx, |display_map, _cx| {
10815                    display_map.replace_blocks(new_styles)
10816                });
10817            }
10818        }
10819    }
10820
10821    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10822        self.dismiss_diagnostics(cx);
10823        let snapshot = self.snapshot(cx);
10824        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10825            let buffer = self.buffer.read(cx).snapshot(cx);
10826
10827            let mut primary_range = None;
10828            let mut primary_message = None;
10829            let mut group_end = Point::zero();
10830            let diagnostic_group = buffer
10831                .diagnostic_group::<MultiBufferPoint>(group_id)
10832                .filter_map(|entry| {
10833                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10834                        && (entry.range.start.row == entry.range.end.row
10835                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10836                    {
10837                        return None;
10838                    }
10839                    if entry.range.end > group_end {
10840                        group_end = entry.range.end;
10841                    }
10842                    if entry.diagnostic.is_primary {
10843                        primary_range = Some(entry.range.clone());
10844                        primary_message = Some(entry.diagnostic.message.clone());
10845                    }
10846                    Some(entry)
10847                })
10848                .collect::<Vec<_>>();
10849            let primary_range = primary_range?;
10850            let primary_message = primary_message?;
10851            let primary_range =
10852                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10853
10854            let blocks = display_map
10855                .insert_blocks(
10856                    diagnostic_group.iter().map(|entry| {
10857                        let diagnostic = entry.diagnostic.clone();
10858                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10859                        BlockProperties {
10860                            style: BlockStyle::Fixed,
10861                            placement: BlockPlacement::Below(
10862                                buffer.anchor_after(entry.range.start),
10863                            ),
10864                            height: message_height,
10865                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10866                            priority: 0,
10867                        }
10868                    }),
10869                    cx,
10870                )
10871                .into_iter()
10872                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10873                .collect();
10874
10875            Some(ActiveDiagnosticGroup {
10876                primary_range,
10877                primary_message,
10878                group_id,
10879                blocks,
10880                is_valid: true,
10881            })
10882        });
10883        self.active_diagnostics.is_some()
10884    }
10885
10886    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10887        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10888            self.display_map.update(cx, |display_map, cx| {
10889                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10890            });
10891            cx.notify();
10892        }
10893    }
10894
10895    pub fn set_selections_from_remote(
10896        &mut self,
10897        selections: Vec<Selection<Anchor>>,
10898        pending_selection: Option<Selection<Anchor>>,
10899        cx: &mut ViewContext<Self>,
10900    ) {
10901        let old_cursor_position = self.selections.newest_anchor().head();
10902        self.selections.change_with(cx, |s| {
10903            s.select_anchors(selections);
10904            if let Some(pending_selection) = pending_selection {
10905                s.set_pending(pending_selection, SelectMode::Character);
10906            } else {
10907                s.clear_pending();
10908            }
10909        });
10910        self.selections_did_change(false, &old_cursor_position, true, cx);
10911    }
10912
10913    fn push_to_selection_history(&mut self) {
10914        self.selection_history.push(SelectionHistoryEntry {
10915            selections: self.selections.disjoint_anchors(),
10916            select_next_state: self.select_next_state.clone(),
10917            select_prev_state: self.select_prev_state.clone(),
10918            add_selections_state: self.add_selections_state.clone(),
10919        });
10920    }
10921
10922    pub fn transact(
10923        &mut self,
10924        cx: &mut ViewContext<Self>,
10925        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10926    ) -> Option<TransactionId> {
10927        self.start_transaction_at(Instant::now(), cx);
10928        update(self, cx);
10929        self.end_transaction_at(Instant::now(), cx)
10930    }
10931
10932    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10933        self.end_selection(cx);
10934        if let Some(tx_id) = self
10935            .buffer
10936            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10937        {
10938            self.selection_history
10939                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10940            cx.emit(EditorEvent::TransactionBegun {
10941                transaction_id: tx_id,
10942            })
10943        }
10944    }
10945
10946    fn end_transaction_at(
10947        &mut self,
10948        now: Instant,
10949        cx: &mut ViewContext<Self>,
10950    ) -> Option<TransactionId> {
10951        if let Some(transaction_id) = self
10952            .buffer
10953            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10954        {
10955            if let Some((_, end_selections)) =
10956                self.selection_history.transaction_mut(transaction_id)
10957            {
10958                *end_selections = Some(self.selections.disjoint_anchors());
10959            } else {
10960                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10961            }
10962
10963            cx.emit(EditorEvent::Edited { transaction_id });
10964            Some(transaction_id)
10965        } else {
10966            None
10967        }
10968    }
10969
10970    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10971        let selection = self.selections.newest::<Point>(cx);
10972
10973        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10974        let range = if selection.is_empty() {
10975            let point = selection.head().to_display_point(&display_map);
10976            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10977            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10978                .to_point(&display_map);
10979            start..end
10980        } else {
10981            selection.range()
10982        };
10983        if display_map.folds_in_range(range).next().is_some() {
10984            self.unfold_lines(&Default::default(), cx)
10985        } else {
10986            self.fold(&Default::default(), cx)
10987        }
10988    }
10989
10990    pub fn toggle_fold_recursive(
10991        &mut self,
10992        _: &actions::ToggleFoldRecursive,
10993        cx: &mut ViewContext<Self>,
10994    ) {
10995        let selection = self.selections.newest::<Point>(cx);
10996
10997        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10998        let range = if selection.is_empty() {
10999            let point = selection.head().to_display_point(&display_map);
11000            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11001            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11002                .to_point(&display_map);
11003            start..end
11004        } else {
11005            selection.range()
11006        };
11007        if display_map.folds_in_range(range).next().is_some() {
11008            self.unfold_recursive(&Default::default(), cx)
11009        } else {
11010            self.fold_recursive(&Default::default(), cx)
11011        }
11012    }
11013
11014    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11015        let mut to_fold = Vec::new();
11016        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11017        let selections = self.selections.all_adjusted(cx);
11018
11019        for selection in selections {
11020            let range = selection.range().sorted();
11021            let buffer_start_row = range.start.row;
11022
11023            if range.start.row != range.end.row {
11024                let mut found = false;
11025                let mut row = range.start.row;
11026                while row <= range.end.row {
11027                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11028                        found = true;
11029                        row = crease.range().end.row + 1;
11030                        to_fold.push(crease);
11031                    } else {
11032                        row += 1
11033                    }
11034                }
11035                if found {
11036                    continue;
11037                }
11038            }
11039
11040            for row in (0..=range.start.row).rev() {
11041                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11042                    if crease.range().end.row >= buffer_start_row {
11043                        to_fold.push(crease);
11044                        if row <= range.start.row {
11045                            break;
11046                        }
11047                    }
11048                }
11049            }
11050        }
11051
11052        self.fold_creases(to_fold, true, cx);
11053    }
11054
11055    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11056        if !self.buffer.read(cx).is_singleton() {
11057            return;
11058        }
11059
11060        let fold_at_level = fold_at.level;
11061        let snapshot = self.buffer.read(cx).snapshot(cx);
11062        let mut to_fold = Vec::new();
11063        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11064
11065        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11066            while start_row < end_row {
11067                match self
11068                    .snapshot(cx)
11069                    .crease_for_buffer_row(MultiBufferRow(start_row))
11070                {
11071                    Some(crease) => {
11072                        let nested_start_row = crease.range().start.row + 1;
11073                        let nested_end_row = crease.range().end.row;
11074
11075                        if current_level < fold_at_level {
11076                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11077                        } else if current_level == fold_at_level {
11078                            to_fold.push(crease);
11079                        }
11080
11081                        start_row = nested_end_row + 1;
11082                    }
11083                    None => start_row += 1,
11084                }
11085            }
11086        }
11087
11088        self.fold_creases(to_fold, true, cx);
11089    }
11090
11091    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11092        if !self.buffer.read(cx).is_singleton() {
11093            return;
11094        }
11095
11096        let mut fold_ranges = Vec::new();
11097        let snapshot = self.buffer.read(cx).snapshot(cx);
11098
11099        for row in 0..snapshot.max_row().0 {
11100            if let Some(foldable_range) =
11101                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11102            {
11103                fold_ranges.push(foldable_range);
11104            }
11105        }
11106
11107        self.fold_creases(fold_ranges, true, cx);
11108    }
11109
11110    pub fn fold_function_bodies(
11111        &mut self,
11112        _: &actions::FoldFunctionBodies,
11113        cx: &mut ViewContext<Self>,
11114    ) {
11115        let snapshot = self.buffer.read(cx).snapshot(cx);
11116        let Some((_, _, buffer)) = snapshot.as_singleton() else {
11117            return;
11118        };
11119        let creases = buffer
11120            .function_body_fold_ranges(0..buffer.len())
11121            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11122            .collect();
11123
11124        self.fold_creases(creases, true, cx);
11125    }
11126
11127    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11128        let mut to_fold = Vec::new();
11129        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11130        let selections = self.selections.all_adjusted(cx);
11131
11132        for selection in selections {
11133            let range = selection.range().sorted();
11134            let buffer_start_row = range.start.row;
11135
11136            if range.start.row != range.end.row {
11137                let mut found = false;
11138                for row in range.start.row..=range.end.row {
11139                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11140                        found = true;
11141                        to_fold.push(crease);
11142                    }
11143                }
11144                if found {
11145                    continue;
11146                }
11147            }
11148
11149            for row in (0..=range.start.row).rev() {
11150                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11151                    if crease.range().end.row >= buffer_start_row {
11152                        to_fold.push(crease);
11153                    } else {
11154                        break;
11155                    }
11156                }
11157            }
11158        }
11159
11160        self.fold_creases(to_fold, true, cx);
11161    }
11162
11163    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11164        let buffer_row = fold_at.buffer_row;
11165        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11166
11167        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11168            let autoscroll = self
11169                .selections
11170                .all::<Point>(cx)
11171                .iter()
11172                .any(|selection| crease.range().overlaps(&selection.range()));
11173
11174            self.fold_creases(vec![crease], autoscroll, cx);
11175        }
11176    }
11177
11178    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11179        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11180        let buffer = &display_map.buffer_snapshot;
11181        let selections = self.selections.all::<Point>(cx);
11182        let ranges = selections
11183            .iter()
11184            .map(|s| {
11185                let range = s.display_range(&display_map).sorted();
11186                let mut start = range.start.to_point(&display_map);
11187                let mut end = range.end.to_point(&display_map);
11188                start.column = 0;
11189                end.column = buffer.line_len(MultiBufferRow(end.row));
11190                start..end
11191            })
11192            .collect::<Vec<_>>();
11193
11194        self.unfold_ranges(&ranges, true, true, cx);
11195    }
11196
11197    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11198        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11199        let selections = self.selections.all::<Point>(cx);
11200        let ranges = selections
11201            .iter()
11202            .map(|s| {
11203                let mut range = s.display_range(&display_map).sorted();
11204                *range.start.column_mut() = 0;
11205                *range.end.column_mut() = display_map.line_len(range.end.row());
11206                let start = range.start.to_point(&display_map);
11207                let end = range.end.to_point(&display_map);
11208                start..end
11209            })
11210            .collect::<Vec<_>>();
11211
11212        self.unfold_ranges(&ranges, true, true, cx);
11213    }
11214
11215    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11216        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11217
11218        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11219            ..Point::new(
11220                unfold_at.buffer_row.0,
11221                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11222            );
11223
11224        let autoscroll = self
11225            .selections
11226            .all::<Point>(cx)
11227            .iter()
11228            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11229
11230        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11231    }
11232
11233    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11234        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11235        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11236    }
11237
11238    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11239        let selections = self.selections.all::<Point>(cx);
11240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11241        let line_mode = self.selections.line_mode;
11242        let ranges = selections
11243            .into_iter()
11244            .map(|s| {
11245                if line_mode {
11246                    let start = Point::new(s.start.row, 0);
11247                    let end = Point::new(
11248                        s.end.row,
11249                        display_map
11250                            .buffer_snapshot
11251                            .line_len(MultiBufferRow(s.end.row)),
11252                    );
11253                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11254                } else {
11255                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11256                }
11257            })
11258            .collect::<Vec<_>>();
11259        self.fold_creases(ranges, true, cx);
11260    }
11261
11262    pub fn fold_creases<T: ToOffset + Clone>(
11263        &mut self,
11264        creases: Vec<Crease<T>>,
11265        auto_scroll: bool,
11266        cx: &mut ViewContext<Self>,
11267    ) {
11268        if creases.is_empty() {
11269            return;
11270        }
11271
11272        let mut buffers_affected = HashMap::default();
11273        let multi_buffer = self.buffer().read(cx);
11274        for crease in &creases {
11275            if let Some((_, buffer, _)) =
11276                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11277            {
11278                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11279            };
11280        }
11281
11282        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11283
11284        if auto_scroll {
11285            self.request_autoscroll(Autoscroll::fit(), cx);
11286        }
11287
11288        for buffer in buffers_affected.into_values() {
11289            self.sync_expanded_diff_hunks(buffer, cx);
11290        }
11291
11292        cx.notify();
11293
11294        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11295            // Clear diagnostics block when folding a range that contains it.
11296            let snapshot = self.snapshot(cx);
11297            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11298                drop(snapshot);
11299                self.active_diagnostics = Some(active_diagnostics);
11300                self.dismiss_diagnostics(cx);
11301            } else {
11302                self.active_diagnostics = Some(active_diagnostics);
11303            }
11304        }
11305
11306        self.scrollbar_marker_state.dirty = true;
11307    }
11308
11309    /// Removes any folds whose ranges intersect any of the given ranges.
11310    pub fn unfold_ranges<T: ToOffset + Clone>(
11311        &mut self,
11312        ranges: &[Range<T>],
11313        inclusive: bool,
11314        auto_scroll: bool,
11315        cx: &mut ViewContext<Self>,
11316    ) {
11317        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11318            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11319        });
11320    }
11321
11322    /// Removes any folds with the given ranges.
11323    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11324        &mut self,
11325        ranges: &[Range<T>],
11326        type_id: TypeId,
11327        auto_scroll: bool,
11328        cx: &mut ViewContext<Self>,
11329    ) {
11330        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11331            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11332        });
11333    }
11334
11335    fn remove_folds_with<T: ToOffset + Clone>(
11336        &mut self,
11337        ranges: &[Range<T>],
11338        auto_scroll: bool,
11339        cx: &mut ViewContext<Self>,
11340        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11341    ) {
11342        if ranges.is_empty() {
11343            return;
11344        }
11345
11346        let mut buffers_affected = HashMap::default();
11347        let multi_buffer = self.buffer().read(cx);
11348        for range in ranges {
11349            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11350                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11351            };
11352        }
11353
11354        self.display_map.update(cx, update);
11355
11356        if auto_scroll {
11357            self.request_autoscroll(Autoscroll::fit(), cx);
11358        }
11359
11360        for buffer in buffers_affected.into_values() {
11361            self.sync_expanded_diff_hunks(buffer, cx);
11362        }
11363
11364        cx.notify();
11365        self.scrollbar_marker_state.dirty = true;
11366        self.active_indent_guides_state.dirty = true;
11367    }
11368
11369    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11370        self.display_map.read(cx).fold_placeholder.clone()
11371    }
11372
11373    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11374        if hovered != self.gutter_hovered {
11375            self.gutter_hovered = hovered;
11376            cx.notify();
11377        }
11378    }
11379
11380    pub fn insert_blocks(
11381        &mut self,
11382        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11383        autoscroll: Option<Autoscroll>,
11384        cx: &mut ViewContext<Self>,
11385    ) -> Vec<CustomBlockId> {
11386        let blocks = self
11387            .display_map
11388            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11389        if let Some(autoscroll) = autoscroll {
11390            self.request_autoscroll(autoscroll, cx);
11391        }
11392        cx.notify();
11393        blocks
11394    }
11395
11396    pub fn resize_blocks(
11397        &mut self,
11398        heights: HashMap<CustomBlockId, u32>,
11399        autoscroll: Option<Autoscroll>,
11400        cx: &mut ViewContext<Self>,
11401    ) {
11402        self.display_map
11403            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11404        if let Some(autoscroll) = autoscroll {
11405            self.request_autoscroll(autoscroll, cx);
11406        }
11407        cx.notify();
11408    }
11409
11410    pub fn replace_blocks(
11411        &mut self,
11412        renderers: HashMap<CustomBlockId, RenderBlock>,
11413        autoscroll: Option<Autoscroll>,
11414        cx: &mut ViewContext<Self>,
11415    ) {
11416        self.display_map
11417            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11418        if let Some(autoscroll) = autoscroll {
11419            self.request_autoscroll(autoscroll, cx);
11420        }
11421        cx.notify();
11422    }
11423
11424    pub fn remove_blocks(
11425        &mut self,
11426        block_ids: HashSet<CustomBlockId>,
11427        autoscroll: Option<Autoscroll>,
11428        cx: &mut ViewContext<Self>,
11429    ) {
11430        self.display_map.update(cx, |display_map, cx| {
11431            display_map.remove_blocks(block_ids, cx)
11432        });
11433        if let Some(autoscroll) = autoscroll {
11434            self.request_autoscroll(autoscroll, cx);
11435        }
11436        cx.notify();
11437    }
11438
11439    pub fn row_for_block(
11440        &self,
11441        block_id: CustomBlockId,
11442        cx: &mut ViewContext<Self>,
11443    ) -> Option<DisplayRow> {
11444        self.display_map
11445            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11446    }
11447
11448    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11449        self.focused_block = Some(focused_block);
11450    }
11451
11452    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11453        self.focused_block.take()
11454    }
11455
11456    pub fn insert_creases(
11457        &mut self,
11458        creases: impl IntoIterator<Item = Crease<Anchor>>,
11459        cx: &mut ViewContext<Self>,
11460    ) -> Vec<CreaseId> {
11461        self.display_map
11462            .update(cx, |map, cx| map.insert_creases(creases, cx))
11463    }
11464
11465    pub fn remove_creases(
11466        &mut self,
11467        ids: impl IntoIterator<Item = CreaseId>,
11468        cx: &mut ViewContext<Self>,
11469    ) {
11470        self.display_map
11471            .update(cx, |map, cx| map.remove_creases(ids, cx));
11472    }
11473
11474    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11475        self.display_map
11476            .update(cx, |map, cx| map.snapshot(cx))
11477            .longest_row()
11478    }
11479
11480    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11481        self.display_map
11482            .update(cx, |map, cx| map.snapshot(cx))
11483            .max_point()
11484    }
11485
11486    pub fn text(&self, cx: &AppContext) -> String {
11487        self.buffer.read(cx).read(cx).text()
11488    }
11489
11490    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11491        let text = self.text(cx);
11492        let text = text.trim();
11493
11494        if text.is_empty() {
11495            return None;
11496        }
11497
11498        Some(text.to_string())
11499    }
11500
11501    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11502        self.transact(cx, |this, cx| {
11503            this.buffer
11504                .read(cx)
11505                .as_singleton()
11506                .expect("you can only call set_text on editors for singleton buffers")
11507                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11508        });
11509    }
11510
11511    pub fn display_text(&self, cx: &mut AppContext) -> String {
11512        self.display_map
11513            .update(cx, |map, cx| map.snapshot(cx))
11514            .text()
11515    }
11516
11517    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11518        let mut wrap_guides = smallvec::smallvec![];
11519
11520        if self.show_wrap_guides == Some(false) {
11521            return wrap_guides;
11522        }
11523
11524        let settings = self.buffer.read(cx).settings_at(0, cx);
11525        if settings.show_wrap_guides {
11526            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11527                wrap_guides.push((soft_wrap as usize, true));
11528            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11529                wrap_guides.push((soft_wrap as usize, true));
11530            }
11531            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11532        }
11533
11534        wrap_guides
11535    }
11536
11537    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11538        let settings = self.buffer.read(cx).settings_at(0, cx);
11539        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11540        match mode {
11541            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11542                SoftWrap::None
11543            }
11544            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11545            language_settings::SoftWrap::PreferredLineLength => {
11546                SoftWrap::Column(settings.preferred_line_length)
11547            }
11548            language_settings::SoftWrap::Bounded => {
11549                SoftWrap::Bounded(settings.preferred_line_length)
11550            }
11551        }
11552    }
11553
11554    pub fn set_soft_wrap_mode(
11555        &mut self,
11556        mode: language_settings::SoftWrap,
11557        cx: &mut ViewContext<Self>,
11558    ) {
11559        self.soft_wrap_mode_override = Some(mode);
11560        cx.notify();
11561    }
11562
11563    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11564        self.text_style_refinement = Some(style);
11565    }
11566
11567    /// called by the Element so we know what style we were most recently rendered with.
11568    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11569        let rem_size = cx.rem_size();
11570        self.display_map.update(cx, |map, cx| {
11571            map.set_font(
11572                style.text.font(),
11573                style.text.font_size.to_pixels(rem_size),
11574                cx,
11575            )
11576        });
11577        self.style = Some(style);
11578    }
11579
11580    pub fn style(&self) -> Option<&EditorStyle> {
11581        self.style.as_ref()
11582    }
11583
11584    // Called by the element. This method is not designed to be called outside of the editor
11585    // element's layout code because it does not notify when rewrapping is computed synchronously.
11586    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11587        self.display_map
11588            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11589    }
11590
11591    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11592        if self.soft_wrap_mode_override.is_some() {
11593            self.soft_wrap_mode_override.take();
11594        } else {
11595            let soft_wrap = match self.soft_wrap_mode(cx) {
11596                SoftWrap::GitDiff => return,
11597                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11598                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11599                    language_settings::SoftWrap::None
11600                }
11601            };
11602            self.soft_wrap_mode_override = Some(soft_wrap);
11603        }
11604        cx.notify();
11605    }
11606
11607    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11608        let Some(workspace) = self.workspace() else {
11609            return;
11610        };
11611        let fs = workspace.read(cx).app_state().fs.clone();
11612        let current_show = TabBarSettings::get_global(cx).show;
11613        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11614            setting.show = Some(!current_show);
11615        });
11616    }
11617
11618    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11619        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11620            self.buffer
11621                .read(cx)
11622                .settings_at(0, cx)
11623                .indent_guides
11624                .enabled
11625        });
11626        self.show_indent_guides = Some(!currently_enabled);
11627        cx.notify();
11628    }
11629
11630    fn should_show_indent_guides(&self) -> Option<bool> {
11631        self.show_indent_guides
11632    }
11633
11634    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11635        let mut editor_settings = EditorSettings::get_global(cx).clone();
11636        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11637        EditorSettings::override_global(editor_settings, cx);
11638    }
11639
11640    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11641        self.use_relative_line_numbers
11642            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11643    }
11644
11645    pub fn toggle_relative_line_numbers(
11646        &mut self,
11647        _: &ToggleRelativeLineNumbers,
11648        cx: &mut ViewContext<Self>,
11649    ) {
11650        let is_relative = self.should_use_relative_line_numbers(cx);
11651        self.set_relative_line_number(Some(!is_relative), cx)
11652    }
11653
11654    pub fn set_relative_line_number(
11655        &mut self,
11656        is_relative: Option<bool>,
11657        cx: &mut ViewContext<Self>,
11658    ) {
11659        self.use_relative_line_numbers = is_relative;
11660        cx.notify();
11661    }
11662
11663    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11664        self.show_gutter = show_gutter;
11665        cx.notify();
11666    }
11667
11668    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11669        self.show_line_numbers = Some(show_line_numbers);
11670        cx.notify();
11671    }
11672
11673    pub fn set_show_git_diff_gutter(
11674        &mut self,
11675        show_git_diff_gutter: bool,
11676        cx: &mut ViewContext<Self>,
11677    ) {
11678        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11679        cx.notify();
11680    }
11681
11682    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11683        self.show_code_actions = Some(show_code_actions);
11684        cx.notify();
11685    }
11686
11687    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11688        self.show_runnables = Some(show_runnables);
11689        cx.notify();
11690    }
11691
11692    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11693        if self.display_map.read(cx).masked != masked {
11694            self.display_map.update(cx, |map, _| map.masked = masked);
11695        }
11696        cx.notify()
11697    }
11698
11699    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11700        self.show_wrap_guides = Some(show_wrap_guides);
11701        cx.notify();
11702    }
11703
11704    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11705        self.show_indent_guides = Some(show_indent_guides);
11706        cx.notify();
11707    }
11708
11709    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11710        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11711            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11712                if let Some(dir) = file.abs_path(cx).parent() {
11713                    return Some(dir.to_owned());
11714                }
11715            }
11716
11717            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11718                return Some(project_path.path.to_path_buf());
11719            }
11720        }
11721
11722        None
11723    }
11724
11725    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11726        self.active_excerpt(cx)?
11727            .1
11728            .read(cx)
11729            .file()
11730            .and_then(|f| f.as_local())
11731    }
11732
11733    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11734        if let Some(target) = self.target_file(cx) {
11735            cx.reveal_path(&target.abs_path(cx));
11736        }
11737    }
11738
11739    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11740        if let Some(file) = self.target_file(cx) {
11741            if let Some(path) = file.abs_path(cx).to_str() {
11742                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11743            }
11744        }
11745    }
11746
11747    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11748        if let Some(file) = self.target_file(cx) {
11749            if let Some(path) = file.path().to_str() {
11750                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11751            }
11752        }
11753    }
11754
11755    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11756        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11757
11758        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11759            self.start_git_blame(true, cx);
11760        }
11761
11762        cx.notify();
11763    }
11764
11765    pub fn toggle_git_blame_inline(
11766        &mut self,
11767        _: &ToggleGitBlameInline,
11768        cx: &mut ViewContext<Self>,
11769    ) {
11770        self.toggle_git_blame_inline_internal(true, cx);
11771        cx.notify();
11772    }
11773
11774    pub fn git_blame_inline_enabled(&self) -> bool {
11775        self.git_blame_inline_enabled
11776    }
11777
11778    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11779        self.show_selection_menu = self
11780            .show_selection_menu
11781            .map(|show_selections_menu| !show_selections_menu)
11782            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11783
11784        cx.notify();
11785    }
11786
11787    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11788        self.show_selection_menu
11789            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11790    }
11791
11792    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11793        if let Some(project) = self.project.as_ref() {
11794            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11795                return;
11796            };
11797
11798            if buffer.read(cx).file().is_none() {
11799                return;
11800            }
11801
11802            let focused = self.focus_handle(cx).contains_focused(cx);
11803
11804            let project = project.clone();
11805            let blame =
11806                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11807            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11808            self.blame = Some(blame);
11809        }
11810    }
11811
11812    fn toggle_git_blame_inline_internal(
11813        &mut self,
11814        user_triggered: bool,
11815        cx: &mut ViewContext<Self>,
11816    ) {
11817        if self.git_blame_inline_enabled {
11818            self.git_blame_inline_enabled = false;
11819            self.show_git_blame_inline = false;
11820            self.show_git_blame_inline_delay_task.take();
11821        } else {
11822            self.git_blame_inline_enabled = true;
11823            self.start_git_blame_inline(user_triggered, cx);
11824        }
11825
11826        cx.notify();
11827    }
11828
11829    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11830        self.start_git_blame(user_triggered, cx);
11831
11832        if ProjectSettings::get_global(cx)
11833            .git
11834            .inline_blame_delay()
11835            .is_some()
11836        {
11837            self.start_inline_blame_timer(cx);
11838        } else {
11839            self.show_git_blame_inline = true
11840        }
11841    }
11842
11843    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11844        self.blame.as_ref()
11845    }
11846
11847    pub fn show_git_blame_gutter(&self) -> bool {
11848        self.show_git_blame_gutter
11849    }
11850
11851    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11852        self.show_git_blame_gutter && self.has_blame_entries(cx)
11853    }
11854
11855    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11856        self.show_git_blame_inline
11857            && self.focus_handle.is_focused(cx)
11858            && !self.newest_selection_head_on_empty_line(cx)
11859            && self.has_blame_entries(cx)
11860    }
11861
11862    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11863        self.blame()
11864            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11865    }
11866
11867    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11868        let cursor_anchor = self.selections.newest_anchor().head();
11869
11870        let snapshot = self.buffer.read(cx).snapshot(cx);
11871        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11872
11873        snapshot.line_len(buffer_row) == 0
11874    }
11875
11876    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11877        let buffer_and_selection = maybe!({
11878            let selection = self.selections.newest::<Point>(cx);
11879            let selection_range = selection.range();
11880
11881            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11882                (buffer, selection_range.start.row..selection_range.end.row)
11883            } else {
11884                let buffer_ranges = self
11885                    .buffer()
11886                    .read(cx)
11887                    .range_to_buffer_ranges(selection_range, cx);
11888
11889                let (buffer, range, _) = if selection.reversed {
11890                    buffer_ranges.first()
11891                } else {
11892                    buffer_ranges.last()
11893                }?;
11894
11895                let snapshot = buffer.read(cx).snapshot();
11896                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11897                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11898                (buffer.clone(), selection)
11899            };
11900
11901            Some((buffer, selection))
11902        });
11903
11904        let Some((buffer, selection)) = buffer_and_selection else {
11905            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11906        };
11907
11908        let Some(project) = self.project.as_ref() else {
11909            return Task::ready(Err(anyhow!("editor does not have project")));
11910        };
11911
11912        project.update(cx, |project, cx| {
11913            project.get_permalink_to_line(&buffer, selection, cx)
11914        })
11915    }
11916
11917    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11918        let permalink_task = self.get_permalink_to_line(cx);
11919        let workspace = self.workspace();
11920
11921        cx.spawn(|_, mut cx| async move {
11922            match permalink_task.await {
11923                Ok(permalink) => {
11924                    cx.update(|cx| {
11925                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11926                    })
11927                    .ok();
11928                }
11929                Err(err) => {
11930                    let message = format!("Failed to copy permalink: {err}");
11931
11932                    Err::<(), anyhow::Error>(err).log_err();
11933
11934                    if let Some(workspace) = workspace {
11935                        workspace
11936                            .update(&mut cx, |workspace, cx| {
11937                                struct CopyPermalinkToLine;
11938
11939                                workspace.show_toast(
11940                                    Toast::new(
11941                                        NotificationId::unique::<CopyPermalinkToLine>(),
11942                                        message,
11943                                    ),
11944                                    cx,
11945                                )
11946                            })
11947                            .ok();
11948                    }
11949                }
11950            }
11951        })
11952        .detach();
11953    }
11954
11955    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11956        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11957        if let Some(file) = self.target_file(cx) {
11958            if let Some(path) = file.path().to_str() {
11959                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11960            }
11961        }
11962    }
11963
11964    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11965        let permalink_task = self.get_permalink_to_line(cx);
11966        let workspace = self.workspace();
11967
11968        cx.spawn(|_, mut cx| async move {
11969            match permalink_task.await {
11970                Ok(permalink) => {
11971                    cx.update(|cx| {
11972                        cx.open_url(permalink.as_ref());
11973                    })
11974                    .ok();
11975                }
11976                Err(err) => {
11977                    let message = format!("Failed to open permalink: {err}");
11978
11979                    Err::<(), anyhow::Error>(err).log_err();
11980
11981                    if let Some(workspace) = workspace {
11982                        workspace
11983                            .update(&mut cx, |workspace, cx| {
11984                                struct OpenPermalinkToLine;
11985
11986                                workspace.show_toast(
11987                                    Toast::new(
11988                                        NotificationId::unique::<OpenPermalinkToLine>(),
11989                                        message,
11990                                    ),
11991                                    cx,
11992                                )
11993                            })
11994                            .ok();
11995                    }
11996                }
11997            }
11998        })
11999        .detach();
12000    }
12001
12002    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12003    /// last highlight added will be used.
12004    ///
12005    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12006    pub fn highlight_rows<T: 'static>(
12007        &mut self,
12008        range: Range<Anchor>,
12009        color: Hsla,
12010        should_autoscroll: bool,
12011        cx: &mut ViewContext<Self>,
12012    ) {
12013        let snapshot = self.buffer().read(cx).snapshot(cx);
12014        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12015        let ix = row_highlights.binary_search_by(|highlight| {
12016            Ordering::Equal
12017                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12018                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12019        });
12020
12021        if let Err(mut ix) = ix {
12022            let index = post_inc(&mut self.highlight_order);
12023
12024            // If this range intersects with the preceding highlight, then merge it with
12025            // the preceding highlight. Otherwise insert a new highlight.
12026            let mut merged = false;
12027            if ix > 0 {
12028                let prev_highlight = &mut row_highlights[ix - 1];
12029                if prev_highlight
12030                    .range
12031                    .end
12032                    .cmp(&range.start, &snapshot)
12033                    .is_ge()
12034                {
12035                    ix -= 1;
12036                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12037                        prev_highlight.range.end = range.end;
12038                    }
12039                    merged = true;
12040                    prev_highlight.index = index;
12041                    prev_highlight.color = color;
12042                    prev_highlight.should_autoscroll = should_autoscroll;
12043                }
12044            }
12045
12046            if !merged {
12047                row_highlights.insert(
12048                    ix,
12049                    RowHighlight {
12050                        range: range.clone(),
12051                        index,
12052                        color,
12053                        should_autoscroll,
12054                    },
12055                );
12056            }
12057
12058            // If any of the following highlights intersect with this one, merge them.
12059            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12060                let highlight = &row_highlights[ix];
12061                if next_highlight
12062                    .range
12063                    .start
12064                    .cmp(&highlight.range.end, &snapshot)
12065                    .is_le()
12066                {
12067                    if next_highlight
12068                        .range
12069                        .end
12070                        .cmp(&highlight.range.end, &snapshot)
12071                        .is_gt()
12072                    {
12073                        row_highlights[ix].range.end = next_highlight.range.end;
12074                    }
12075                    row_highlights.remove(ix + 1);
12076                } else {
12077                    break;
12078                }
12079            }
12080        }
12081    }
12082
12083    /// Remove any highlighted row ranges of the given type that intersect the
12084    /// given ranges.
12085    pub fn remove_highlighted_rows<T: 'static>(
12086        &mut self,
12087        ranges_to_remove: Vec<Range<Anchor>>,
12088        cx: &mut ViewContext<Self>,
12089    ) {
12090        let snapshot = self.buffer().read(cx).snapshot(cx);
12091        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12092        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12093        row_highlights.retain(|highlight| {
12094            while let Some(range_to_remove) = ranges_to_remove.peek() {
12095                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12096                    Ordering::Less | Ordering::Equal => {
12097                        ranges_to_remove.next();
12098                    }
12099                    Ordering::Greater => {
12100                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12101                            Ordering::Less | Ordering::Equal => {
12102                                return false;
12103                            }
12104                            Ordering::Greater => break,
12105                        }
12106                    }
12107                }
12108            }
12109
12110            true
12111        })
12112    }
12113
12114    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12115    pub fn clear_row_highlights<T: 'static>(&mut self) {
12116        self.highlighted_rows.remove(&TypeId::of::<T>());
12117    }
12118
12119    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12120    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12121        self.highlighted_rows
12122            .get(&TypeId::of::<T>())
12123            .map_or(&[] as &[_], |vec| vec.as_slice())
12124            .iter()
12125            .map(|highlight| (highlight.range.clone(), highlight.color))
12126    }
12127
12128    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12129    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12130    /// Allows to ignore certain kinds of highlights.
12131    pub fn highlighted_display_rows(
12132        &mut self,
12133        cx: &mut WindowContext,
12134    ) -> BTreeMap<DisplayRow, Hsla> {
12135        let snapshot = self.snapshot(cx);
12136        let mut used_highlight_orders = HashMap::default();
12137        self.highlighted_rows
12138            .iter()
12139            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12140            .fold(
12141                BTreeMap::<DisplayRow, Hsla>::new(),
12142                |mut unique_rows, highlight| {
12143                    let start = highlight.range.start.to_display_point(&snapshot);
12144                    let end = highlight.range.end.to_display_point(&snapshot);
12145                    let start_row = start.row().0;
12146                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12147                        && end.column() == 0
12148                    {
12149                        end.row().0.saturating_sub(1)
12150                    } else {
12151                        end.row().0
12152                    };
12153                    for row in start_row..=end_row {
12154                        let used_index =
12155                            used_highlight_orders.entry(row).or_insert(highlight.index);
12156                        if highlight.index >= *used_index {
12157                            *used_index = highlight.index;
12158                            unique_rows.insert(DisplayRow(row), highlight.color);
12159                        }
12160                    }
12161                    unique_rows
12162                },
12163            )
12164    }
12165
12166    pub fn highlighted_display_row_for_autoscroll(
12167        &self,
12168        snapshot: &DisplaySnapshot,
12169    ) -> Option<DisplayRow> {
12170        self.highlighted_rows
12171            .values()
12172            .flat_map(|highlighted_rows| highlighted_rows.iter())
12173            .filter_map(|highlight| {
12174                if highlight.should_autoscroll {
12175                    Some(highlight.range.start.to_display_point(snapshot).row())
12176                } else {
12177                    None
12178                }
12179            })
12180            .min()
12181    }
12182
12183    pub fn set_search_within_ranges(
12184        &mut self,
12185        ranges: &[Range<Anchor>],
12186        cx: &mut ViewContext<Self>,
12187    ) {
12188        self.highlight_background::<SearchWithinRange>(
12189            ranges,
12190            |colors| colors.editor_document_highlight_read_background,
12191            cx,
12192        )
12193    }
12194
12195    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12196        self.breadcrumb_header = Some(new_header);
12197    }
12198
12199    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12200        self.clear_background_highlights::<SearchWithinRange>(cx);
12201    }
12202
12203    pub fn highlight_background<T: 'static>(
12204        &mut self,
12205        ranges: &[Range<Anchor>],
12206        color_fetcher: fn(&ThemeColors) -> Hsla,
12207        cx: &mut ViewContext<Self>,
12208    ) {
12209        self.background_highlights
12210            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12211        self.scrollbar_marker_state.dirty = true;
12212        cx.notify();
12213    }
12214
12215    pub fn clear_background_highlights<T: 'static>(
12216        &mut self,
12217        cx: &mut ViewContext<Self>,
12218    ) -> Option<BackgroundHighlight> {
12219        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12220        if !text_highlights.1.is_empty() {
12221            self.scrollbar_marker_state.dirty = true;
12222            cx.notify();
12223        }
12224        Some(text_highlights)
12225    }
12226
12227    pub fn highlight_gutter<T: 'static>(
12228        &mut self,
12229        ranges: &[Range<Anchor>],
12230        color_fetcher: fn(&AppContext) -> Hsla,
12231        cx: &mut ViewContext<Self>,
12232    ) {
12233        self.gutter_highlights
12234            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12235        cx.notify();
12236    }
12237
12238    pub fn clear_gutter_highlights<T: 'static>(
12239        &mut self,
12240        cx: &mut ViewContext<Self>,
12241    ) -> Option<GutterHighlight> {
12242        cx.notify();
12243        self.gutter_highlights.remove(&TypeId::of::<T>())
12244    }
12245
12246    #[cfg(feature = "test-support")]
12247    pub fn all_text_background_highlights(
12248        &mut self,
12249        cx: &mut ViewContext<Self>,
12250    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12251        let snapshot = self.snapshot(cx);
12252        let buffer = &snapshot.buffer_snapshot;
12253        let start = buffer.anchor_before(0);
12254        let end = buffer.anchor_after(buffer.len());
12255        let theme = cx.theme().colors();
12256        self.background_highlights_in_range(start..end, &snapshot, theme)
12257    }
12258
12259    #[cfg(feature = "test-support")]
12260    pub fn search_background_highlights(
12261        &mut self,
12262        cx: &mut ViewContext<Self>,
12263    ) -> Vec<Range<Point>> {
12264        let snapshot = self.buffer().read(cx).snapshot(cx);
12265
12266        let highlights = self
12267            .background_highlights
12268            .get(&TypeId::of::<items::BufferSearchHighlights>());
12269
12270        if let Some((_color, ranges)) = highlights {
12271            ranges
12272                .iter()
12273                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12274                .collect_vec()
12275        } else {
12276            vec![]
12277        }
12278    }
12279
12280    fn document_highlights_for_position<'a>(
12281        &'a self,
12282        position: Anchor,
12283        buffer: &'a MultiBufferSnapshot,
12284    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12285        let read_highlights = self
12286            .background_highlights
12287            .get(&TypeId::of::<DocumentHighlightRead>())
12288            .map(|h| &h.1);
12289        let write_highlights = self
12290            .background_highlights
12291            .get(&TypeId::of::<DocumentHighlightWrite>())
12292            .map(|h| &h.1);
12293        let left_position = position.bias_left(buffer);
12294        let right_position = position.bias_right(buffer);
12295        read_highlights
12296            .into_iter()
12297            .chain(write_highlights)
12298            .flat_map(move |ranges| {
12299                let start_ix = match ranges.binary_search_by(|probe| {
12300                    let cmp = probe.end.cmp(&left_position, buffer);
12301                    if cmp.is_ge() {
12302                        Ordering::Greater
12303                    } else {
12304                        Ordering::Less
12305                    }
12306                }) {
12307                    Ok(i) | Err(i) => i,
12308                };
12309
12310                ranges[start_ix..]
12311                    .iter()
12312                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12313            })
12314    }
12315
12316    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12317        self.background_highlights
12318            .get(&TypeId::of::<T>())
12319            .map_or(false, |(_, highlights)| !highlights.is_empty())
12320    }
12321
12322    pub fn background_highlights_in_range(
12323        &self,
12324        search_range: Range<Anchor>,
12325        display_snapshot: &DisplaySnapshot,
12326        theme: &ThemeColors,
12327    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12328        let mut results = Vec::new();
12329        for (color_fetcher, ranges) in self.background_highlights.values() {
12330            let color = color_fetcher(theme);
12331            let start_ix = match ranges.binary_search_by(|probe| {
12332                let cmp = probe
12333                    .end
12334                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12335                if cmp.is_gt() {
12336                    Ordering::Greater
12337                } else {
12338                    Ordering::Less
12339                }
12340            }) {
12341                Ok(i) | Err(i) => i,
12342            };
12343            for range in &ranges[start_ix..] {
12344                if range
12345                    .start
12346                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12347                    .is_ge()
12348                {
12349                    break;
12350                }
12351
12352                let start = range.start.to_display_point(display_snapshot);
12353                let end = range.end.to_display_point(display_snapshot);
12354                results.push((start..end, color))
12355            }
12356        }
12357        results
12358    }
12359
12360    pub fn background_highlight_row_ranges<T: 'static>(
12361        &self,
12362        search_range: Range<Anchor>,
12363        display_snapshot: &DisplaySnapshot,
12364        count: usize,
12365    ) -> Vec<RangeInclusive<DisplayPoint>> {
12366        let mut results = Vec::new();
12367        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12368            return vec![];
12369        };
12370
12371        let start_ix = match ranges.binary_search_by(|probe| {
12372            let cmp = probe
12373                .end
12374                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12375            if cmp.is_gt() {
12376                Ordering::Greater
12377            } else {
12378                Ordering::Less
12379            }
12380        }) {
12381            Ok(i) | Err(i) => i,
12382        };
12383        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12384            if let (Some(start_display), Some(end_display)) = (start, end) {
12385                results.push(
12386                    start_display.to_display_point(display_snapshot)
12387                        ..=end_display.to_display_point(display_snapshot),
12388                );
12389            }
12390        };
12391        let mut start_row: Option<Point> = None;
12392        let mut end_row: Option<Point> = None;
12393        if ranges.len() > count {
12394            return Vec::new();
12395        }
12396        for range in &ranges[start_ix..] {
12397            if range
12398                .start
12399                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12400                .is_ge()
12401            {
12402                break;
12403            }
12404            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12405            if let Some(current_row) = &end_row {
12406                if end.row == current_row.row {
12407                    continue;
12408                }
12409            }
12410            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12411            if start_row.is_none() {
12412                assert_eq!(end_row, None);
12413                start_row = Some(start);
12414                end_row = Some(end);
12415                continue;
12416            }
12417            if let Some(current_end) = end_row.as_mut() {
12418                if start.row > current_end.row + 1 {
12419                    push_region(start_row, end_row);
12420                    start_row = Some(start);
12421                    end_row = Some(end);
12422                } else {
12423                    // Merge two hunks.
12424                    *current_end = end;
12425                }
12426            } else {
12427                unreachable!();
12428            }
12429        }
12430        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12431        push_region(start_row, end_row);
12432        results
12433    }
12434
12435    pub fn gutter_highlights_in_range(
12436        &self,
12437        search_range: Range<Anchor>,
12438        display_snapshot: &DisplaySnapshot,
12439        cx: &AppContext,
12440    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12441        let mut results = Vec::new();
12442        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12443            let color = color_fetcher(cx);
12444            let start_ix = match ranges.binary_search_by(|probe| {
12445                let cmp = probe
12446                    .end
12447                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12448                if cmp.is_gt() {
12449                    Ordering::Greater
12450                } else {
12451                    Ordering::Less
12452                }
12453            }) {
12454                Ok(i) | Err(i) => i,
12455            };
12456            for range in &ranges[start_ix..] {
12457                if range
12458                    .start
12459                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12460                    .is_ge()
12461                {
12462                    break;
12463                }
12464
12465                let start = range.start.to_display_point(display_snapshot);
12466                let end = range.end.to_display_point(display_snapshot);
12467                results.push((start..end, color))
12468            }
12469        }
12470        results
12471    }
12472
12473    /// Get the text ranges corresponding to the redaction query
12474    pub fn redacted_ranges(
12475        &self,
12476        search_range: Range<Anchor>,
12477        display_snapshot: &DisplaySnapshot,
12478        cx: &WindowContext,
12479    ) -> Vec<Range<DisplayPoint>> {
12480        display_snapshot
12481            .buffer_snapshot
12482            .redacted_ranges(search_range, |file| {
12483                if let Some(file) = file {
12484                    file.is_private()
12485                        && EditorSettings::get(
12486                            Some(SettingsLocation {
12487                                worktree_id: file.worktree_id(cx),
12488                                path: file.path().as_ref(),
12489                            }),
12490                            cx,
12491                        )
12492                        .redact_private_values
12493                } else {
12494                    false
12495                }
12496            })
12497            .map(|range| {
12498                range.start.to_display_point(display_snapshot)
12499                    ..range.end.to_display_point(display_snapshot)
12500            })
12501            .collect()
12502    }
12503
12504    pub fn highlight_text<T: 'static>(
12505        &mut self,
12506        ranges: Vec<Range<Anchor>>,
12507        style: HighlightStyle,
12508        cx: &mut ViewContext<Self>,
12509    ) {
12510        self.display_map.update(cx, |map, _| {
12511            map.highlight_text(TypeId::of::<T>(), ranges, style)
12512        });
12513        cx.notify();
12514    }
12515
12516    pub(crate) fn highlight_inlays<T: 'static>(
12517        &mut self,
12518        highlights: Vec<InlayHighlight>,
12519        style: HighlightStyle,
12520        cx: &mut ViewContext<Self>,
12521    ) {
12522        self.display_map.update(cx, |map, _| {
12523            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12524        });
12525        cx.notify();
12526    }
12527
12528    pub fn text_highlights<'a, T: 'static>(
12529        &'a self,
12530        cx: &'a AppContext,
12531    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12532        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12533    }
12534
12535    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12536        let cleared = self
12537            .display_map
12538            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12539        if cleared {
12540            cx.notify();
12541        }
12542    }
12543
12544    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12545        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12546            && self.focus_handle.is_focused(cx)
12547    }
12548
12549    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12550        self.show_cursor_when_unfocused = is_enabled;
12551        cx.notify();
12552    }
12553
12554    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12555        cx.notify();
12556    }
12557
12558    fn on_buffer_event(
12559        &mut self,
12560        multibuffer: Model<MultiBuffer>,
12561        event: &multi_buffer::Event,
12562        cx: &mut ViewContext<Self>,
12563    ) {
12564        match event {
12565            multi_buffer::Event::Edited {
12566                singleton_buffer_edited,
12567            } => {
12568                self.scrollbar_marker_state.dirty = true;
12569                self.active_indent_guides_state.dirty = true;
12570                self.refresh_active_diagnostics(cx);
12571                self.refresh_code_actions(cx);
12572                if self.has_active_inline_completion(cx) {
12573                    self.update_visible_inline_completion(cx);
12574                }
12575                cx.emit(EditorEvent::BufferEdited);
12576                cx.emit(SearchEvent::MatchesInvalidated);
12577                if *singleton_buffer_edited {
12578                    if let Some(project) = &self.project {
12579                        let project = project.read(cx);
12580                        #[allow(clippy::mutable_key_type)]
12581                        let languages_affected = multibuffer
12582                            .read(cx)
12583                            .all_buffers()
12584                            .into_iter()
12585                            .filter_map(|buffer| {
12586                                let buffer = buffer.read(cx);
12587                                let language = buffer.language()?;
12588                                if project.is_local()
12589                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12590                                {
12591                                    None
12592                                } else {
12593                                    Some(language)
12594                                }
12595                            })
12596                            .cloned()
12597                            .collect::<HashSet<_>>();
12598                        if !languages_affected.is_empty() {
12599                            self.refresh_inlay_hints(
12600                                InlayHintRefreshReason::BufferEdited(languages_affected),
12601                                cx,
12602                            );
12603                        }
12604                    }
12605                }
12606
12607                let Some(project) = &self.project else { return };
12608                let (telemetry, is_via_ssh) = {
12609                    let project = project.read(cx);
12610                    let telemetry = project.client().telemetry().clone();
12611                    let is_via_ssh = project.is_via_ssh();
12612                    (telemetry, is_via_ssh)
12613                };
12614                refresh_linked_ranges(self, cx);
12615                telemetry.log_edit_event("editor", is_via_ssh);
12616            }
12617            multi_buffer::Event::ExcerptsAdded {
12618                buffer,
12619                predecessor,
12620                excerpts,
12621            } => {
12622                self.tasks_update_task = Some(self.refresh_runnables(cx));
12623                cx.emit(EditorEvent::ExcerptsAdded {
12624                    buffer: buffer.clone(),
12625                    predecessor: *predecessor,
12626                    excerpts: excerpts.clone(),
12627                });
12628                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12629            }
12630            multi_buffer::Event::ExcerptsRemoved { ids } => {
12631                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12632                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12633            }
12634            multi_buffer::Event::ExcerptsEdited { ids } => {
12635                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12636            }
12637            multi_buffer::Event::ExcerptsExpanded { ids } => {
12638                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12639            }
12640            multi_buffer::Event::Reparsed(buffer_id) => {
12641                self.tasks_update_task = Some(self.refresh_runnables(cx));
12642
12643                cx.emit(EditorEvent::Reparsed(*buffer_id));
12644            }
12645            multi_buffer::Event::LanguageChanged(buffer_id) => {
12646                linked_editing_ranges::refresh_linked_ranges(self, cx);
12647                cx.emit(EditorEvent::Reparsed(*buffer_id));
12648                cx.notify();
12649            }
12650            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12651            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12652            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12653                cx.emit(EditorEvent::TitleChanged)
12654            }
12655            multi_buffer::Event::DiffBaseChanged => {
12656                self.scrollbar_marker_state.dirty = true;
12657                cx.emit(EditorEvent::DiffBaseChanged);
12658                cx.notify();
12659            }
12660            multi_buffer::Event::DiffUpdated { buffer } => {
12661                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12662                cx.notify();
12663            }
12664            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12665            multi_buffer::Event::DiagnosticsUpdated => {
12666                self.refresh_active_diagnostics(cx);
12667                self.scrollbar_marker_state.dirty = true;
12668                cx.notify();
12669            }
12670            _ => {}
12671        };
12672    }
12673
12674    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12675        cx.notify();
12676    }
12677
12678    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12679        self.tasks_update_task = Some(self.refresh_runnables(cx));
12680        self.refresh_inline_completion(true, false, cx);
12681        self.refresh_inlay_hints(
12682            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12683                self.selections.newest_anchor().head(),
12684                &self.buffer.read(cx).snapshot(cx),
12685                cx,
12686            )),
12687            cx,
12688        );
12689
12690        let old_cursor_shape = self.cursor_shape;
12691
12692        {
12693            let editor_settings = EditorSettings::get_global(cx);
12694            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12695            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12696            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12697        }
12698
12699        if old_cursor_shape != self.cursor_shape {
12700            cx.emit(EditorEvent::CursorShapeChanged);
12701        }
12702
12703        let project_settings = ProjectSettings::get_global(cx);
12704        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12705
12706        if self.mode == EditorMode::Full {
12707            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12708            if self.git_blame_inline_enabled != inline_blame_enabled {
12709                self.toggle_git_blame_inline_internal(false, cx);
12710            }
12711        }
12712
12713        cx.notify();
12714    }
12715
12716    pub fn set_searchable(&mut self, searchable: bool) {
12717        self.searchable = searchable;
12718    }
12719
12720    pub fn searchable(&self) -> bool {
12721        self.searchable
12722    }
12723
12724    fn open_proposed_changes_editor(
12725        &mut self,
12726        _: &OpenProposedChangesEditor,
12727        cx: &mut ViewContext<Self>,
12728    ) {
12729        let Some(workspace) = self.workspace() else {
12730            cx.propagate();
12731            return;
12732        };
12733
12734        let selections = self.selections.all::<usize>(cx);
12735        let buffer = self.buffer.read(cx);
12736        let mut new_selections_by_buffer = HashMap::default();
12737        for selection in selections {
12738            for (buffer, range, _) in
12739                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12740            {
12741                let mut range = range.to_point(buffer.read(cx));
12742                range.start.column = 0;
12743                range.end.column = buffer.read(cx).line_len(range.end.row);
12744                new_selections_by_buffer
12745                    .entry(buffer)
12746                    .or_insert(Vec::new())
12747                    .push(range)
12748            }
12749        }
12750
12751        let proposed_changes_buffers = new_selections_by_buffer
12752            .into_iter()
12753            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12754            .collect::<Vec<_>>();
12755        let proposed_changes_editor = cx.new_view(|cx| {
12756            ProposedChangesEditor::new(
12757                "Proposed changes",
12758                proposed_changes_buffers,
12759                self.project.clone(),
12760                cx,
12761            )
12762        });
12763
12764        cx.window_context().defer(move |cx| {
12765            workspace.update(cx, |workspace, cx| {
12766                workspace.active_pane().update(cx, |pane, cx| {
12767                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12768                });
12769            });
12770        });
12771    }
12772
12773    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12774        self.open_excerpts_common(None, true, cx)
12775    }
12776
12777    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12778        self.open_excerpts_common(None, false, cx)
12779    }
12780
12781    fn open_excerpts_common(
12782        &mut self,
12783        jump_data: Option<JumpData>,
12784        split: bool,
12785        cx: &mut ViewContext<Self>,
12786    ) {
12787        let Some(workspace) = self.workspace() else {
12788            cx.propagate();
12789            return;
12790        };
12791
12792        if self.buffer.read(cx).is_singleton() {
12793            cx.propagate();
12794            return;
12795        }
12796
12797        let mut new_selections_by_buffer = HashMap::default();
12798        match &jump_data {
12799            Some(jump_data) => {
12800                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12801                if let Some(buffer) = multi_buffer_snapshot
12802                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12803                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12804                {
12805                    let buffer_snapshot = buffer.read(cx).snapshot();
12806                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12807                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12808                    } else {
12809                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12810                    };
12811                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12812                    new_selections_by_buffer.insert(
12813                        buffer,
12814                        (
12815                            vec![jump_to_offset..jump_to_offset],
12816                            Some(jump_data.line_offset_from_top),
12817                        ),
12818                    );
12819                }
12820            }
12821            None => {
12822                let selections = self.selections.all::<usize>(cx);
12823                let buffer = self.buffer.read(cx);
12824                for selection in selections {
12825                    for (mut buffer_handle, mut range, _) in
12826                        buffer.range_to_buffer_ranges(selection.range(), cx)
12827                    {
12828                        // When editing branch buffers, jump to the corresponding location
12829                        // in their base buffer.
12830                        let buffer = buffer_handle.read(cx);
12831                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12832                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12833                            buffer_handle = base_buffer;
12834                        }
12835
12836                        if selection.reversed {
12837                            mem::swap(&mut range.start, &mut range.end);
12838                        }
12839                        new_selections_by_buffer
12840                            .entry(buffer_handle)
12841                            .or_insert((Vec::new(), None))
12842                            .0
12843                            .push(range)
12844                    }
12845                }
12846            }
12847        }
12848
12849        if new_selections_by_buffer.is_empty() {
12850            return;
12851        }
12852
12853        // We defer the pane interaction because we ourselves are a workspace item
12854        // and activating a new item causes the pane to call a method on us reentrantly,
12855        // which panics if we're on the stack.
12856        cx.window_context().defer(move |cx| {
12857            workspace.update(cx, |workspace, cx| {
12858                let pane = if split {
12859                    workspace.adjacent_pane(cx)
12860                } else {
12861                    workspace.active_pane().clone()
12862                };
12863
12864                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12865                    let editor = buffer
12866                        .read(cx)
12867                        .file()
12868                        .is_none()
12869                        .then(|| {
12870                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12871                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12872                            // Instead, we try to activate the existing editor in the pane first.
12873                            let (editor, pane_item_index) =
12874                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12875                                    let editor = item.downcast::<Editor>()?;
12876                                    let singleton_buffer =
12877                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12878                                    if singleton_buffer == buffer {
12879                                        Some((editor, i))
12880                                    } else {
12881                                        None
12882                                    }
12883                                })?;
12884                            pane.update(cx, |pane, cx| {
12885                                pane.activate_item(pane_item_index, true, true, cx)
12886                            });
12887                            Some(editor)
12888                        })
12889                        .flatten()
12890                        .unwrap_or_else(|| {
12891                            workspace.open_project_item::<Self>(
12892                                pane.clone(),
12893                                buffer,
12894                                true,
12895                                true,
12896                                cx,
12897                            )
12898                        });
12899
12900                    editor.update(cx, |editor, cx| {
12901                        let autoscroll = match scroll_offset {
12902                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12903                            None => Autoscroll::newest(),
12904                        };
12905                        let nav_history = editor.nav_history.take();
12906                        editor.unfold_ranges(&ranges, false, true, cx);
12907                        editor.change_selections(Some(autoscroll), cx, |s| {
12908                            s.select_ranges(ranges);
12909                        });
12910                        editor.nav_history = nav_history;
12911                    });
12912                }
12913            })
12914        });
12915    }
12916
12917    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12918        let snapshot = self.buffer.read(cx).read(cx);
12919        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12920        Some(
12921            ranges
12922                .iter()
12923                .map(move |range| {
12924                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12925                })
12926                .collect(),
12927        )
12928    }
12929
12930    fn selection_replacement_ranges(
12931        &self,
12932        range: Range<OffsetUtf16>,
12933        cx: &mut AppContext,
12934    ) -> Vec<Range<OffsetUtf16>> {
12935        let selections = self.selections.all::<OffsetUtf16>(cx);
12936        let newest_selection = selections
12937            .iter()
12938            .max_by_key(|selection| selection.id)
12939            .unwrap();
12940        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12941        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12942        let snapshot = self.buffer.read(cx).read(cx);
12943        selections
12944            .into_iter()
12945            .map(|mut selection| {
12946                selection.start.0 =
12947                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12948                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12949                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12950                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12951            })
12952            .collect()
12953    }
12954
12955    fn report_editor_event(
12956        &self,
12957        operation: &'static str,
12958        file_extension: Option<String>,
12959        cx: &AppContext,
12960    ) {
12961        if cfg!(any(test, feature = "test-support")) {
12962            return;
12963        }
12964
12965        let Some(project) = &self.project else { return };
12966
12967        // If None, we are in a file without an extension
12968        let file = self
12969            .buffer
12970            .read(cx)
12971            .as_singleton()
12972            .and_then(|b| b.read(cx).file());
12973        let file_extension = file_extension.or(file
12974            .as_ref()
12975            .and_then(|file| Path::new(file.file_name(cx)).extension())
12976            .and_then(|e| e.to_str())
12977            .map(|a| a.to_string()));
12978
12979        let vim_mode = cx
12980            .global::<SettingsStore>()
12981            .raw_user_settings()
12982            .get("vim_mode")
12983            == Some(&serde_json::Value::Bool(true));
12984
12985        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12986            == language::language_settings::InlineCompletionProvider::Copilot;
12987        let copilot_enabled_for_language = self
12988            .buffer
12989            .read(cx)
12990            .settings_at(0, cx)
12991            .show_inline_completions;
12992
12993        let project = project.read(cx);
12994        let telemetry = project.client().telemetry().clone();
12995        telemetry.report_editor_event(
12996            file_extension,
12997            vim_mode,
12998            operation,
12999            copilot_enabled,
13000            copilot_enabled_for_language,
13001            project.is_via_ssh(),
13002        )
13003    }
13004
13005    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13006    /// with each line being an array of {text, highlight} objects.
13007    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13008        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13009            return;
13010        };
13011
13012        #[derive(Serialize)]
13013        struct Chunk<'a> {
13014            text: String,
13015            highlight: Option<&'a str>,
13016        }
13017
13018        let snapshot = buffer.read(cx).snapshot();
13019        let range = self
13020            .selected_text_range(false, cx)
13021            .and_then(|selection| {
13022                if selection.range.is_empty() {
13023                    None
13024                } else {
13025                    Some(selection.range)
13026                }
13027            })
13028            .unwrap_or_else(|| 0..snapshot.len());
13029
13030        let chunks = snapshot.chunks(range, true);
13031        let mut lines = Vec::new();
13032        let mut line: VecDeque<Chunk> = VecDeque::new();
13033
13034        let Some(style) = self.style.as_ref() else {
13035            return;
13036        };
13037
13038        for chunk in chunks {
13039            let highlight = chunk
13040                .syntax_highlight_id
13041                .and_then(|id| id.name(&style.syntax));
13042            let mut chunk_lines = chunk.text.split('\n').peekable();
13043            while let Some(text) = chunk_lines.next() {
13044                let mut merged_with_last_token = false;
13045                if let Some(last_token) = line.back_mut() {
13046                    if last_token.highlight == highlight {
13047                        last_token.text.push_str(text);
13048                        merged_with_last_token = true;
13049                    }
13050                }
13051
13052                if !merged_with_last_token {
13053                    line.push_back(Chunk {
13054                        text: text.into(),
13055                        highlight,
13056                    });
13057                }
13058
13059                if chunk_lines.peek().is_some() {
13060                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13061                        line.pop_front();
13062                    }
13063                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13064                        line.pop_back();
13065                    }
13066
13067                    lines.push(mem::take(&mut line));
13068                }
13069            }
13070        }
13071
13072        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13073            return;
13074        };
13075        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13076    }
13077
13078    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
13079        self.request_autoscroll(Autoscroll::newest(), cx);
13080        let position = self.selections.newest_display(cx).start;
13081        mouse_context_menu::deploy_context_menu(self, None, position, cx);
13082    }
13083
13084    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13085        &self.inlay_hint_cache
13086    }
13087
13088    pub fn replay_insert_event(
13089        &mut self,
13090        text: &str,
13091        relative_utf16_range: Option<Range<isize>>,
13092        cx: &mut ViewContext<Self>,
13093    ) {
13094        if !self.input_enabled {
13095            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13096            return;
13097        }
13098        if let Some(relative_utf16_range) = relative_utf16_range {
13099            let selections = self.selections.all::<OffsetUtf16>(cx);
13100            self.change_selections(None, cx, |s| {
13101                let new_ranges = selections.into_iter().map(|range| {
13102                    let start = OffsetUtf16(
13103                        range
13104                            .head()
13105                            .0
13106                            .saturating_add_signed(relative_utf16_range.start),
13107                    );
13108                    let end = OffsetUtf16(
13109                        range
13110                            .head()
13111                            .0
13112                            .saturating_add_signed(relative_utf16_range.end),
13113                    );
13114                    start..end
13115                });
13116                s.select_ranges(new_ranges);
13117            });
13118        }
13119
13120        self.handle_input(text, cx);
13121    }
13122
13123    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13124        let Some(provider) = self.semantics_provider.as_ref() else {
13125            return false;
13126        };
13127
13128        let mut supports = false;
13129        self.buffer().read(cx).for_each_buffer(|buffer| {
13130            supports |= provider.supports_inlay_hints(buffer, cx);
13131        });
13132        supports
13133    }
13134
13135    pub fn focus(&self, cx: &mut WindowContext) {
13136        cx.focus(&self.focus_handle)
13137    }
13138
13139    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13140        self.focus_handle.is_focused(cx)
13141    }
13142
13143    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13144        cx.emit(EditorEvent::Focused);
13145
13146        if let Some(descendant) = self
13147            .last_focused_descendant
13148            .take()
13149            .and_then(|descendant| descendant.upgrade())
13150        {
13151            cx.focus(&descendant);
13152        } else {
13153            if let Some(blame) = self.blame.as_ref() {
13154                blame.update(cx, GitBlame::focus)
13155            }
13156
13157            self.blink_manager.update(cx, BlinkManager::enable);
13158            self.show_cursor_names(cx);
13159            self.buffer.update(cx, |buffer, cx| {
13160                buffer.finalize_last_transaction(cx);
13161                if self.leader_peer_id.is_none() {
13162                    buffer.set_active_selections(
13163                        &self.selections.disjoint_anchors(),
13164                        self.selections.line_mode,
13165                        self.cursor_shape,
13166                        cx,
13167                    );
13168                }
13169            });
13170        }
13171    }
13172
13173    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13174        cx.emit(EditorEvent::FocusedIn)
13175    }
13176
13177    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13178        if event.blurred != self.focus_handle {
13179            self.last_focused_descendant = Some(event.blurred);
13180        }
13181    }
13182
13183    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13184        self.blink_manager.update(cx, BlinkManager::disable);
13185        self.buffer
13186            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13187
13188        if let Some(blame) = self.blame.as_ref() {
13189            blame.update(cx, GitBlame::blur)
13190        }
13191        if !self.hover_state.focused(cx) {
13192            hide_hover(self, cx);
13193        }
13194
13195        self.hide_context_menu(cx);
13196        cx.emit(EditorEvent::Blurred);
13197        cx.notify();
13198    }
13199
13200    pub fn register_action<A: Action>(
13201        &mut self,
13202        listener: impl Fn(&A, &mut WindowContext) + 'static,
13203    ) -> Subscription {
13204        let id = self.next_editor_action_id.post_inc();
13205        let listener = Arc::new(listener);
13206        self.editor_actions.borrow_mut().insert(
13207            id,
13208            Box::new(move |cx| {
13209                let cx = cx.window_context();
13210                let listener = listener.clone();
13211                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13212                    let action = action.downcast_ref().unwrap();
13213                    if phase == DispatchPhase::Bubble {
13214                        listener(action, cx)
13215                    }
13216                })
13217            }),
13218        );
13219
13220        let editor_actions = self.editor_actions.clone();
13221        Subscription::new(move || {
13222            editor_actions.borrow_mut().remove(&id);
13223        })
13224    }
13225
13226    pub fn file_header_size(&self) -> u32 {
13227        FILE_HEADER_HEIGHT
13228    }
13229
13230    pub fn revert(
13231        &mut self,
13232        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13233        cx: &mut ViewContext<Self>,
13234    ) {
13235        self.buffer().update(cx, |multi_buffer, cx| {
13236            for (buffer_id, changes) in revert_changes {
13237                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13238                    buffer.update(cx, |buffer, cx| {
13239                        buffer.edit(
13240                            changes.into_iter().map(|(range, text)| {
13241                                (range, text.to_string().map(Arc::<str>::from))
13242                            }),
13243                            None,
13244                            cx,
13245                        );
13246                    });
13247                }
13248            }
13249        });
13250        self.change_selections(None, cx, |selections| selections.refresh());
13251    }
13252
13253    pub fn to_pixel_point(
13254        &mut self,
13255        source: multi_buffer::Anchor,
13256        editor_snapshot: &EditorSnapshot,
13257        cx: &mut ViewContext<Self>,
13258    ) -> Option<gpui::Point<Pixels>> {
13259        let source_point = source.to_display_point(editor_snapshot);
13260        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13261    }
13262
13263    pub fn display_to_pixel_point(
13264        &mut self,
13265        source: DisplayPoint,
13266        editor_snapshot: &EditorSnapshot,
13267        cx: &mut ViewContext<Self>,
13268    ) -> Option<gpui::Point<Pixels>> {
13269        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13270        let text_layout_details = self.text_layout_details(cx);
13271        let scroll_top = text_layout_details
13272            .scroll_anchor
13273            .scroll_position(editor_snapshot)
13274            .y;
13275
13276        if source.row().as_f32() < scroll_top.floor() {
13277            return None;
13278        }
13279        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13280        let source_y = line_height * (source.row().as_f32() - scroll_top);
13281        Some(gpui::Point::new(source_x, source_y))
13282    }
13283
13284    pub fn has_active_completions_menu(&self) -> bool {
13285        self.context_menu.read().as_ref().map_or(false, |menu| {
13286            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13287        })
13288    }
13289
13290    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13291        self.addons
13292            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13293    }
13294
13295    pub fn unregister_addon<T: Addon>(&mut self) {
13296        self.addons.remove(&std::any::TypeId::of::<T>());
13297    }
13298
13299    pub fn addon<T: Addon>(&self) -> Option<&T> {
13300        let type_id = std::any::TypeId::of::<T>();
13301        self.addons
13302            .get(&type_id)
13303            .and_then(|item| item.to_any().downcast_ref::<T>())
13304    }
13305
13306    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13307        let text_layout_details = self.text_layout_details(cx);
13308        let style = &text_layout_details.editor_style;
13309        let font_id = cx.text_system().resolve_font(&style.text.font());
13310        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13311        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13312
13313        let em_width = cx
13314            .text_system()
13315            .typographic_bounds(font_id, font_size, 'm')
13316            .unwrap()
13317            .size
13318            .width;
13319
13320        gpui::Point::new(em_width, line_height)
13321    }
13322}
13323
13324fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13325    let tab_size = tab_size.get() as usize;
13326    let mut width = offset;
13327
13328    for ch in text.chars() {
13329        width += if ch == '\t' {
13330            tab_size - (width % tab_size)
13331        } else {
13332            1
13333        };
13334    }
13335
13336    width - offset
13337}
13338
13339#[cfg(test)]
13340mod tests {
13341    use super::*;
13342
13343    #[test]
13344    fn test_string_size_with_expanded_tabs() {
13345        let nz = |val| NonZeroU32::new(val).unwrap();
13346        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13347        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13348        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13349        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13350        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13351        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13352        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13353        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13354    }
13355}
13356
13357/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13358struct WordBreakingTokenizer<'a> {
13359    input: &'a str,
13360}
13361
13362impl<'a> WordBreakingTokenizer<'a> {
13363    fn new(input: &'a str) -> Self {
13364        Self { input }
13365    }
13366}
13367
13368fn is_char_ideographic(ch: char) -> bool {
13369    use unicode_script::Script::*;
13370    use unicode_script::UnicodeScript;
13371    matches!(ch.script(), Han | Tangut | Yi)
13372}
13373
13374fn is_grapheme_ideographic(text: &str) -> bool {
13375    text.chars().any(is_char_ideographic)
13376}
13377
13378fn is_grapheme_whitespace(text: &str) -> bool {
13379    text.chars().any(|x| x.is_whitespace())
13380}
13381
13382fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13383    text.chars().next().map_or(false, |ch| {
13384        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13385    })
13386}
13387
13388#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13389struct WordBreakToken<'a> {
13390    token: &'a str,
13391    grapheme_len: usize,
13392    is_whitespace: bool,
13393}
13394
13395impl<'a> Iterator for WordBreakingTokenizer<'a> {
13396    /// Yields a span, the count of graphemes in the token, and whether it was
13397    /// whitespace. Note that it also breaks at word boundaries.
13398    type Item = WordBreakToken<'a>;
13399
13400    fn next(&mut self) -> Option<Self::Item> {
13401        use unicode_segmentation::UnicodeSegmentation;
13402        if self.input.is_empty() {
13403            return None;
13404        }
13405
13406        let mut iter = self.input.graphemes(true).peekable();
13407        let mut offset = 0;
13408        let mut graphemes = 0;
13409        if let Some(first_grapheme) = iter.next() {
13410            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13411            offset += first_grapheme.len();
13412            graphemes += 1;
13413            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13414                if let Some(grapheme) = iter.peek().copied() {
13415                    if should_stay_with_preceding_ideograph(grapheme) {
13416                        offset += grapheme.len();
13417                        graphemes += 1;
13418                    }
13419                }
13420            } else {
13421                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13422                let mut next_word_bound = words.peek().copied();
13423                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13424                    next_word_bound = words.next();
13425                }
13426                while let Some(grapheme) = iter.peek().copied() {
13427                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13428                        break;
13429                    };
13430                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13431                        break;
13432                    };
13433                    offset += grapheme.len();
13434                    graphemes += 1;
13435                    iter.next();
13436                }
13437            }
13438            let token = &self.input[..offset];
13439            self.input = &self.input[offset..];
13440            if is_whitespace {
13441                Some(WordBreakToken {
13442                    token: " ",
13443                    grapheme_len: 1,
13444                    is_whitespace: true,
13445                })
13446            } else {
13447                Some(WordBreakToken {
13448                    token,
13449                    grapheme_len: graphemes,
13450                    is_whitespace: false,
13451                })
13452            }
13453        } else {
13454            None
13455        }
13456    }
13457}
13458
13459#[test]
13460fn test_word_breaking_tokenizer() {
13461    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13462        ("", &[]),
13463        ("  ", &[(" ", 1, true)]),
13464        ("Ʒ", &[("Ʒ", 1, false)]),
13465        ("Ǽ", &[("Ǽ", 1, false)]),
13466        ("", &[("", 1, false)]),
13467        ("⋑⋑", &[("⋑⋑", 2, false)]),
13468        (
13469            "原理,进而",
13470            &[
13471                ("", 1, false),
13472                ("理,", 2, false),
13473                ("", 1, false),
13474                ("", 1, false),
13475            ],
13476        ),
13477        (
13478            "hello world",
13479            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13480        ),
13481        (
13482            "hello, world",
13483            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13484        ),
13485        (
13486            "  hello world",
13487            &[
13488                (" ", 1, true),
13489                ("hello", 5, false),
13490                (" ", 1, true),
13491                ("world", 5, false),
13492            ],
13493        ),
13494        (
13495            "这是什么 \n 钢笔",
13496            &[
13497                ("", 1, false),
13498                ("", 1, false),
13499                ("", 1, false),
13500                ("", 1, false),
13501                (" ", 1, true),
13502                ("", 1, false),
13503                ("", 1, false),
13504            ],
13505        ),
13506        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13507    ];
13508
13509    for (input, result) in tests {
13510        assert_eq!(
13511            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13512            result
13513                .iter()
13514                .copied()
13515                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13516                    token,
13517                    grapheme_len,
13518                    is_whitespace,
13519                })
13520                .collect::<Vec<_>>()
13521        );
13522    }
13523}
13524
13525fn wrap_with_prefix(
13526    line_prefix: String,
13527    unwrapped_text: String,
13528    wrap_column: usize,
13529    tab_size: NonZeroU32,
13530) -> String {
13531    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13532    let mut wrapped_text = String::new();
13533    let mut current_line = line_prefix.clone();
13534
13535    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13536    let mut current_line_len = line_prefix_len;
13537    for WordBreakToken {
13538        token,
13539        grapheme_len,
13540        is_whitespace,
13541    } in tokenizer
13542    {
13543        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13544            wrapped_text.push_str(current_line.trim_end());
13545            wrapped_text.push('\n');
13546            current_line.truncate(line_prefix.len());
13547            current_line_len = line_prefix_len;
13548            if !is_whitespace {
13549                current_line.push_str(token);
13550                current_line_len += grapheme_len;
13551            }
13552        } else if !is_whitespace {
13553            current_line.push_str(token);
13554            current_line_len += grapheme_len;
13555        } else if current_line_len != line_prefix_len {
13556            current_line.push(' ');
13557            current_line_len += 1;
13558        }
13559    }
13560
13561    if !current_line.is_empty() {
13562        wrapped_text.push_str(&current_line);
13563    }
13564    wrapped_text
13565}
13566
13567#[test]
13568fn test_wrap_with_prefix() {
13569    assert_eq!(
13570        wrap_with_prefix(
13571            "# ".to_string(),
13572            "abcdefg".to_string(),
13573            4,
13574            NonZeroU32::new(4).unwrap()
13575        ),
13576        "# abcdefg"
13577    );
13578    assert_eq!(
13579        wrap_with_prefix(
13580            "".to_string(),
13581            "\thello world".to_string(),
13582            8,
13583            NonZeroU32::new(4).unwrap()
13584        ),
13585        "hello\nworld"
13586    );
13587    assert_eq!(
13588        wrap_with_prefix(
13589            "// ".to_string(),
13590            "xx \nyy zz aa bb cc".to_string(),
13591            12,
13592            NonZeroU32::new(4).unwrap()
13593        ),
13594        "// xx yy zz\n// aa bb cc"
13595    );
13596    assert_eq!(
13597        wrap_with_prefix(
13598            String::new(),
13599            "这是什么 \n 钢笔".to_string(),
13600            3,
13601            NonZeroU32::new(4).unwrap()
13602        ),
13603        "这是什\n么 钢\n"
13604    );
13605}
13606
13607fn hunks_for_selections(
13608    multi_buffer_snapshot: &MultiBufferSnapshot,
13609    selections: &[Selection<Anchor>],
13610) -> Vec<MultiBufferDiffHunk> {
13611    let buffer_rows_for_selections = selections.iter().map(|selection| {
13612        let head = selection.head();
13613        let tail = selection.tail();
13614        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13615        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13616        if start > end {
13617            end..start
13618        } else {
13619            start..end
13620        }
13621    });
13622
13623    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13624}
13625
13626pub fn hunks_for_rows(
13627    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13628    multi_buffer_snapshot: &MultiBufferSnapshot,
13629) -> Vec<MultiBufferDiffHunk> {
13630    let mut hunks = Vec::new();
13631    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13632        HashMap::default();
13633    for selected_multi_buffer_rows in rows {
13634        let query_rows =
13635            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13636        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13637            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13638            // when the caret is just above or just below the deleted hunk.
13639            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13640            let related_to_selection = if allow_adjacent {
13641                hunk.row_range.overlaps(&query_rows)
13642                    || hunk.row_range.start == query_rows.end
13643                    || hunk.row_range.end == query_rows.start
13644            } else {
13645                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13646                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13647                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13648                    || selected_multi_buffer_rows.end == hunk.row_range.start
13649            };
13650            if related_to_selection {
13651                if !processed_buffer_rows
13652                    .entry(hunk.buffer_id)
13653                    .or_default()
13654                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13655                {
13656                    continue;
13657                }
13658                hunks.push(hunk);
13659            }
13660        }
13661    }
13662
13663    hunks
13664}
13665
13666pub trait CollaborationHub {
13667    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13668    fn user_participant_indices<'a>(
13669        &self,
13670        cx: &'a AppContext,
13671    ) -> &'a HashMap<u64, ParticipantIndex>;
13672    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13673}
13674
13675impl CollaborationHub for Model<Project> {
13676    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13677        self.read(cx).collaborators()
13678    }
13679
13680    fn user_participant_indices<'a>(
13681        &self,
13682        cx: &'a AppContext,
13683    ) -> &'a HashMap<u64, ParticipantIndex> {
13684        self.read(cx).user_store().read(cx).participant_indices()
13685    }
13686
13687    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13688        let this = self.read(cx);
13689        let user_ids = this.collaborators().values().map(|c| c.user_id);
13690        this.user_store().read_with(cx, |user_store, cx| {
13691            user_store.participant_names(user_ids, cx)
13692        })
13693    }
13694}
13695
13696pub trait SemanticsProvider {
13697    fn hover(
13698        &self,
13699        buffer: &Model<Buffer>,
13700        position: text::Anchor,
13701        cx: &mut AppContext,
13702    ) -> Option<Task<Vec<project::Hover>>>;
13703
13704    fn inlay_hints(
13705        &self,
13706        buffer_handle: Model<Buffer>,
13707        range: Range<text::Anchor>,
13708        cx: &mut AppContext,
13709    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13710
13711    fn resolve_inlay_hint(
13712        &self,
13713        hint: InlayHint,
13714        buffer_handle: Model<Buffer>,
13715        server_id: LanguageServerId,
13716        cx: &mut AppContext,
13717    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13718
13719    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13720
13721    fn document_highlights(
13722        &self,
13723        buffer: &Model<Buffer>,
13724        position: text::Anchor,
13725        cx: &mut AppContext,
13726    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13727
13728    fn definitions(
13729        &self,
13730        buffer: &Model<Buffer>,
13731        position: text::Anchor,
13732        kind: GotoDefinitionKind,
13733        cx: &mut AppContext,
13734    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13735
13736    fn range_for_rename(
13737        &self,
13738        buffer: &Model<Buffer>,
13739        position: text::Anchor,
13740        cx: &mut AppContext,
13741    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13742
13743    fn perform_rename(
13744        &self,
13745        buffer: &Model<Buffer>,
13746        position: text::Anchor,
13747        new_name: String,
13748        cx: &mut AppContext,
13749    ) -> Option<Task<Result<ProjectTransaction>>>;
13750}
13751
13752pub trait CompletionProvider {
13753    fn completions(
13754        &self,
13755        buffer: &Model<Buffer>,
13756        buffer_position: text::Anchor,
13757        trigger: CompletionContext,
13758        cx: &mut ViewContext<Editor>,
13759    ) -> Task<Result<Vec<Completion>>>;
13760
13761    fn resolve_completions(
13762        &self,
13763        buffer: Model<Buffer>,
13764        completion_indices: Vec<usize>,
13765        completions: Arc<RwLock<Box<[Completion]>>>,
13766        cx: &mut ViewContext<Editor>,
13767    ) -> Task<Result<bool>>;
13768
13769    fn apply_additional_edits_for_completion(
13770        &self,
13771        buffer: Model<Buffer>,
13772        completion: Completion,
13773        push_to_history: bool,
13774        cx: &mut ViewContext<Editor>,
13775    ) -> Task<Result<Option<language::Transaction>>>;
13776
13777    fn is_completion_trigger(
13778        &self,
13779        buffer: &Model<Buffer>,
13780        position: language::Anchor,
13781        text: &str,
13782        trigger_in_words: bool,
13783        cx: &mut ViewContext<Editor>,
13784    ) -> bool;
13785
13786    fn sort_completions(&self) -> bool {
13787        true
13788    }
13789}
13790
13791pub trait CodeActionProvider {
13792    fn code_actions(
13793        &self,
13794        buffer: &Model<Buffer>,
13795        range: Range<text::Anchor>,
13796        cx: &mut WindowContext,
13797    ) -> Task<Result<Vec<CodeAction>>>;
13798
13799    fn apply_code_action(
13800        &self,
13801        buffer_handle: Model<Buffer>,
13802        action: CodeAction,
13803        excerpt_id: ExcerptId,
13804        push_to_history: bool,
13805        cx: &mut WindowContext,
13806    ) -> Task<Result<ProjectTransaction>>;
13807}
13808
13809impl CodeActionProvider for Model<Project> {
13810    fn code_actions(
13811        &self,
13812        buffer: &Model<Buffer>,
13813        range: Range<text::Anchor>,
13814        cx: &mut WindowContext,
13815    ) -> Task<Result<Vec<CodeAction>>> {
13816        self.update(cx, |project, cx| {
13817            project.code_actions(buffer, range, None, cx)
13818        })
13819    }
13820
13821    fn apply_code_action(
13822        &self,
13823        buffer_handle: Model<Buffer>,
13824        action: CodeAction,
13825        _excerpt_id: ExcerptId,
13826        push_to_history: bool,
13827        cx: &mut WindowContext,
13828    ) -> Task<Result<ProjectTransaction>> {
13829        self.update(cx, |project, cx| {
13830            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13831        })
13832    }
13833}
13834
13835fn snippet_completions(
13836    project: &Project,
13837    buffer: &Model<Buffer>,
13838    buffer_position: text::Anchor,
13839    cx: &mut AppContext,
13840) -> Task<Result<Vec<Completion>>> {
13841    let language = buffer.read(cx).language_at(buffer_position);
13842    let language_name = language.as_ref().map(|language| language.lsp_id());
13843    let snippet_store = project.snippets().read(cx);
13844    let snippets = snippet_store.snippets_for(language_name, cx);
13845
13846    if snippets.is_empty() {
13847        return Task::ready(Ok(vec![]));
13848    }
13849    let snapshot = buffer.read(cx).text_snapshot();
13850    let chars: String = snapshot
13851        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13852        .collect();
13853
13854    let scope = language.map(|language| language.default_scope());
13855    let executor = cx.background_executor().clone();
13856
13857    cx.background_executor().spawn(async move {
13858        let classifier = CharClassifier::new(scope).for_completion(true);
13859        let mut last_word = chars
13860            .chars()
13861            .take_while(|c| classifier.is_word(*c))
13862            .collect::<String>();
13863        last_word = last_word.chars().rev().collect();
13864        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13865        let to_lsp = |point: &text::Anchor| {
13866            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13867            point_to_lsp(end)
13868        };
13869        let lsp_end = to_lsp(&buffer_position);
13870
13871        let candidates = snippets
13872            .iter()
13873            .enumerate()
13874            .flat_map(|(ix, snippet)| {
13875                snippet
13876                    .prefix
13877                    .iter()
13878                    .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
13879            })
13880            .collect::<Vec<StringMatchCandidate>>();
13881
13882        let mut matches = fuzzy::match_strings(
13883            &candidates,
13884            &last_word,
13885            last_word.chars().any(|c| c.is_uppercase()),
13886            100,
13887            &Default::default(),
13888            executor,
13889        )
13890        .await;
13891
13892        // Remove all candidates where the query's start does not match the start of any word in the candidate
13893        if let Some(query_start) = last_word.chars().next() {
13894            matches.retain(|string_match| {
13895                split_words(&string_match.string).any(|word| {
13896                    // Check that the first codepoint of the word as lowercase matches the first
13897                    // codepoint of the query as lowercase
13898                    word.chars()
13899                        .flat_map(|codepoint| codepoint.to_lowercase())
13900                        .zip(query_start.to_lowercase())
13901                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13902                })
13903            });
13904        }
13905
13906        let matched_strings = matches
13907            .into_iter()
13908            .map(|m| m.string)
13909            .collect::<HashSet<_>>();
13910
13911        let result: Vec<Completion> = snippets
13912            .into_iter()
13913            .filter_map(|snippet| {
13914                let matching_prefix = snippet
13915                    .prefix
13916                    .iter()
13917                    .find(|prefix| matched_strings.contains(*prefix))?;
13918                let start = as_offset - last_word.len();
13919                let start = snapshot.anchor_before(start);
13920                let range = start..buffer_position;
13921                let lsp_start = to_lsp(&start);
13922                let lsp_range = lsp::Range {
13923                    start: lsp_start,
13924                    end: lsp_end,
13925                };
13926                Some(Completion {
13927                    old_range: range,
13928                    new_text: snippet.body.clone(),
13929                    label: CodeLabel {
13930                        text: matching_prefix.clone(),
13931                        runs: vec![],
13932                        filter_range: 0..matching_prefix.len(),
13933                    },
13934                    server_id: LanguageServerId(usize::MAX),
13935                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13936                    lsp_completion: lsp::CompletionItem {
13937                        label: snippet.prefix.first().unwrap().clone(),
13938                        kind: Some(CompletionItemKind::SNIPPET),
13939                        label_details: snippet.description.as_ref().map(|description| {
13940                            lsp::CompletionItemLabelDetails {
13941                                detail: Some(description.clone()),
13942                                description: None,
13943                            }
13944                        }),
13945                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13946                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13947                            lsp::InsertReplaceEdit {
13948                                new_text: snippet.body.clone(),
13949                                insert: lsp_range,
13950                                replace: lsp_range,
13951                            },
13952                        )),
13953                        filter_text: Some(snippet.body.clone()),
13954                        sort_text: Some(char::MAX.to_string()),
13955                        ..Default::default()
13956                    },
13957                    confirm: None,
13958                })
13959            })
13960            .collect();
13961
13962        Ok(result)
13963    })
13964}
13965
13966impl CompletionProvider for Model<Project> {
13967    fn completions(
13968        &self,
13969        buffer: &Model<Buffer>,
13970        buffer_position: text::Anchor,
13971        options: CompletionContext,
13972        cx: &mut ViewContext<Editor>,
13973    ) -> Task<Result<Vec<Completion>>> {
13974        self.update(cx, |project, cx| {
13975            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13976            let project_completions = project.completions(buffer, buffer_position, options, cx);
13977            cx.background_executor().spawn(async move {
13978                let mut completions = project_completions.await?;
13979                let snippets_completions = snippets.await?;
13980                completions.extend(snippets_completions);
13981                Ok(completions)
13982            })
13983        })
13984    }
13985
13986    fn resolve_completions(
13987        &self,
13988        buffer: Model<Buffer>,
13989        completion_indices: Vec<usize>,
13990        completions: Arc<RwLock<Box<[Completion]>>>,
13991        cx: &mut ViewContext<Editor>,
13992    ) -> Task<Result<bool>> {
13993        self.update(cx, |project, cx| {
13994            project.resolve_completions(buffer, completion_indices, completions, cx)
13995        })
13996    }
13997
13998    fn apply_additional_edits_for_completion(
13999        &self,
14000        buffer: Model<Buffer>,
14001        completion: Completion,
14002        push_to_history: bool,
14003        cx: &mut ViewContext<Editor>,
14004    ) -> Task<Result<Option<language::Transaction>>> {
14005        self.update(cx, |project, cx| {
14006            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
14007        })
14008    }
14009
14010    fn is_completion_trigger(
14011        &self,
14012        buffer: &Model<Buffer>,
14013        position: language::Anchor,
14014        text: &str,
14015        trigger_in_words: bool,
14016        cx: &mut ViewContext<Editor>,
14017    ) -> bool {
14018        if !EditorSettings::get_global(cx).show_completions_on_input {
14019            return false;
14020        }
14021
14022        let mut chars = text.chars();
14023        let char = if let Some(char) = chars.next() {
14024            char
14025        } else {
14026            return false;
14027        };
14028        if chars.next().is_some() {
14029            return false;
14030        }
14031
14032        let buffer = buffer.read(cx);
14033        let classifier = buffer
14034            .snapshot()
14035            .char_classifier_at(position)
14036            .for_completion(true);
14037        if trigger_in_words && classifier.is_word(char) {
14038            return true;
14039        }
14040
14041        buffer.completion_triggers().contains(text)
14042    }
14043}
14044
14045impl SemanticsProvider for Model<Project> {
14046    fn hover(
14047        &self,
14048        buffer: &Model<Buffer>,
14049        position: text::Anchor,
14050        cx: &mut AppContext,
14051    ) -> Option<Task<Vec<project::Hover>>> {
14052        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14053    }
14054
14055    fn document_highlights(
14056        &self,
14057        buffer: &Model<Buffer>,
14058        position: text::Anchor,
14059        cx: &mut AppContext,
14060    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14061        Some(self.update(cx, |project, cx| {
14062            project.document_highlights(buffer, position, cx)
14063        }))
14064    }
14065
14066    fn definitions(
14067        &self,
14068        buffer: &Model<Buffer>,
14069        position: text::Anchor,
14070        kind: GotoDefinitionKind,
14071        cx: &mut AppContext,
14072    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14073        Some(self.update(cx, |project, cx| match kind {
14074            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14075            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14076            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14077            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14078        }))
14079    }
14080
14081    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14082        // TODO: make this work for remote projects
14083        self.read(cx)
14084            .language_servers_for_buffer(buffer.read(cx), cx)
14085            .any(
14086                |(_, server)| match server.capabilities().inlay_hint_provider {
14087                    Some(lsp::OneOf::Left(enabled)) => enabled,
14088                    Some(lsp::OneOf::Right(_)) => true,
14089                    None => false,
14090                },
14091            )
14092    }
14093
14094    fn inlay_hints(
14095        &self,
14096        buffer_handle: Model<Buffer>,
14097        range: Range<text::Anchor>,
14098        cx: &mut AppContext,
14099    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14100        Some(self.update(cx, |project, cx| {
14101            project.inlay_hints(buffer_handle, range, cx)
14102        }))
14103    }
14104
14105    fn resolve_inlay_hint(
14106        &self,
14107        hint: InlayHint,
14108        buffer_handle: Model<Buffer>,
14109        server_id: LanguageServerId,
14110        cx: &mut AppContext,
14111    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14112        Some(self.update(cx, |project, cx| {
14113            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14114        }))
14115    }
14116
14117    fn range_for_rename(
14118        &self,
14119        buffer: &Model<Buffer>,
14120        position: text::Anchor,
14121        cx: &mut AppContext,
14122    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14123        Some(self.update(cx, |project, cx| {
14124            project.prepare_rename(buffer.clone(), position, cx)
14125        }))
14126    }
14127
14128    fn perform_rename(
14129        &self,
14130        buffer: &Model<Buffer>,
14131        position: text::Anchor,
14132        new_name: String,
14133        cx: &mut AppContext,
14134    ) -> Option<Task<Result<ProjectTransaction>>> {
14135        Some(self.update(cx, |project, cx| {
14136            project.perform_rename(buffer.clone(), position, new_name, cx)
14137        }))
14138    }
14139}
14140
14141fn inlay_hint_settings(
14142    location: Anchor,
14143    snapshot: &MultiBufferSnapshot,
14144    cx: &mut ViewContext<'_, Editor>,
14145) -> InlayHintSettings {
14146    let file = snapshot.file_at(location);
14147    let language = snapshot.language_at(location).map(|l| l.name());
14148    language_settings(language, file, cx).inlay_hints
14149}
14150
14151fn consume_contiguous_rows(
14152    contiguous_row_selections: &mut Vec<Selection<Point>>,
14153    selection: &Selection<Point>,
14154    display_map: &DisplaySnapshot,
14155    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14156) -> (MultiBufferRow, MultiBufferRow) {
14157    contiguous_row_selections.push(selection.clone());
14158    let start_row = MultiBufferRow(selection.start.row);
14159    let mut end_row = ending_row(selection, display_map);
14160
14161    while let Some(next_selection) = selections.peek() {
14162        if next_selection.start.row <= end_row.0 {
14163            end_row = ending_row(next_selection, display_map);
14164            contiguous_row_selections.push(selections.next().unwrap().clone());
14165        } else {
14166            break;
14167        }
14168    }
14169    (start_row, end_row)
14170}
14171
14172fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14173    if next_selection.end.column > 0 || next_selection.is_empty() {
14174        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14175    } else {
14176        MultiBufferRow(next_selection.end.row)
14177    }
14178}
14179
14180impl EditorSnapshot {
14181    pub fn remote_selections_in_range<'a>(
14182        &'a self,
14183        range: &'a Range<Anchor>,
14184        collaboration_hub: &dyn CollaborationHub,
14185        cx: &'a AppContext,
14186    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14187        let participant_names = collaboration_hub.user_names(cx);
14188        let participant_indices = collaboration_hub.user_participant_indices(cx);
14189        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14190        let collaborators_by_replica_id = collaborators_by_peer_id
14191            .iter()
14192            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14193            .collect::<HashMap<_, _>>();
14194        self.buffer_snapshot
14195            .selections_in_range(range, false)
14196            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14197                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14198                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14199                let user_name = participant_names.get(&collaborator.user_id).cloned();
14200                Some(RemoteSelection {
14201                    replica_id,
14202                    selection,
14203                    cursor_shape,
14204                    line_mode,
14205                    participant_index,
14206                    peer_id: collaborator.peer_id,
14207                    user_name,
14208                })
14209            })
14210    }
14211
14212    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14213        self.display_snapshot.buffer_snapshot.language_at(position)
14214    }
14215
14216    pub fn is_focused(&self) -> bool {
14217        self.is_focused
14218    }
14219
14220    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14221        self.placeholder_text.as_ref()
14222    }
14223
14224    pub fn scroll_position(&self) -> gpui::Point<f32> {
14225        self.scroll_anchor.scroll_position(&self.display_snapshot)
14226    }
14227
14228    fn gutter_dimensions(
14229        &self,
14230        font_id: FontId,
14231        font_size: Pixels,
14232        em_width: Pixels,
14233        em_advance: Pixels,
14234        max_line_number_width: Pixels,
14235        cx: &AppContext,
14236    ) -> GutterDimensions {
14237        if !self.show_gutter {
14238            return GutterDimensions::default();
14239        }
14240        let descent = cx.text_system().descent(font_id, font_size);
14241
14242        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14243            matches!(
14244                ProjectSettings::get_global(cx).git.git_gutter,
14245                Some(GitGutterSetting::TrackedFiles)
14246            )
14247        });
14248        let gutter_settings = EditorSettings::get_global(cx).gutter;
14249        let show_line_numbers = self
14250            .show_line_numbers
14251            .unwrap_or(gutter_settings.line_numbers);
14252        let line_gutter_width = if show_line_numbers {
14253            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14254            let min_width_for_number_on_gutter = em_advance * 4.0;
14255            max_line_number_width.max(min_width_for_number_on_gutter)
14256        } else {
14257            0.0.into()
14258        };
14259
14260        let show_code_actions = self
14261            .show_code_actions
14262            .unwrap_or(gutter_settings.code_actions);
14263
14264        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14265
14266        let git_blame_entries_width =
14267            self.git_blame_gutter_max_author_length
14268                .map(|max_author_length| {
14269                    // Length of the author name, but also space for the commit hash,
14270                    // the spacing and the timestamp.
14271                    let max_char_count = max_author_length
14272                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14273                        + 7 // length of commit sha
14274                        + 14 // length of max relative timestamp ("60 minutes ago")
14275                        + 4; // gaps and margins
14276
14277                    em_advance * max_char_count
14278                });
14279
14280        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14281        left_padding += if show_code_actions || show_runnables {
14282            em_width * 3.0
14283        } else if show_git_gutter && show_line_numbers {
14284            em_width * 2.0
14285        } else if show_git_gutter || show_line_numbers {
14286            em_width
14287        } else {
14288            px(0.)
14289        };
14290
14291        let right_padding = if gutter_settings.folds && show_line_numbers {
14292            em_width * 4.0
14293        } else if gutter_settings.folds {
14294            em_width * 3.0
14295        } else if show_line_numbers {
14296            em_width
14297        } else {
14298            px(0.)
14299        };
14300
14301        GutterDimensions {
14302            left_padding,
14303            right_padding,
14304            width: line_gutter_width + left_padding + right_padding,
14305            margin: -descent,
14306            git_blame_entries_width,
14307        }
14308    }
14309
14310    pub fn render_crease_toggle(
14311        &self,
14312        buffer_row: MultiBufferRow,
14313        row_contains_cursor: bool,
14314        editor: View<Editor>,
14315        cx: &mut WindowContext,
14316    ) -> Option<AnyElement> {
14317        let folded = self.is_line_folded(buffer_row);
14318        let mut is_foldable = false;
14319
14320        if let Some(crease) = self
14321            .crease_snapshot
14322            .query_row(buffer_row, &self.buffer_snapshot)
14323        {
14324            is_foldable = true;
14325            match crease {
14326                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14327                    if let Some(render_toggle) = render_toggle {
14328                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14329                            if folded {
14330                                editor.update(cx, |editor, cx| {
14331                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14332                                });
14333                            } else {
14334                                editor.update(cx, |editor, cx| {
14335                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14336                                });
14337                            }
14338                        });
14339                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14340                    }
14341                }
14342            }
14343        }
14344
14345        is_foldable |= self.starts_indent(buffer_row);
14346
14347        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14348            Some(
14349                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14350                    .selected(folded)
14351                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14352                        if folded {
14353                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14354                        } else {
14355                            this.fold_at(&FoldAt { buffer_row }, cx);
14356                        }
14357                    }))
14358                    .into_any_element(),
14359            )
14360        } else {
14361            None
14362        }
14363    }
14364
14365    pub fn render_crease_trailer(
14366        &self,
14367        buffer_row: MultiBufferRow,
14368        cx: &mut WindowContext,
14369    ) -> Option<AnyElement> {
14370        let folded = self.is_line_folded(buffer_row);
14371        if let Crease::Inline { render_trailer, .. } = self
14372            .crease_snapshot
14373            .query_row(buffer_row, &self.buffer_snapshot)?
14374        {
14375            let render_trailer = render_trailer.as_ref()?;
14376            Some(render_trailer(buffer_row, folded, cx))
14377        } else {
14378            None
14379        }
14380    }
14381}
14382
14383impl Deref for EditorSnapshot {
14384    type Target = DisplaySnapshot;
14385
14386    fn deref(&self) -> &Self::Target {
14387        &self.display_snapshot
14388    }
14389}
14390
14391#[derive(Clone, Debug, PartialEq, Eq)]
14392pub enum EditorEvent {
14393    InputIgnored {
14394        text: Arc<str>,
14395    },
14396    InputHandled {
14397        utf16_range_to_replace: Option<Range<isize>>,
14398        text: Arc<str>,
14399    },
14400    ExcerptsAdded {
14401        buffer: Model<Buffer>,
14402        predecessor: ExcerptId,
14403        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14404    },
14405    ExcerptsRemoved {
14406        ids: Vec<ExcerptId>,
14407    },
14408    ExcerptsEdited {
14409        ids: Vec<ExcerptId>,
14410    },
14411    ExcerptsExpanded {
14412        ids: Vec<ExcerptId>,
14413    },
14414    BufferEdited,
14415    Edited {
14416        transaction_id: clock::Lamport,
14417    },
14418    Reparsed(BufferId),
14419    Focused,
14420    FocusedIn,
14421    Blurred,
14422    DirtyChanged,
14423    Saved,
14424    TitleChanged,
14425    DiffBaseChanged,
14426    SelectionsChanged {
14427        local: bool,
14428    },
14429    ScrollPositionChanged {
14430        local: bool,
14431        autoscroll: bool,
14432    },
14433    Closed,
14434    TransactionUndone {
14435        transaction_id: clock::Lamport,
14436    },
14437    TransactionBegun {
14438        transaction_id: clock::Lamport,
14439    },
14440    Reloaded,
14441    CursorShapeChanged,
14442}
14443
14444impl EventEmitter<EditorEvent> for Editor {}
14445
14446impl FocusableView for Editor {
14447    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14448        self.focus_handle.clone()
14449    }
14450}
14451
14452impl Render for Editor {
14453    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14454        let settings = ThemeSettings::get_global(cx);
14455
14456        let mut text_style = match self.mode {
14457            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14458                color: cx.theme().colors().editor_foreground,
14459                font_family: settings.ui_font.family.clone(),
14460                font_features: settings.ui_font.features.clone(),
14461                font_fallbacks: settings.ui_font.fallbacks.clone(),
14462                font_size: rems(0.875).into(),
14463                font_weight: settings.ui_font.weight,
14464                line_height: relative(settings.buffer_line_height.value()),
14465                ..Default::default()
14466            },
14467            EditorMode::Full => TextStyle {
14468                color: cx.theme().colors().editor_foreground,
14469                font_family: settings.buffer_font.family.clone(),
14470                font_features: settings.buffer_font.features.clone(),
14471                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14472                font_size: settings.buffer_font_size(cx).into(),
14473                font_weight: settings.buffer_font.weight,
14474                line_height: relative(settings.buffer_line_height.value()),
14475                ..Default::default()
14476            },
14477        };
14478        if let Some(text_style_refinement) = &self.text_style_refinement {
14479            text_style.refine(text_style_refinement)
14480        }
14481
14482        let background = match self.mode {
14483            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14484            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14485            EditorMode::Full => cx.theme().colors().editor_background,
14486        };
14487
14488        EditorElement::new(
14489            cx.view(),
14490            EditorStyle {
14491                background,
14492                local_player: cx.theme().players().local(),
14493                text: text_style,
14494                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14495                syntax: cx.theme().syntax().clone(),
14496                status: cx.theme().status().clone(),
14497                inlay_hints_style: make_inlay_hints_style(cx),
14498                suggestions_style: HighlightStyle {
14499                    color: Some(cx.theme().status().predictive),
14500                    ..HighlightStyle::default()
14501                },
14502                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14503            },
14504        )
14505    }
14506}
14507
14508impl ViewInputHandler for Editor {
14509    fn text_for_range(
14510        &mut self,
14511        range_utf16: Range<usize>,
14512        adjusted_range: &mut Option<Range<usize>>,
14513        cx: &mut ViewContext<Self>,
14514    ) -> Option<String> {
14515        let snapshot = self.buffer.read(cx).read(cx);
14516        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14517        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14518        if (start.0..end.0) != range_utf16 {
14519            adjusted_range.replace(start.0..end.0);
14520        }
14521        Some(snapshot.text_for_range(start..end).collect())
14522    }
14523
14524    fn selected_text_range(
14525        &mut self,
14526        ignore_disabled_input: bool,
14527        cx: &mut ViewContext<Self>,
14528    ) -> Option<UTF16Selection> {
14529        // Prevent the IME menu from appearing when holding down an alphabetic key
14530        // while input is disabled.
14531        if !ignore_disabled_input && !self.input_enabled {
14532            return None;
14533        }
14534
14535        let selection = self.selections.newest::<OffsetUtf16>(cx);
14536        let range = selection.range();
14537
14538        Some(UTF16Selection {
14539            range: range.start.0..range.end.0,
14540            reversed: selection.reversed,
14541        })
14542    }
14543
14544    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14545        let snapshot = self.buffer.read(cx).read(cx);
14546        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14547        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14548    }
14549
14550    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14551        self.clear_highlights::<InputComposition>(cx);
14552        self.ime_transaction.take();
14553    }
14554
14555    fn replace_text_in_range(
14556        &mut self,
14557        range_utf16: Option<Range<usize>>,
14558        text: &str,
14559        cx: &mut ViewContext<Self>,
14560    ) {
14561        if !self.input_enabled {
14562            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14563            return;
14564        }
14565
14566        self.transact(cx, |this, cx| {
14567            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14568                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14569                Some(this.selection_replacement_ranges(range_utf16, cx))
14570            } else {
14571                this.marked_text_ranges(cx)
14572            };
14573
14574            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14575                let newest_selection_id = this.selections.newest_anchor().id;
14576                this.selections
14577                    .all::<OffsetUtf16>(cx)
14578                    .iter()
14579                    .zip(ranges_to_replace.iter())
14580                    .find_map(|(selection, range)| {
14581                        if selection.id == newest_selection_id {
14582                            Some(
14583                                (range.start.0 as isize - selection.head().0 as isize)
14584                                    ..(range.end.0 as isize - selection.head().0 as isize),
14585                            )
14586                        } else {
14587                            None
14588                        }
14589                    })
14590            });
14591
14592            cx.emit(EditorEvent::InputHandled {
14593                utf16_range_to_replace: range_to_replace,
14594                text: text.into(),
14595            });
14596
14597            if let Some(new_selected_ranges) = new_selected_ranges {
14598                this.change_selections(None, cx, |selections| {
14599                    selections.select_ranges(new_selected_ranges)
14600                });
14601                this.backspace(&Default::default(), cx);
14602            }
14603
14604            this.handle_input(text, cx);
14605        });
14606
14607        if let Some(transaction) = self.ime_transaction {
14608            self.buffer.update(cx, |buffer, cx| {
14609                buffer.group_until_transaction(transaction, cx);
14610            });
14611        }
14612
14613        self.unmark_text(cx);
14614    }
14615
14616    fn replace_and_mark_text_in_range(
14617        &mut self,
14618        range_utf16: Option<Range<usize>>,
14619        text: &str,
14620        new_selected_range_utf16: Option<Range<usize>>,
14621        cx: &mut ViewContext<Self>,
14622    ) {
14623        if !self.input_enabled {
14624            return;
14625        }
14626
14627        let transaction = self.transact(cx, |this, cx| {
14628            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14629                let snapshot = this.buffer.read(cx).read(cx);
14630                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14631                    for marked_range in &mut marked_ranges {
14632                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14633                        marked_range.start.0 += relative_range_utf16.start;
14634                        marked_range.start =
14635                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14636                        marked_range.end =
14637                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14638                    }
14639                }
14640                Some(marked_ranges)
14641            } else if let Some(range_utf16) = range_utf16 {
14642                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14643                Some(this.selection_replacement_ranges(range_utf16, cx))
14644            } else {
14645                None
14646            };
14647
14648            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14649                let newest_selection_id = this.selections.newest_anchor().id;
14650                this.selections
14651                    .all::<OffsetUtf16>(cx)
14652                    .iter()
14653                    .zip(ranges_to_replace.iter())
14654                    .find_map(|(selection, range)| {
14655                        if selection.id == newest_selection_id {
14656                            Some(
14657                                (range.start.0 as isize - selection.head().0 as isize)
14658                                    ..(range.end.0 as isize - selection.head().0 as isize),
14659                            )
14660                        } else {
14661                            None
14662                        }
14663                    })
14664            });
14665
14666            cx.emit(EditorEvent::InputHandled {
14667                utf16_range_to_replace: range_to_replace,
14668                text: text.into(),
14669            });
14670
14671            if let Some(ranges) = ranges_to_replace {
14672                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14673            }
14674
14675            let marked_ranges = {
14676                let snapshot = this.buffer.read(cx).read(cx);
14677                this.selections
14678                    .disjoint_anchors()
14679                    .iter()
14680                    .map(|selection| {
14681                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14682                    })
14683                    .collect::<Vec<_>>()
14684            };
14685
14686            if text.is_empty() {
14687                this.unmark_text(cx);
14688            } else {
14689                this.highlight_text::<InputComposition>(
14690                    marked_ranges.clone(),
14691                    HighlightStyle {
14692                        underline: Some(UnderlineStyle {
14693                            thickness: px(1.),
14694                            color: None,
14695                            wavy: false,
14696                        }),
14697                        ..Default::default()
14698                    },
14699                    cx,
14700                );
14701            }
14702
14703            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14704            let use_autoclose = this.use_autoclose;
14705            let use_auto_surround = this.use_auto_surround;
14706            this.set_use_autoclose(false);
14707            this.set_use_auto_surround(false);
14708            this.handle_input(text, cx);
14709            this.set_use_autoclose(use_autoclose);
14710            this.set_use_auto_surround(use_auto_surround);
14711
14712            if let Some(new_selected_range) = new_selected_range_utf16 {
14713                let snapshot = this.buffer.read(cx).read(cx);
14714                let new_selected_ranges = marked_ranges
14715                    .into_iter()
14716                    .map(|marked_range| {
14717                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14718                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14719                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14720                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14721                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14722                    })
14723                    .collect::<Vec<_>>();
14724
14725                drop(snapshot);
14726                this.change_selections(None, cx, |selections| {
14727                    selections.select_ranges(new_selected_ranges)
14728                });
14729            }
14730        });
14731
14732        self.ime_transaction = self.ime_transaction.or(transaction);
14733        if let Some(transaction) = self.ime_transaction {
14734            self.buffer.update(cx, |buffer, cx| {
14735                buffer.group_until_transaction(transaction, cx);
14736            });
14737        }
14738
14739        if self.text_highlights::<InputComposition>(cx).is_none() {
14740            self.ime_transaction.take();
14741        }
14742    }
14743
14744    fn bounds_for_range(
14745        &mut self,
14746        range_utf16: Range<usize>,
14747        element_bounds: gpui::Bounds<Pixels>,
14748        cx: &mut ViewContext<Self>,
14749    ) -> Option<gpui::Bounds<Pixels>> {
14750        let text_layout_details = self.text_layout_details(cx);
14751        let gpui::Point {
14752            x: em_width,
14753            y: line_height,
14754        } = self.character_size(cx);
14755
14756        let snapshot = self.snapshot(cx);
14757        let scroll_position = snapshot.scroll_position();
14758        let scroll_left = scroll_position.x * em_width;
14759
14760        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14761        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14762            + self.gutter_dimensions.width
14763            + self.gutter_dimensions.margin;
14764        let y = line_height * (start.row().as_f32() - scroll_position.y);
14765
14766        Some(Bounds {
14767            origin: element_bounds.origin + point(x, y),
14768            size: size(em_width, line_height),
14769        })
14770    }
14771}
14772
14773trait SelectionExt {
14774    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14775    fn spanned_rows(
14776        &self,
14777        include_end_if_at_line_start: bool,
14778        map: &DisplaySnapshot,
14779    ) -> Range<MultiBufferRow>;
14780}
14781
14782impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14783    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14784        let start = self
14785            .start
14786            .to_point(&map.buffer_snapshot)
14787            .to_display_point(map);
14788        let end = self
14789            .end
14790            .to_point(&map.buffer_snapshot)
14791            .to_display_point(map);
14792        if self.reversed {
14793            end..start
14794        } else {
14795            start..end
14796        }
14797    }
14798
14799    fn spanned_rows(
14800        &self,
14801        include_end_if_at_line_start: bool,
14802        map: &DisplaySnapshot,
14803    ) -> Range<MultiBufferRow> {
14804        let start = self.start.to_point(&map.buffer_snapshot);
14805        let mut end = self.end.to_point(&map.buffer_snapshot);
14806        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14807            end.row -= 1;
14808        }
14809
14810        let buffer_start = map.prev_line_boundary(start).0;
14811        let buffer_end = map.next_line_boundary(end).0;
14812        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14813    }
14814}
14815
14816impl<T: InvalidationRegion> InvalidationStack<T> {
14817    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14818    where
14819        S: Clone + ToOffset,
14820    {
14821        while let Some(region) = self.last() {
14822            let all_selections_inside_invalidation_ranges =
14823                if selections.len() == region.ranges().len() {
14824                    selections
14825                        .iter()
14826                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14827                        .all(|(selection, invalidation_range)| {
14828                            let head = selection.head().to_offset(buffer);
14829                            invalidation_range.start <= head && invalidation_range.end >= head
14830                        })
14831                } else {
14832                    false
14833                };
14834
14835            if all_selections_inside_invalidation_ranges {
14836                break;
14837            } else {
14838                self.pop();
14839            }
14840        }
14841    }
14842}
14843
14844impl<T> Default for InvalidationStack<T> {
14845    fn default() -> Self {
14846        Self(Default::default())
14847    }
14848}
14849
14850impl<T> Deref for InvalidationStack<T> {
14851    type Target = Vec<T>;
14852
14853    fn deref(&self) -> &Self::Target {
14854        &self.0
14855    }
14856}
14857
14858impl<T> DerefMut for InvalidationStack<T> {
14859    fn deref_mut(&mut self) -> &mut Self::Target {
14860        &mut self.0
14861    }
14862}
14863
14864impl InvalidationRegion for SnippetState {
14865    fn ranges(&self) -> &[Range<Anchor>] {
14866        &self.ranges[self.active_index]
14867    }
14868}
14869
14870pub fn diagnostic_block_renderer(
14871    diagnostic: Diagnostic,
14872    max_message_rows: Option<u8>,
14873    allow_closing: bool,
14874    _is_valid: bool,
14875) -> RenderBlock {
14876    let (text_without_backticks, code_ranges) =
14877        highlight_diagnostic_message(&diagnostic, max_message_rows);
14878
14879    Arc::new(move |cx: &mut BlockContext| {
14880        let group_id: SharedString = cx.block_id.to_string().into();
14881
14882        let mut text_style = cx.text_style().clone();
14883        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14884        let theme_settings = ThemeSettings::get_global(cx);
14885        text_style.font_family = theme_settings.buffer_font.family.clone();
14886        text_style.font_style = theme_settings.buffer_font.style;
14887        text_style.font_features = theme_settings.buffer_font.features.clone();
14888        text_style.font_weight = theme_settings.buffer_font.weight;
14889
14890        let multi_line_diagnostic = diagnostic.message.contains('\n');
14891
14892        let buttons = |diagnostic: &Diagnostic| {
14893            if multi_line_diagnostic {
14894                v_flex()
14895            } else {
14896                h_flex()
14897            }
14898            .when(allow_closing, |div| {
14899                div.children(diagnostic.is_primary.then(|| {
14900                    IconButton::new("close-block", IconName::XCircle)
14901                        .icon_color(Color::Muted)
14902                        .size(ButtonSize::Compact)
14903                        .style(ButtonStyle::Transparent)
14904                        .visible_on_hover(group_id.clone())
14905                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14906                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14907                }))
14908            })
14909            .child(
14910                IconButton::new("copy-block", IconName::Copy)
14911                    .icon_color(Color::Muted)
14912                    .size(ButtonSize::Compact)
14913                    .style(ButtonStyle::Transparent)
14914                    .visible_on_hover(group_id.clone())
14915                    .on_click({
14916                        let message = diagnostic.message.clone();
14917                        move |_click, cx| {
14918                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14919                        }
14920                    })
14921                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14922            )
14923        };
14924
14925        let icon_size = buttons(&diagnostic)
14926            .into_any_element()
14927            .layout_as_root(AvailableSpace::min_size(), cx);
14928
14929        h_flex()
14930            .id(cx.block_id)
14931            .group(group_id.clone())
14932            .relative()
14933            .size_full()
14934            .block_mouse_down()
14935            .pl(cx.gutter_dimensions.width)
14936            .w(cx.max_width - cx.gutter_dimensions.full_width())
14937            .child(
14938                div()
14939                    .flex()
14940                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14941                    .flex_shrink(),
14942            )
14943            .child(buttons(&diagnostic))
14944            .child(div().flex().flex_shrink_0().child(
14945                StyledText::new(text_without_backticks.clone()).with_highlights(
14946                    &text_style,
14947                    code_ranges.iter().map(|range| {
14948                        (
14949                            range.clone(),
14950                            HighlightStyle {
14951                                font_weight: Some(FontWeight::BOLD),
14952                                ..Default::default()
14953                            },
14954                        )
14955                    }),
14956                ),
14957            ))
14958            .into_any_element()
14959    })
14960}
14961
14962pub fn highlight_diagnostic_message(
14963    diagnostic: &Diagnostic,
14964    mut max_message_rows: Option<u8>,
14965) -> (SharedString, Vec<Range<usize>>) {
14966    let mut text_without_backticks = String::new();
14967    let mut code_ranges = Vec::new();
14968
14969    if let Some(source) = &diagnostic.source {
14970        text_without_backticks.push_str(source);
14971        code_ranges.push(0..source.len());
14972        text_without_backticks.push_str(": ");
14973    }
14974
14975    let mut prev_offset = 0;
14976    let mut in_code_block = false;
14977    let has_row_limit = max_message_rows.is_some();
14978    let mut newline_indices = diagnostic
14979        .message
14980        .match_indices('\n')
14981        .filter(|_| has_row_limit)
14982        .map(|(ix, _)| ix)
14983        .fuse()
14984        .peekable();
14985
14986    for (quote_ix, _) in diagnostic
14987        .message
14988        .match_indices('`')
14989        .chain([(diagnostic.message.len(), "")])
14990    {
14991        let mut first_newline_ix = None;
14992        let mut last_newline_ix = None;
14993        while let Some(newline_ix) = newline_indices.peek() {
14994            if *newline_ix < quote_ix {
14995                if first_newline_ix.is_none() {
14996                    first_newline_ix = Some(*newline_ix);
14997                }
14998                last_newline_ix = Some(*newline_ix);
14999
15000                if let Some(rows_left) = &mut max_message_rows {
15001                    if *rows_left == 0 {
15002                        break;
15003                    } else {
15004                        *rows_left -= 1;
15005                    }
15006                }
15007                let _ = newline_indices.next();
15008            } else {
15009                break;
15010            }
15011        }
15012        let prev_len = text_without_backticks.len();
15013        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15014        text_without_backticks.push_str(new_text);
15015        if in_code_block {
15016            code_ranges.push(prev_len..text_without_backticks.len());
15017        }
15018        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15019        in_code_block = !in_code_block;
15020        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15021            text_without_backticks.push_str("...");
15022            break;
15023        }
15024    }
15025
15026    (text_without_backticks.into(), code_ranges)
15027}
15028
15029fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15030    match severity {
15031        DiagnosticSeverity::ERROR => colors.error,
15032        DiagnosticSeverity::WARNING => colors.warning,
15033        DiagnosticSeverity::INFORMATION => colors.info,
15034        DiagnosticSeverity::HINT => colors.info,
15035        _ => colors.ignored,
15036    }
15037}
15038
15039pub fn styled_runs_for_code_label<'a>(
15040    label: &'a CodeLabel,
15041    syntax_theme: &'a theme::SyntaxTheme,
15042) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15043    let fade_out = HighlightStyle {
15044        fade_out: Some(0.35),
15045        ..Default::default()
15046    };
15047
15048    let mut prev_end = label.filter_range.end;
15049    label
15050        .runs
15051        .iter()
15052        .enumerate()
15053        .flat_map(move |(ix, (range, highlight_id))| {
15054            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15055                style
15056            } else {
15057                return Default::default();
15058            };
15059            let mut muted_style = style;
15060            muted_style.highlight(fade_out);
15061
15062            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15063            if range.start >= label.filter_range.end {
15064                if range.start > prev_end {
15065                    runs.push((prev_end..range.start, fade_out));
15066                }
15067                runs.push((range.clone(), muted_style));
15068            } else if range.end <= label.filter_range.end {
15069                runs.push((range.clone(), style));
15070            } else {
15071                runs.push((range.start..label.filter_range.end, style));
15072                runs.push((label.filter_range.end..range.end, muted_style));
15073            }
15074            prev_end = cmp::max(prev_end, range.end);
15075
15076            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15077                runs.push((prev_end..label.text.len(), fade_out));
15078            }
15079
15080            runs
15081        })
15082}
15083
15084pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15085    let mut prev_index = 0;
15086    let mut prev_codepoint: Option<char> = None;
15087    text.char_indices()
15088        .chain([(text.len(), '\0')])
15089        .filter_map(move |(index, codepoint)| {
15090            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15091            let is_boundary = index == text.len()
15092                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15093                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15094            if is_boundary {
15095                let chunk = &text[prev_index..index];
15096                prev_index = index;
15097                Some(chunk)
15098            } else {
15099                None
15100            }
15101        })
15102}
15103
15104pub trait RangeToAnchorExt: Sized {
15105    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15106
15107    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15108        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15109        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15110    }
15111}
15112
15113impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15114    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15115        let start_offset = self.start.to_offset(snapshot);
15116        let end_offset = self.end.to_offset(snapshot);
15117        if start_offset == end_offset {
15118            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15119        } else {
15120            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15121        }
15122    }
15123}
15124
15125pub trait RowExt {
15126    fn as_f32(&self) -> f32;
15127
15128    fn next_row(&self) -> Self;
15129
15130    fn previous_row(&self) -> Self;
15131
15132    fn minus(&self, other: Self) -> u32;
15133}
15134
15135impl RowExt for DisplayRow {
15136    fn as_f32(&self) -> f32 {
15137        self.0 as f32
15138    }
15139
15140    fn next_row(&self) -> Self {
15141        Self(self.0 + 1)
15142    }
15143
15144    fn previous_row(&self) -> Self {
15145        Self(self.0.saturating_sub(1))
15146    }
15147
15148    fn minus(&self, other: Self) -> u32 {
15149        self.0 - other.0
15150    }
15151}
15152
15153impl RowExt for MultiBufferRow {
15154    fn as_f32(&self) -> f32 {
15155        self.0 as f32
15156    }
15157
15158    fn next_row(&self) -> Self {
15159        Self(self.0 + 1)
15160    }
15161
15162    fn previous_row(&self) -> Self {
15163        Self(self.0.saturating_sub(1))
15164    }
15165
15166    fn minus(&self, other: Self) -> u32 {
15167        self.0 - other.0
15168    }
15169}
15170
15171trait RowRangeExt {
15172    type Row;
15173
15174    fn len(&self) -> usize;
15175
15176    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15177}
15178
15179impl RowRangeExt for Range<MultiBufferRow> {
15180    type Row = MultiBufferRow;
15181
15182    fn len(&self) -> usize {
15183        (self.end.0 - self.start.0) as usize
15184    }
15185
15186    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15187        (self.start.0..self.end.0).map(MultiBufferRow)
15188    }
15189}
15190
15191impl RowRangeExt for Range<DisplayRow> {
15192    type Row = DisplayRow;
15193
15194    fn len(&self) -> usize {
15195        (self.end.0 - self.start.0) as usize
15196    }
15197
15198    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15199        (self.start.0..self.end.0).map(DisplayRow)
15200    }
15201}
15202
15203fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15204    if hunk.diff_base_byte_range.is_empty() {
15205        DiffHunkStatus::Added
15206    } else if hunk.row_range.is_empty() {
15207        DiffHunkStatus::Removed
15208    } else {
15209        DiffHunkStatus::Modified
15210    }
15211}
15212
15213/// If select range has more than one line, we
15214/// just point the cursor to range.start.
15215fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15216    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15217        range
15218    } else {
15219        range.start..range.start
15220    }
15221}
15222
15223pub struct KillRing(ClipboardItem);
15224impl Global for KillRing {}
15225
15226const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);