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(action.lsp_action.title.clone()))
 1694                            })
 1695                            .when_some(action.as_task(), |this, task| {
 1696                                this.on_mouse_down(
 1697                                    MouseButton::Left,
 1698                                    cx.listener(move |editor, _, cx| {
 1699                                        cx.stop_propagation();
 1700                                        if let Some(task) = editor.confirm_code_action(
 1701                                            &ConfirmCodeAction {
 1702                                                item_ix: Some(item_ix),
 1703                                            },
 1704                                            cx,
 1705                                        ) {
 1706                                            task.detach_and_log_err(cx)
 1707                                        }
 1708                                    }),
 1709                                )
 1710                                .child(SharedString::from(task.resolved_label.clone()))
 1711                            })
 1712                    })
 1713                    .collect()
 1714            },
 1715        )
 1716        .elevation_1(cx)
 1717        .p_1()
 1718        .max_h(max_height)
 1719        .occlude()
 1720        .track_scroll(self.scroll_handle.clone())
 1721        .with_width_from_item(
 1722            self.actions
 1723                .iter()
 1724                .enumerate()
 1725                .max_by_key(|(_, action)| match action {
 1726                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1727                    CodeActionsItem::CodeAction { action, .. } => {
 1728                        action.lsp_action.title.chars().count()
 1729                    }
 1730                })
 1731                .map(|(ix, _)| ix),
 1732        )
 1733        .with_sizing_behavior(ListSizingBehavior::Infer)
 1734        .into_any_element();
 1735
 1736        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1737            ContextMenuOrigin::GutterIndicator(row)
 1738        } else {
 1739            ContextMenuOrigin::EditorPoint(cursor_position)
 1740        };
 1741
 1742        (cursor_position, element)
 1743    }
 1744}
 1745
 1746#[derive(Debug)]
 1747struct ActiveDiagnosticGroup {
 1748    primary_range: Range<Anchor>,
 1749    primary_message: String,
 1750    group_id: usize,
 1751    blocks: HashMap<CustomBlockId, Diagnostic>,
 1752    is_valid: bool,
 1753}
 1754
 1755#[derive(Serialize, Deserialize, Clone, Debug)]
 1756pub struct ClipboardSelection {
 1757    pub len: usize,
 1758    pub is_entire_line: bool,
 1759    pub first_line_indent: u32,
 1760}
 1761
 1762#[derive(Debug)]
 1763pub(crate) struct NavigationData {
 1764    cursor_anchor: Anchor,
 1765    cursor_position: Point,
 1766    scroll_anchor: ScrollAnchor,
 1767    scroll_top_row: u32,
 1768}
 1769
 1770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1771pub enum GotoDefinitionKind {
 1772    Symbol,
 1773    Declaration,
 1774    Type,
 1775    Implementation,
 1776}
 1777
 1778#[derive(Debug, Clone)]
 1779enum InlayHintRefreshReason {
 1780    Toggle(bool),
 1781    SettingsChange(InlayHintSettings),
 1782    NewLinesShown,
 1783    BufferEdited(HashSet<Arc<Language>>),
 1784    RefreshRequested,
 1785    ExcerptsRemoved(Vec<ExcerptId>),
 1786}
 1787
 1788impl InlayHintRefreshReason {
 1789    fn description(&self) -> &'static str {
 1790        match self {
 1791            Self::Toggle(_) => "toggle",
 1792            Self::SettingsChange(_) => "settings change",
 1793            Self::NewLinesShown => "new lines shown",
 1794            Self::BufferEdited(_) => "buffer edited",
 1795            Self::RefreshRequested => "refresh requested",
 1796            Self::ExcerptsRemoved(_) => "excerpts removed",
 1797        }
 1798    }
 1799}
 1800
 1801pub(crate) struct FocusedBlock {
 1802    id: BlockId,
 1803    focus_handle: WeakFocusHandle,
 1804}
 1805
 1806#[derive(Clone)]
 1807struct JumpData {
 1808    excerpt_id: ExcerptId,
 1809    position: Point,
 1810    anchor: text::Anchor,
 1811    path: Option<project::ProjectPath>,
 1812    line_offset_from_top: u32,
 1813}
 1814
 1815impl Editor {
 1816    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1817        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1818        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1819        Self::new(
 1820            EditorMode::SingleLine { auto_width: false },
 1821            buffer,
 1822            None,
 1823            false,
 1824            cx,
 1825        )
 1826    }
 1827
 1828    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1829        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1830        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1831        Self::new(EditorMode::Full, buffer, None, false, cx)
 1832    }
 1833
 1834    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1835        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1836        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1837        Self::new(
 1838            EditorMode::SingleLine { auto_width: true },
 1839            buffer,
 1840            None,
 1841            false,
 1842            cx,
 1843        )
 1844    }
 1845
 1846    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1847        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1848        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1849        Self::new(
 1850            EditorMode::AutoHeight { max_lines },
 1851            buffer,
 1852            None,
 1853            false,
 1854            cx,
 1855        )
 1856    }
 1857
 1858    pub fn for_buffer(
 1859        buffer: Model<Buffer>,
 1860        project: Option<Model<Project>>,
 1861        cx: &mut ViewContext<Self>,
 1862    ) -> Self {
 1863        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1864        Self::new(EditorMode::Full, buffer, project, false, cx)
 1865    }
 1866
 1867    pub fn for_multibuffer(
 1868        buffer: Model<MultiBuffer>,
 1869        project: Option<Model<Project>>,
 1870        show_excerpt_controls: bool,
 1871        cx: &mut ViewContext<Self>,
 1872    ) -> Self {
 1873        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1874    }
 1875
 1876    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1877        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1878        let mut clone = Self::new(
 1879            self.mode,
 1880            self.buffer.clone(),
 1881            self.project.clone(),
 1882            show_excerpt_controls,
 1883            cx,
 1884        );
 1885        self.display_map.update(cx, |display_map, cx| {
 1886            let snapshot = display_map.snapshot(cx);
 1887            clone.display_map.update(cx, |display_map, cx| {
 1888                display_map.set_state(&snapshot, cx);
 1889            });
 1890        });
 1891        clone.selections.clone_state(&self.selections);
 1892        clone.scroll_manager.clone_state(&self.scroll_manager);
 1893        clone.searchable = self.searchable;
 1894        clone
 1895    }
 1896
 1897    pub fn new(
 1898        mode: EditorMode,
 1899        buffer: Model<MultiBuffer>,
 1900        project: Option<Model<Project>>,
 1901        show_excerpt_controls: bool,
 1902        cx: &mut ViewContext<Self>,
 1903    ) -> Self {
 1904        let style = cx.text_style();
 1905        let font_size = style.font_size.to_pixels(cx.rem_size());
 1906        let editor = cx.view().downgrade();
 1907        let fold_placeholder = FoldPlaceholder {
 1908            constrain_width: true,
 1909            render: Arc::new(move |fold_id, fold_range, cx| {
 1910                let editor = editor.clone();
 1911                div()
 1912                    .id(fold_id)
 1913                    .bg(cx.theme().colors().ghost_element_background)
 1914                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1915                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1916                    .rounded_sm()
 1917                    .size_full()
 1918                    .cursor_pointer()
 1919                    .child("")
 1920                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1921                    .on_click(move |_, cx| {
 1922                        editor
 1923                            .update(cx, |editor, cx| {
 1924                                editor.unfold_ranges(
 1925                                    &[fold_range.start..fold_range.end],
 1926                                    true,
 1927                                    false,
 1928                                    cx,
 1929                                );
 1930                                cx.stop_propagation();
 1931                            })
 1932                            .ok();
 1933                    })
 1934                    .into_any()
 1935            }),
 1936            merge_adjacent: true,
 1937            ..Default::default()
 1938        };
 1939        let display_map = cx.new_model(|cx| {
 1940            DisplayMap::new(
 1941                buffer.clone(),
 1942                style.font(),
 1943                font_size,
 1944                None,
 1945                show_excerpt_controls,
 1946                FILE_HEADER_HEIGHT,
 1947                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1948                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1949                fold_placeholder,
 1950                cx,
 1951            )
 1952        });
 1953
 1954        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1955
 1956        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1957
 1958        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1959            .then(|| language_settings::SoftWrap::None);
 1960
 1961        let mut project_subscriptions = Vec::new();
 1962        if mode == EditorMode::Full {
 1963            if let Some(project) = project.as_ref() {
 1964                if buffer.read(cx).is_singleton() {
 1965                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1966                        cx.emit(EditorEvent::TitleChanged);
 1967                    }));
 1968                }
 1969                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1970                    if let project::Event::RefreshInlayHints = event {
 1971                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1972                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1973                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1974                            let focus_handle = editor.focus_handle(cx);
 1975                            if focus_handle.is_focused(cx) {
 1976                                let snapshot = buffer.read(cx).snapshot();
 1977                                for (range, snippet) in snippet_edits {
 1978                                    let editor_range =
 1979                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1980                                    editor
 1981                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1982                                        .ok();
 1983                                }
 1984                            }
 1985                        }
 1986                    }
 1987                }));
 1988                if let Some(task_inventory) = project
 1989                    .read(cx)
 1990                    .task_store()
 1991                    .read(cx)
 1992                    .task_inventory()
 1993                    .cloned()
 1994                {
 1995                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1996                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1997                    }));
 1998                }
 1999            }
 2000        }
 2001
 2002        let inlay_hint_settings = inlay_hint_settings(
 2003            selections.newest_anchor().head(),
 2004            &buffer.read(cx).snapshot(cx),
 2005            cx,
 2006        );
 2007        let focus_handle = cx.focus_handle();
 2008        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 2009        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 2010            .detach();
 2011        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 2012            .detach();
 2013        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 2014
 2015        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 2016            Some(false)
 2017        } else {
 2018            None
 2019        };
 2020
 2021        let mut code_action_providers = Vec::new();
 2022        if let Some(project) = project.clone() {
 2023            code_action_providers.push(Arc::new(project) as Arc<_>);
 2024        }
 2025
 2026        let mut this = Self {
 2027            focus_handle,
 2028            show_cursor_when_unfocused: false,
 2029            last_focused_descendant: None,
 2030            buffer: buffer.clone(),
 2031            display_map: display_map.clone(),
 2032            selections,
 2033            scroll_manager: ScrollManager::new(cx),
 2034            columnar_selection_tail: None,
 2035            add_selections_state: None,
 2036            select_next_state: None,
 2037            select_prev_state: None,
 2038            selection_history: Default::default(),
 2039            autoclose_regions: Default::default(),
 2040            snippet_stack: Default::default(),
 2041            select_larger_syntax_node_stack: Vec::new(),
 2042            ime_transaction: Default::default(),
 2043            active_diagnostics: None,
 2044            soft_wrap_mode_override,
 2045            completion_provider: project.clone().map(|project| Box::new(project) as _),
 2046            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 2047            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 2048            project,
 2049            blink_manager: blink_manager.clone(),
 2050            show_local_selections: true,
 2051            mode,
 2052            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2053            show_gutter: mode == EditorMode::Full,
 2054            show_line_numbers: None,
 2055            use_relative_line_numbers: None,
 2056            show_git_diff_gutter: None,
 2057            show_code_actions: None,
 2058            show_runnables: None,
 2059            show_wrap_guides: None,
 2060            show_indent_guides,
 2061            placeholder_text: None,
 2062            highlight_order: 0,
 2063            highlighted_rows: HashMap::default(),
 2064            background_highlights: Default::default(),
 2065            gutter_highlights: TreeMap::default(),
 2066            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2067            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2068            nav_history: None,
 2069            context_menu: RwLock::new(None),
 2070            mouse_context_menu: None,
 2071            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2072            completion_tasks: Default::default(),
 2073            signature_help_state: SignatureHelpState::default(),
 2074            auto_signature_help: None,
 2075            find_all_references_task_sources: Vec::new(),
 2076            next_completion_id: 0,
 2077            next_inlay_id: 0,
 2078            code_action_providers,
 2079            available_code_actions: Default::default(),
 2080            code_actions_task: Default::default(),
 2081            document_highlights_task: Default::default(),
 2082            linked_editing_range_task: Default::default(),
 2083            pending_rename: Default::default(),
 2084            searchable: true,
 2085            cursor_shape: EditorSettings::get_global(cx)
 2086                .cursor_shape
 2087                .unwrap_or_default(),
 2088            current_line_highlight: None,
 2089            autoindent_mode: Some(AutoindentMode::EachLine),
 2090            collapse_matches: false,
 2091            workspace: None,
 2092            input_enabled: true,
 2093            use_modal_editing: mode == EditorMode::Full,
 2094            read_only: false,
 2095            use_autoclose: true,
 2096            use_auto_surround: true,
 2097            auto_replace_emoji_shortcode: false,
 2098            leader_peer_id: None,
 2099            remote_id: None,
 2100            hover_state: Default::default(),
 2101            hovered_link_state: Default::default(),
 2102            inline_completion_provider: None,
 2103            active_inline_completion: None,
 2104            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2105            expanded_hunks: ExpandedHunks::default(),
 2106            gutter_hovered: false,
 2107            pixel_position_of_newest_cursor: None,
 2108            last_bounds: None,
 2109            expect_bounds_change: None,
 2110            gutter_dimensions: GutterDimensions::default(),
 2111            style: None,
 2112            show_cursor_names: false,
 2113            hovered_cursors: Default::default(),
 2114            next_editor_action_id: EditorActionId::default(),
 2115            editor_actions: Rc::default(),
 2116            show_inline_completions_override: None,
 2117            enable_inline_completions: true,
 2118            custom_context_menu: None,
 2119            show_git_blame_gutter: false,
 2120            show_git_blame_inline: false,
 2121            show_selection_menu: None,
 2122            show_git_blame_inline_delay_task: None,
 2123            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2124            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2125                .session
 2126                .restore_unsaved_buffers,
 2127            blame: None,
 2128            blame_subscription: None,
 2129            tasks: Default::default(),
 2130            _subscriptions: vec![
 2131                cx.observe(&buffer, Self::on_buffer_changed),
 2132                cx.subscribe(&buffer, Self::on_buffer_event),
 2133                cx.observe(&display_map, Self::on_display_map_changed),
 2134                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2135                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2136                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2137                cx.observe_window_activation(|editor, cx| {
 2138                    let active = cx.is_window_active();
 2139                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2140                        if active {
 2141                            blink_manager.enable(cx);
 2142                        } else {
 2143                            blink_manager.disable(cx);
 2144                        }
 2145                    });
 2146                }),
 2147            ],
 2148            tasks_update_task: None,
 2149            linked_edit_ranges: Default::default(),
 2150            previous_search_ranges: None,
 2151            breadcrumb_header: None,
 2152            focused_block: None,
 2153            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2154            addons: HashMap::default(),
 2155            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2156            text_style_refinement: None,
 2157        };
 2158        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2159        this._subscriptions.extend(project_subscriptions);
 2160
 2161        this.end_selection(cx);
 2162        this.scroll_manager.show_scrollbar(cx);
 2163
 2164        if mode == EditorMode::Full {
 2165            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2166            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2167
 2168            if this.git_blame_inline_enabled {
 2169                this.git_blame_inline_enabled = true;
 2170                this.start_git_blame_inline(false, cx);
 2171            }
 2172        }
 2173
 2174        this.report_editor_event("open", None, cx);
 2175        this
 2176    }
 2177
 2178    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2179        self.mouse_context_menu
 2180            .as_ref()
 2181            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2182    }
 2183
 2184    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2185        let mut key_context = KeyContext::new_with_defaults();
 2186        key_context.add("Editor");
 2187        let mode = match self.mode {
 2188            EditorMode::SingleLine { .. } => "single_line",
 2189            EditorMode::AutoHeight { .. } => "auto_height",
 2190            EditorMode::Full => "full",
 2191        };
 2192
 2193        if EditorSettings::jupyter_enabled(cx) {
 2194            key_context.add("jupyter");
 2195        }
 2196
 2197        key_context.set("mode", mode);
 2198        if self.pending_rename.is_some() {
 2199            key_context.add("renaming");
 2200        }
 2201        if self.context_menu_visible() {
 2202            match self.context_menu.read().as_ref() {
 2203                Some(ContextMenu::Completions(_)) => {
 2204                    key_context.add("menu");
 2205                    key_context.add("showing_completions")
 2206                }
 2207                Some(ContextMenu::CodeActions(_)) => {
 2208                    key_context.add("menu");
 2209                    key_context.add("showing_code_actions")
 2210                }
 2211                None => {}
 2212            }
 2213        }
 2214
 2215        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2216        if !self.focus_handle(cx).contains_focused(cx)
 2217            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2218        {
 2219            for addon in self.addons.values() {
 2220                addon.extend_key_context(&mut key_context, cx)
 2221            }
 2222        }
 2223
 2224        if let Some(extension) = self
 2225            .buffer
 2226            .read(cx)
 2227            .as_singleton()
 2228            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2229        {
 2230            key_context.set("extension", extension.to_string());
 2231        }
 2232
 2233        if self.has_active_inline_completion(cx) {
 2234            key_context.add("copilot_suggestion");
 2235            key_context.add("inline_completion");
 2236        }
 2237
 2238        key_context
 2239    }
 2240
 2241    pub fn new_file(
 2242        workspace: &mut Workspace,
 2243        _: &workspace::NewFile,
 2244        cx: &mut ViewContext<Workspace>,
 2245    ) {
 2246        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2247            "Failed to create buffer",
 2248            cx,
 2249            |e, _| match e.error_code() {
 2250                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2251                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2252                e.error_tag("required").unwrap_or("the latest version")
 2253            )),
 2254                _ => None,
 2255            },
 2256        );
 2257    }
 2258
 2259    pub fn new_in_workspace(
 2260        workspace: &mut Workspace,
 2261        cx: &mut ViewContext<Workspace>,
 2262    ) -> Task<Result<View<Editor>>> {
 2263        let project = workspace.project().clone();
 2264        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2265
 2266        cx.spawn(|workspace, mut cx| async move {
 2267            let buffer = create.await?;
 2268            workspace.update(&mut cx, |workspace, cx| {
 2269                let editor =
 2270                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2271                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2272                editor
 2273            })
 2274        })
 2275    }
 2276
 2277    fn new_file_vertical(
 2278        workspace: &mut Workspace,
 2279        _: &workspace::NewFileSplitVertical,
 2280        cx: &mut ViewContext<Workspace>,
 2281    ) {
 2282        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2283    }
 2284
 2285    fn new_file_horizontal(
 2286        workspace: &mut Workspace,
 2287        _: &workspace::NewFileSplitHorizontal,
 2288        cx: &mut ViewContext<Workspace>,
 2289    ) {
 2290        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2291    }
 2292
 2293    fn new_file_in_direction(
 2294        workspace: &mut Workspace,
 2295        direction: SplitDirection,
 2296        cx: &mut ViewContext<Workspace>,
 2297    ) {
 2298        let project = workspace.project().clone();
 2299        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2300
 2301        cx.spawn(|workspace, mut cx| async move {
 2302            let buffer = create.await?;
 2303            workspace.update(&mut cx, move |workspace, cx| {
 2304                workspace.split_item(
 2305                    direction,
 2306                    Box::new(
 2307                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2308                    ),
 2309                    cx,
 2310                )
 2311            })?;
 2312            anyhow::Ok(())
 2313        })
 2314        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2315            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2316                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2317                e.error_tag("required").unwrap_or("the latest version")
 2318            )),
 2319            _ => None,
 2320        });
 2321    }
 2322
 2323    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2324        self.leader_peer_id
 2325    }
 2326
 2327    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2328        &self.buffer
 2329    }
 2330
 2331    pub fn workspace(&self) -> Option<View<Workspace>> {
 2332        self.workspace.as_ref()?.0.upgrade()
 2333    }
 2334
 2335    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2336        self.buffer().read(cx).title(cx)
 2337    }
 2338
 2339    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2340        let git_blame_gutter_max_author_length = self
 2341            .render_git_blame_gutter(cx)
 2342            .then(|| {
 2343                if let Some(blame) = self.blame.as_ref() {
 2344                    let max_author_length =
 2345                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2346                    Some(max_author_length)
 2347                } else {
 2348                    None
 2349                }
 2350            })
 2351            .flatten();
 2352
 2353        EditorSnapshot {
 2354            mode: self.mode,
 2355            show_gutter: self.show_gutter,
 2356            show_line_numbers: self.show_line_numbers,
 2357            show_git_diff_gutter: self.show_git_diff_gutter,
 2358            show_code_actions: self.show_code_actions,
 2359            show_runnables: self.show_runnables,
 2360            git_blame_gutter_max_author_length,
 2361            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2362            scroll_anchor: self.scroll_manager.anchor(),
 2363            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2364            placeholder_text: self.placeholder_text.clone(),
 2365            is_focused: self.focus_handle.is_focused(cx),
 2366            current_line_highlight: self
 2367                .current_line_highlight
 2368                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2369            gutter_hovered: self.gutter_hovered,
 2370        }
 2371    }
 2372
 2373    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2374        self.buffer.read(cx).language_at(point, cx)
 2375    }
 2376
 2377    pub fn file_at<T: ToOffset>(
 2378        &self,
 2379        point: T,
 2380        cx: &AppContext,
 2381    ) -> Option<Arc<dyn language::File>> {
 2382        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2383    }
 2384
 2385    pub fn active_excerpt(
 2386        &self,
 2387        cx: &AppContext,
 2388    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2389        self.buffer
 2390            .read(cx)
 2391            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2392    }
 2393
 2394    pub fn mode(&self) -> EditorMode {
 2395        self.mode
 2396    }
 2397
 2398    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2399        self.collaboration_hub.as_deref()
 2400    }
 2401
 2402    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2403        self.collaboration_hub = Some(hub);
 2404    }
 2405
 2406    pub fn set_custom_context_menu(
 2407        &mut self,
 2408        f: impl 'static
 2409            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2410    ) {
 2411        self.custom_context_menu = Some(Box::new(f))
 2412    }
 2413
 2414    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2415        self.completion_provider = provider;
 2416    }
 2417
 2418    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2419        self.semantics_provider.clone()
 2420    }
 2421
 2422    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2423        self.semantics_provider = provider;
 2424    }
 2425
 2426    pub fn set_inline_completion_provider<T>(
 2427        &mut self,
 2428        provider: Option<Model<T>>,
 2429        cx: &mut ViewContext<Self>,
 2430    ) where
 2431        T: InlineCompletionProvider,
 2432    {
 2433        self.inline_completion_provider =
 2434            provider.map(|provider| RegisteredInlineCompletionProvider {
 2435                _subscription: cx.observe(&provider, |this, _, cx| {
 2436                    if this.focus_handle.is_focused(cx) {
 2437                        this.update_visible_inline_completion(cx);
 2438                    }
 2439                }),
 2440                provider: Arc::new(provider),
 2441            });
 2442        self.refresh_inline_completion(false, false, cx);
 2443    }
 2444
 2445    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2446        self.placeholder_text.as_deref()
 2447    }
 2448
 2449    pub fn set_placeholder_text(
 2450        &mut self,
 2451        placeholder_text: impl Into<Arc<str>>,
 2452        cx: &mut ViewContext<Self>,
 2453    ) {
 2454        let placeholder_text = Some(placeholder_text.into());
 2455        if self.placeholder_text != placeholder_text {
 2456            self.placeholder_text = placeholder_text;
 2457            cx.notify();
 2458        }
 2459    }
 2460
 2461    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2462        self.cursor_shape = cursor_shape;
 2463
 2464        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2465        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2466
 2467        cx.notify();
 2468    }
 2469
 2470    pub fn set_current_line_highlight(
 2471        &mut self,
 2472        current_line_highlight: Option<CurrentLineHighlight>,
 2473    ) {
 2474        self.current_line_highlight = current_line_highlight;
 2475    }
 2476
 2477    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2478        self.collapse_matches = collapse_matches;
 2479    }
 2480
 2481    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2482        if self.collapse_matches {
 2483            return range.start..range.start;
 2484        }
 2485        range.clone()
 2486    }
 2487
 2488    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2489        if self.display_map.read(cx).clip_at_line_ends != clip {
 2490            self.display_map
 2491                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2492        }
 2493    }
 2494
 2495    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2496        self.input_enabled = input_enabled;
 2497    }
 2498
 2499    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2500        self.enable_inline_completions = enabled;
 2501    }
 2502
 2503    pub fn set_autoindent(&mut self, autoindent: bool) {
 2504        if autoindent {
 2505            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2506        } else {
 2507            self.autoindent_mode = None;
 2508        }
 2509    }
 2510
 2511    pub fn read_only(&self, cx: &AppContext) -> bool {
 2512        self.read_only || self.buffer.read(cx).read_only()
 2513    }
 2514
 2515    pub fn set_read_only(&mut self, read_only: bool) {
 2516        self.read_only = read_only;
 2517    }
 2518
 2519    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2520        self.use_autoclose = autoclose;
 2521    }
 2522
 2523    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2524        self.use_auto_surround = auto_surround;
 2525    }
 2526
 2527    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2528        self.auto_replace_emoji_shortcode = auto_replace;
 2529    }
 2530
 2531    pub fn toggle_inline_completions(
 2532        &mut self,
 2533        _: &ToggleInlineCompletions,
 2534        cx: &mut ViewContext<Self>,
 2535    ) {
 2536        if self.show_inline_completions_override.is_some() {
 2537            self.set_show_inline_completions(None, cx);
 2538        } else {
 2539            let cursor = self.selections.newest_anchor().head();
 2540            if let Some((buffer, cursor_buffer_position)) =
 2541                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2542            {
 2543                let show_inline_completions =
 2544                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2545                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2546            }
 2547        }
 2548    }
 2549
 2550    pub fn set_show_inline_completions(
 2551        &mut self,
 2552        show_inline_completions: Option<bool>,
 2553        cx: &mut ViewContext<Self>,
 2554    ) {
 2555        self.show_inline_completions_override = show_inline_completions;
 2556        self.refresh_inline_completion(false, true, cx);
 2557    }
 2558
 2559    fn should_show_inline_completions(
 2560        &self,
 2561        buffer: &Model<Buffer>,
 2562        buffer_position: language::Anchor,
 2563        cx: &AppContext,
 2564    ) -> bool {
 2565        if !self.snippet_stack.is_empty() {
 2566            return false;
 2567        }
 2568
 2569        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2570            return false;
 2571        }
 2572
 2573        if let Some(provider) = self.inline_completion_provider() {
 2574            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2575                show_inline_completions
 2576            } else {
 2577                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2578            }
 2579        } else {
 2580            false
 2581        }
 2582    }
 2583
 2584    fn inline_completions_disabled_in_scope(
 2585        &self,
 2586        buffer: &Model<Buffer>,
 2587        buffer_position: language::Anchor,
 2588        cx: &AppContext,
 2589    ) -> bool {
 2590        let snapshot = buffer.read(cx).snapshot();
 2591        let settings = snapshot.settings_at(buffer_position, cx);
 2592
 2593        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2594            return false;
 2595        };
 2596
 2597        scope.override_name().map_or(false, |scope_name| {
 2598            settings
 2599                .inline_completions_disabled_in
 2600                .iter()
 2601                .any(|s| s == scope_name)
 2602        })
 2603    }
 2604
 2605    pub fn set_use_modal_editing(&mut self, to: bool) {
 2606        self.use_modal_editing = to;
 2607    }
 2608
 2609    pub fn use_modal_editing(&self) -> bool {
 2610        self.use_modal_editing
 2611    }
 2612
 2613    fn selections_did_change(
 2614        &mut self,
 2615        local: bool,
 2616        old_cursor_position: &Anchor,
 2617        show_completions: bool,
 2618        cx: &mut ViewContext<Self>,
 2619    ) {
 2620        cx.invalidate_character_coordinates();
 2621
 2622        // Copy selections to primary selection buffer
 2623        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2624        if local {
 2625            let selections = self.selections.all::<usize>(cx);
 2626            let buffer_handle = self.buffer.read(cx).read(cx);
 2627
 2628            let mut text = String::new();
 2629            for (index, selection) in selections.iter().enumerate() {
 2630                let text_for_selection = buffer_handle
 2631                    .text_for_range(selection.start..selection.end)
 2632                    .collect::<String>();
 2633
 2634                text.push_str(&text_for_selection);
 2635                if index != selections.len() - 1 {
 2636                    text.push('\n');
 2637                }
 2638            }
 2639
 2640            if !text.is_empty() {
 2641                cx.write_to_primary(ClipboardItem::new_string(text));
 2642            }
 2643        }
 2644
 2645        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2646            self.buffer.update(cx, |buffer, cx| {
 2647                buffer.set_active_selections(
 2648                    &self.selections.disjoint_anchors(),
 2649                    self.selections.line_mode,
 2650                    self.cursor_shape,
 2651                    cx,
 2652                )
 2653            });
 2654        }
 2655        let display_map = self
 2656            .display_map
 2657            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2658        let buffer = &display_map.buffer_snapshot;
 2659        self.add_selections_state = None;
 2660        self.select_next_state = None;
 2661        self.select_prev_state = None;
 2662        self.select_larger_syntax_node_stack.clear();
 2663        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2664        self.snippet_stack
 2665            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2666        self.take_rename(false, cx);
 2667
 2668        let new_cursor_position = self.selections.newest_anchor().head();
 2669
 2670        self.push_to_nav_history(
 2671            *old_cursor_position,
 2672            Some(new_cursor_position.to_point(buffer)),
 2673            cx,
 2674        );
 2675
 2676        if local {
 2677            let new_cursor_position = self.selections.newest_anchor().head();
 2678            let mut context_menu = self.context_menu.write();
 2679            let completion_menu = match context_menu.as_ref() {
 2680                Some(ContextMenu::Completions(menu)) => Some(menu),
 2681
 2682                _ => {
 2683                    *context_menu = None;
 2684                    None
 2685                }
 2686            };
 2687
 2688            if let Some(completion_menu) = completion_menu {
 2689                let cursor_position = new_cursor_position.to_offset(buffer);
 2690                let (word_range, kind) =
 2691                    buffer.surrounding_word(completion_menu.initial_position, true);
 2692                if kind == Some(CharKind::Word)
 2693                    && word_range.to_inclusive().contains(&cursor_position)
 2694                {
 2695                    let mut completion_menu = completion_menu.clone();
 2696                    drop(context_menu);
 2697
 2698                    let query = Self::completion_query(buffer, cursor_position);
 2699                    cx.spawn(move |this, mut cx| async move {
 2700                        completion_menu
 2701                            .filter(query.as_deref(), cx.background_executor().clone())
 2702                            .await;
 2703
 2704                        this.update(&mut cx, |this, cx| {
 2705                            let mut context_menu = this.context_menu.write();
 2706                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2707                                return;
 2708                            };
 2709
 2710                            if menu.id > completion_menu.id {
 2711                                return;
 2712                            }
 2713
 2714                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2715                            drop(context_menu);
 2716                            cx.notify();
 2717                        })
 2718                    })
 2719                    .detach();
 2720
 2721                    if show_completions {
 2722                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2723                    }
 2724                } else {
 2725                    drop(context_menu);
 2726                    self.hide_context_menu(cx);
 2727                }
 2728            } else {
 2729                drop(context_menu);
 2730            }
 2731
 2732            hide_hover(self, cx);
 2733
 2734            if old_cursor_position.to_display_point(&display_map).row()
 2735                != new_cursor_position.to_display_point(&display_map).row()
 2736            {
 2737                self.available_code_actions.take();
 2738            }
 2739            self.refresh_code_actions(cx);
 2740            self.refresh_document_highlights(cx);
 2741            refresh_matching_bracket_highlights(self, cx);
 2742            self.discard_inline_completion(false, cx);
 2743            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2744            if self.git_blame_inline_enabled {
 2745                self.start_inline_blame_timer(cx);
 2746            }
 2747        }
 2748
 2749        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2750        cx.emit(EditorEvent::SelectionsChanged { local });
 2751
 2752        if self.selections.disjoint_anchors().len() == 1 {
 2753            cx.emit(SearchEvent::ActiveMatchChanged)
 2754        }
 2755        cx.notify();
 2756    }
 2757
 2758    pub fn change_selections<R>(
 2759        &mut self,
 2760        autoscroll: Option<Autoscroll>,
 2761        cx: &mut ViewContext<Self>,
 2762        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2763    ) -> R {
 2764        self.change_selections_inner(autoscroll, true, cx, change)
 2765    }
 2766
 2767    pub fn change_selections_inner<R>(
 2768        &mut self,
 2769        autoscroll: Option<Autoscroll>,
 2770        request_completions: bool,
 2771        cx: &mut ViewContext<Self>,
 2772        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2773    ) -> R {
 2774        let old_cursor_position = self.selections.newest_anchor().head();
 2775        self.push_to_selection_history();
 2776
 2777        let (changed, result) = self.selections.change_with(cx, change);
 2778
 2779        if changed {
 2780            if let Some(autoscroll) = autoscroll {
 2781                self.request_autoscroll(autoscroll, cx);
 2782            }
 2783            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2784
 2785            if self.should_open_signature_help_automatically(
 2786                &old_cursor_position,
 2787                self.signature_help_state.backspace_pressed(),
 2788                cx,
 2789            ) {
 2790                self.show_signature_help(&ShowSignatureHelp, cx);
 2791            }
 2792            self.signature_help_state.set_backspace_pressed(false);
 2793        }
 2794
 2795        result
 2796    }
 2797
 2798    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2799    where
 2800        I: IntoIterator<Item = (Range<S>, T)>,
 2801        S: ToOffset,
 2802        T: Into<Arc<str>>,
 2803    {
 2804        if self.read_only(cx) {
 2805            return;
 2806        }
 2807
 2808        self.buffer
 2809            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2810    }
 2811
 2812    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2813    where
 2814        I: IntoIterator<Item = (Range<S>, T)>,
 2815        S: ToOffset,
 2816        T: Into<Arc<str>>,
 2817    {
 2818        if self.read_only(cx) {
 2819            return;
 2820        }
 2821
 2822        self.buffer.update(cx, |buffer, cx| {
 2823            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2824        });
 2825    }
 2826
 2827    pub fn edit_with_block_indent<I, S, T>(
 2828        &mut self,
 2829        edits: I,
 2830        original_indent_columns: Vec<u32>,
 2831        cx: &mut ViewContext<Self>,
 2832    ) where
 2833        I: IntoIterator<Item = (Range<S>, T)>,
 2834        S: ToOffset,
 2835        T: Into<Arc<str>>,
 2836    {
 2837        if self.read_only(cx) {
 2838            return;
 2839        }
 2840
 2841        self.buffer.update(cx, |buffer, cx| {
 2842            buffer.edit(
 2843                edits,
 2844                Some(AutoindentMode::Block {
 2845                    original_indent_columns,
 2846                }),
 2847                cx,
 2848            )
 2849        });
 2850    }
 2851
 2852    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2853        self.hide_context_menu(cx);
 2854
 2855        match phase {
 2856            SelectPhase::Begin {
 2857                position,
 2858                add,
 2859                click_count,
 2860            } => self.begin_selection(position, add, click_count, cx),
 2861            SelectPhase::BeginColumnar {
 2862                position,
 2863                goal_column,
 2864                reset,
 2865            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2866            SelectPhase::Extend {
 2867                position,
 2868                click_count,
 2869            } => self.extend_selection(position, click_count, cx),
 2870            SelectPhase::Update {
 2871                position,
 2872                goal_column,
 2873                scroll_delta,
 2874            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2875            SelectPhase::End => self.end_selection(cx),
 2876        }
 2877    }
 2878
 2879    fn extend_selection(
 2880        &mut self,
 2881        position: DisplayPoint,
 2882        click_count: usize,
 2883        cx: &mut ViewContext<Self>,
 2884    ) {
 2885        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2886        let tail = self.selections.newest::<usize>(cx).tail();
 2887        self.begin_selection(position, false, click_count, cx);
 2888
 2889        let position = position.to_offset(&display_map, Bias::Left);
 2890        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2891
 2892        let mut pending_selection = self
 2893            .selections
 2894            .pending_anchor()
 2895            .expect("extend_selection not called with pending selection");
 2896        if position >= tail {
 2897            pending_selection.start = tail_anchor;
 2898        } else {
 2899            pending_selection.end = tail_anchor;
 2900            pending_selection.reversed = true;
 2901        }
 2902
 2903        let mut pending_mode = self.selections.pending_mode().unwrap();
 2904        match &mut pending_mode {
 2905            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2906            _ => {}
 2907        }
 2908
 2909        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2910            s.set_pending(pending_selection, pending_mode)
 2911        });
 2912    }
 2913
 2914    fn begin_selection(
 2915        &mut self,
 2916        position: DisplayPoint,
 2917        add: bool,
 2918        click_count: usize,
 2919        cx: &mut ViewContext<Self>,
 2920    ) {
 2921        if !self.focus_handle.is_focused(cx) {
 2922            self.last_focused_descendant = None;
 2923            cx.focus(&self.focus_handle);
 2924        }
 2925
 2926        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2927        let buffer = &display_map.buffer_snapshot;
 2928        let newest_selection = self.selections.newest_anchor().clone();
 2929        let position = display_map.clip_point(position, Bias::Left);
 2930
 2931        let start;
 2932        let end;
 2933        let mode;
 2934        let mut auto_scroll;
 2935        match click_count {
 2936            1 => {
 2937                start = buffer.anchor_before(position.to_point(&display_map));
 2938                end = start;
 2939                mode = SelectMode::Character;
 2940                auto_scroll = true;
 2941            }
 2942            2 => {
 2943                let range = movement::surrounding_word(&display_map, position);
 2944                start = buffer.anchor_before(range.start.to_point(&display_map));
 2945                end = buffer.anchor_before(range.end.to_point(&display_map));
 2946                mode = SelectMode::Word(start..end);
 2947                auto_scroll = true;
 2948            }
 2949            3 => {
 2950                let position = display_map
 2951                    .clip_point(position, Bias::Left)
 2952                    .to_point(&display_map);
 2953                let line_start = display_map.prev_line_boundary(position).0;
 2954                let next_line_start = buffer.clip_point(
 2955                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2956                    Bias::Left,
 2957                );
 2958                start = buffer.anchor_before(line_start);
 2959                end = buffer.anchor_before(next_line_start);
 2960                mode = SelectMode::Line(start..end);
 2961                auto_scroll = true;
 2962            }
 2963            _ => {
 2964                start = buffer.anchor_before(0);
 2965                end = buffer.anchor_before(buffer.len());
 2966                mode = SelectMode::All;
 2967                auto_scroll = false;
 2968            }
 2969        }
 2970        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2971
 2972        let point_to_delete: Option<usize> = {
 2973            let selected_points: Vec<Selection<Point>> =
 2974                self.selections.disjoint_in_range(start..end, cx);
 2975
 2976            if !add || click_count > 1 {
 2977                None
 2978            } else if !selected_points.is_empty() {
 2979                Some(selected_points[0].id)
 2980            } else {
 2981                let clicked_point_already_selected =
 2982                    self.selections.disjoint.iter().find(|selection| {
 2983                        selection.start.to_point(buffer) == start.to_point(buffer)
 2984                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2985                    });
 2986
 2987                clicked_point_already_selected.map(|selection| selection.id)
 2988            }
 2989        };
 2990
 2991        let selections_count = self.selections.count();
 2992
 2993        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2994            if let Some(point_to_delete) = point_to_delete {
 2995                s.delete(point_to_delete);
 2996
 2997                if selections_count == 1 {
 2998                    s.set_pending_anchor_range(start..end, mode);
 2999                }
 3000            } else {
 3001                if !add {
 3002                    s.clear_disjoint();
 3003                } else if click_count > 1 {
 3004                    s.delete(newest_selection.id)
 3005                }
 3006
 3007                s.set_pending_anchor_range(start..end, mode);
 3008            }
 3009        });
 3010    }
 3011
 3012    fn begin_columnar_selection(
 3013        &mut self,
 3014        position: DisplayPoint,
 3015        goal_column: u32,
 3016        reset: bool,
 3017        cx: &mut ViewContext<Self>,
 3018    ) {
 3019        if !self.focus_handle.is_focused(cx) {
 3020            self.last_focused_descendant = None;
 3021            cx.focus(&self.focus_handle);
 3022        }
 3023
 3024        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3025
 3026        if reset {
 3027            let pointer_position = display_map
 3028                .buffer_snapshot
 3029                .anchor_before(position.to_point(&display_map));
 3030
 3031            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 3032                s.clear_disjoint();
 3033                s.set_pending_anchor_range(
 3034                    pointer_position..pointer_position,
 3035                    SelectMode::Character,
 3036                );
 3037            });
 3038        }
 3039
 3040        let tail = self.selections.newest::<Point>(cx).tail();
 3041        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3042
 3043        if !reset {
 3044            self.select_columns(
 3045                tail.to_display_point(&display_map),
 3046                position,
 3047                goal_column,
 3048                &display_map,
 3049                cx,
 3050            );
 3051        }
 3052    }
 3053
 3054    fn update_selection(
 3055        &mut self,
 3056        position: DisplayPoint,
 3057        goal_column: u32,
 3058        scroll_delta: gpui::Point<f32>,
 3059        cx: &mut ViewContext<Self>,
 3060    ) {
 3061        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3062
 3063        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3064            let tail = tail.to_display_point(&display_map);
 3065            self.select_columns(tail, position, goal_column, &display_map, cx);
 3066        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3067            let buffer = self.buffer.read(cx).snapshot(cx);
 3068            let head;
 3069            let tail;
 3070            let mode = self.selections.pending_mode().unwrap();
 3071            match &mode {
 3072                SelectMode::Character => {
 3073                    head = position.to_point(&display_map);
 3074                    tail = pending.tail().to_point(&buffer);
 3075                }
 3076                SelectMode::Word(original_range) => {
 3077                    let original_display_range = original_range.start.to_display_point(&display_map)
 3078                        ..original_range.end.to_display_point(&display_map);
 3079                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3080                        ..original_display_range.end.to_point(&display_map);
 3081                    if movement::is_inside_word(&display_map, position)
 3082                        || original_display_range.contains(&position)
 3083                    {
 3084                        let word_range = movement::surrounding_word(&display_map, position);
 3085                        if word_range.start < original_display_range.start {
 3086                            head = word_range.start.to_point(&display_map);
 3087                        } else {
 3088                            head = word_range.end.to_point(&display_map);
 3089                        }
 3090                    } else {
 3091                        head = position.to_point(&display_map);
 3092                    }
 3093
 3094                    if head <= original_buffer_range.start {
 3095                        tail = original_buffer_range.end;
 3096                    } else {
 3097                        tail = original_buffer_range.start;
 3098                    }
 3099                }
 3100                SelectMode::Line(original_range) => {
 3101                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3102
 3103                    let position = display_map
 3104                        .clip_point(position, Bias::Left)
 3105                        .to_point(&display_map);
 3106                    let line_start = display_map.prev_line_boundary(position).0;
 3107                    let next_line_start = buffer.clip_point(
 3108                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3109                        Bias::Left,
 3110                    );
 3111
 3112                    if line_start < original_range.start {
 3113                        head = line_start
 3114                    } else {
 3115                        head = next_line_start
 3116                    }
 3117
 3118                    if head <= original_range.start {
 3119                        tail = original_range.end;
 3120                    } else {
 3121                        tail = original_range.start;
 3122                    }
 3123                }
 3124                SelectMode::All => {
 3125                    return;
 3126                }
 3127            };
 3128
 3129            if head < tail {
 3130                pending.start = buffer.anchor_before(head);
 3131                pending.end = buffer.anchor_before(tail);
 3132                pending.reversed = true;
 3133            } else {
 3134                pending.start = buffer.anchor_before(tail);
 3135                pending.end = buffer.anchor_before(head);
 3136                pending.reversed = false;
 3137            }
 3138
 3139            self.change_selections(None, cx, |s| {
 3140                s.set_pending(pending, mode);
 3141            });
 3142        } else {
 3143            log::error!("update_selection dispatched with no pending selection");
 3144            return;
 3145        }
 3146
 3147        self.apply_scroll_delta(scroll_delta, cx);
 3148        cx.notify();
 3149    }
 3150
 3151    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3152        self.columnar_selection_tail.take();
 3153        if self.selections.pending_anchor().is_some() {
 3154            let selections = self.selections.all::<usize>(cx);
 3155            self.change_selections(None, cx, |s| {
 3156                s.select(selections);
 3157                s.clear_pending();
 3158            });
 3159        }
 3160    }
 3161
 3162    fn select_columns(
 3163        &mut self,
 3164        tail: DisplayPoint,
 3165        head: DisplayPoint,
 3166        goal_column: u32,
 3167        display_map: &DisplaySnapshot,
 3168        cx: &mut ViewContext<Self>,
 3169    ) {
 3170        let start_row = cmp::min(tail.row(), head.row());
 3171        let end_row = cmp::max(tail.row(), head.row());
 3172        let start_column = cmp::min(tail.column(), goal_column);
 3173        let end_column = cmp::max(tail.column(), goal_column);
 3174        let reversed = start_column < tail.column();
 3175
 3176        let selection_ranges = (start_row.0..=end_row.0)
 3177            .map(DisplayRow)
 3178            .filter_map(|row| {
 3179                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3180                    let start = display_map
 3181                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3182                        .to_point(display_map);
 3183                    let end = display_map
 3184                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3185                        .to_point(display_map);
 3186                    if reversed {
 3187                        Some(end..start)
 3188                    } else {
 3189                        Some(start..end)
 3190                    }
 3191                } else {
 3192                    None
 3193                }
 3194            })
 3195            .collect::<Vec<_>>();
 3196
 3197        self.change_selections(None, cx, |s| {
 3198            s.select_ranges(selection_ranges);
 3199        });
 3200        cx.notify();
 3201    }
 3202
 3203    pub fn has_pending_nonempty_selection(&self) -> bool {
 3204        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3205            Some(Selection { start, end, .. }) => start != end,
 3206            None => false,
 3207        };
 3208
 3209        pending_nonempty_selection
 3210            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3211    }
 3212
 3213    pub fn has_pending_selection(&self) -> bool {
 3214        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3215    }
 3216
 3217    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3218        if self.clear_expanded_diff_hunks(cx) {
 3219            cx.notify();
 3220            return;
 3221        }
 3222        if self.dismiss_menus_and_popups(true, cx) {
 3223            return;
 3224        }
 3225
 3226        if self.mode == EditorMode::Full
 3227            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3228        {
 3229            return;
 3230        }
 3231
 3232        cx.propagate();
 3233    }
 3234
 3235    pub fn dismiss_menus_and_popups(
 3236        &mut self,
 3237        should_report_inline_completion_event: bool,
 3238        cx: &mut ViewContext<Self>,
 3239    ) -> bool {
 3240        if self.take_rename(false, cx).is_some() {
 3241            return true;
 3242        }
 3243
 3244        if hide_hover(self, cx) {
 3245            return true;
 3246        }
 3247
 3248        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3249            return true;
 3250        }
 3251
 3252        if self.hide_context_menu(cx).is_some() {
 3253            return true;
 3254        }
 3255
 3256        if self.mouse_context_menu.take().is_some() {
 3257            return true;
 3258        }
 3259
 3260        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3261            return true;
 3262        }
 3263
 3264        if self.snippet_stack.pop().is_some() {
 3265            return true;
 3266        }
 3267
 3268        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3269            self.dismiss_diagnostics(cx);
 3270            return true;
 3271        }
 3272
 3273        false
 3274    }
 3275
 3276    fn linked_editing_ranges_for(
 3277        &self,
 3278        selection: Range<text::Anchor>,
 3279        cx: &AppContext,
 3280    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3281        if self.linked_edit_ranges.is_empty() {
 3282            return None;
 3283        }
 3284        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3285            selection.end.buffer_id.and_then(|end_buffer_id| {
 3286                if selection.start.buffer_id != Some(end_buffer_id) {
 3287                    return None;
 3288                }
 3289                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3290                let snapshot = buffer.read(cx).snapshot();
 3291                self.linked_edit_ranges
 3292                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3293                    .map(|ranges| (ranges, snapshot, buffer))
 3294            })?;
 3295        use text::ToOffset as TO;
 3296        // find offset from the start of current range to current cursor position
 3297        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3298
 3299        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3300        let start_difference = start_offset - start_byte_offset;
 3301        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3302        let end_difference = end_offset - start_byte_offset;
 3303        // Current range has associated linked ranges.
 3304        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3305        for range in linked_ranges.iter() {
 3306            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3307            let end_offset = start_offset + end_difference;
 3308            let start_offset = start_offset + start_difference;
 3309            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3310                continue;
 3311            }
 3312            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3313                if s.start.buffer_id != selection.start.buffer_id
 3314                    || s.end.buffer_id != selection.end.buffer_id
 3315                {
 3316                    return false;
 3317                }
 3318                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3319                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3320            }) {
 3321                continue;
 3322            }
 3323            let start = buffer_snapshot.anchor_after(start_offset);
 3324            let end = buffer_snapshot.anchor_after(end_offset);
 3325            linked_edits
 3326                .entry(buffer.clone())
 3327                .or_default()
 3328                .push(start..end);
 3329        }
 3330        Some(linked_edits)
 3331    }
 3332
 3333    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3334        let text: Arc<str> = text.into();
 3335
 3336        if self.read_only(cx) {
 3337            return;
 3338        }
 3339
 3340        let selections = self.selections.all_adjusted(cx);
 3341        let mut bracket_inserted = false;
 3342        let mut edits = Vec::new();
 3343        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3344        let mut new_selections = Vec::with_capacity(selections.len());
 3345        let mut new_autoclose_regions = Vec::new();
 3346        let snapshot = self.buffer.read(cx).read(cx);
 3347
 3348        for (selection, autoclose_region) in
 3349            self.selections_with_autoclose_regions(selections, &snapshot)
 3350        {
 3351            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3352                // Determine if the inserted text matches the opening or closing
 3353                // bracket of any of this language's bracket pairs.
 3354                let mut bracket_pair = None;
 3355                let mut is_bracket_pair_start = false;
 3356                let mut is_bracket_pair_end = false;
 3357                if !text.is_empty() {
 3358                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3359                    //  and they are removing the character that triggered IME popup.
 3360                    for (pair, enabled) in scope.brackets() {
 3361                        if !pair.close && !pair.surround {
 3362                            continue;
 3363                        }
 3364
 3365                        if enabled && pair.start.ends_with(text.as_ref()) {
 3366                            let prefix_len = pair.start.len() - text.len();
 3367                            let preceding_text_matches_prefix = prefix_len == 0
 3368                                || (selection.start.column >= (prefix_len as u32)
 3369                                    && snapshot.contains_str_at(
 3370                                        Point::new(
 3371                                            selection.start.row,
 3372                                            selection.start.column - (prefix_len as u32),
 3373                                        ),
 3374                                        &pair.start[..prefix_len],
 3375                                    ));
 3376                            if preceding_text_matches_prefix {
 3377                                bracket_pair = Some(pair.clone());
 3378                                is_bracket_pair_start = true;
 3379                                break;
 3380                            }
 3381                        }
 3382                        if pair.end.as_str() == text.as_ref() {
 3383                            bracket_pair = Some(pair.clone());
 3384                            is_bracket_pair_end = true;
 3385                            break;
 3386                        }
 3387                    }
 3388                }
 3389
 3390                if let Some(bracket_pair) = bracket_pair {
 3391                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3392                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3393                    let auto_surround =
 3394                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3395                    if selection.is_empty() {
 3396                        if is_bracket_pair_start {
 3397                            // If the inserted text is a suffix of an opening bracket and the
 3398                            // selection is preceded by the rest of the opening bracket, then
 3399                            // insert the closing bracket.
 3400                            let following_text_allows_autoclose = snapshot
 3401                                .chars_at(selection.start)
 3402                                .next()
 3403                                .map_or(true, |c| scope.should_autoclose_before(c));
 3404
 3405                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3406                                && bracket_pair.start.len() == 1
 3407                            {
 3408                                let target = bracket_pair.start.chars().next().unwrap();
 3409                                let current_line_count = snapshot
 3410                                    .reversed_chars_at(selection.start)
 3411                                    .take_while(|&c| c != '\n')
 3412                                    .filter(|&c| c == target)
 3413                                    .count();
 3414                                current_line_count % 2 == 1
 3415                            } else {
 3416                                false
 3417                            };
 3418
 3419                            if autoclose
 3420                                && bracket_pair.close
 3421                                && following_text_allows_autoclose
 3422                                && !is_closing_quote
 3423                            {
 3424                                let anchor = snapshot.anchor_before(selection.end);
 3425                                new_selections.push((selection.map(|_| anchor), text.len()));
 3426                                new_autoclose_regions.push((
 3427                                    anchor,
 3428                                    text.len(),
 3429                                    selection.id,
 3430                                    bracket_pair.clone(),
 3431                                ));
 3432                                edits.push((
 3433                                    selection.range(),
 3434                                    format!("{}{}", text, bracket_pair.end).into(),
 3435                                ));
 3436                                bracket_inserted = true;
 3437                                continue;
 3438                            }
 3439                        }
 3440
 3441                        if let Some(region) = autoclose_region {
 3442                            // If the selection is followed by an auto-inserted closing bracket,
 3443                            // then don't insert that closing bracket again; just move the selection
 3444                            // past the closing bracket.
 3445                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3446                                && text.as_ref() == region.pair.end.as_str();
 3447                            if should_skip {
 3448                                let anchor = snapshot.anchor_after(selection.end);
 3449                                new_selections
 3450                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3451                                continue;
 3452                            }
 3453                        }
 3454
 3455                        let always_treat_brackets_as_autoclosed = snapshot
 3456                            .settings_at(selection.start, cx)
 3457                            .always_treat_brackets_as_autoclosed;
 3458                        if always_treat_brackets_as_autoclosed
 3459                            && is_bracket_pair_end
 3460                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3461                        {
 3462                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3463                            // and the inserted text is a closing bracket and the selection is followed
 3464                            // by the closing bracket then move the selection past the closing bracket.
 3465                            let anchor = snapshot.anchor_after(selection.end);
 3466                            new_selections.push((selection.map(|_| anchor), text.len()));
 3467                            continue;
 3468                        }
 3469                    }
 3470                    // If an opening bracket is 1 character long and is typed while
 3471                    // text is selected, then surround that text with the bracket pair.
 3472                    else if auto_surround
 3473                        && bracket_pair.surround
 3474                        && is_bracket_pair_start
 3475                        && bracket_pair.start.chars().count() == 1
 3476                    {
 3477                        edits.push((selection.start..selection.start, text.clone()));
 3478                        edits.push((
 3479                            selection.end..selection.end,
 3480                            bracket_pair.end.as_str().into(),
 3481                        ));
 3482                        bracket_inserted = true;
 3483                        new_selections.push((
 3484                            Selection {
 3485                                id: selection.id,
 3486                                start: snapshot.anchor_after(selection.start),
 3487                                end: snapshot.anchor_before(selection.end),
 3488                                reversed: selection.reversed,
 3489                                goal: selection.goal,
 3490                            },
 3491                            0,
 3492                        ));
 3493                        continue;
 3494                    }
 3495                }
 3496            }
 3497
 3498            if self.auto_replace_emoji_shortcode
 3499                && selection.is_empty()
 3500                && text.as_ref().ends_with(':')
 3501            {
 3502                if let Some(possible_emoji_short_code) =
 3503                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3504                {
 3505                    if !possible_emoji_short_code.is_empty() {
 3506                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3507                            let emoji_shortcode_start = Point::new(
 3508                                selection.start.row,
 3509                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3510                            );
 3511
 3512                            // Remove shortcode from buffer
 3513                            edits.push((
 3514                                emoji_shortcode_start..selection.start,
 3515                                "".to_string().into(),
 3516                            ));
 3517                            new_selections.push((
 3518                                Selection {
 3519                                    id: selection.id,
 3520                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3521                                    end: snapshot.anchor_before(selection.start),
 3522                                    reversed: selection.reversed,
 3523                                    goal: selection.goal,
 3524                                },
 3525                                0,
 3526                            ));
 3527
 3528                            // Insert emoji
 3529                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3530                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3531                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3532
 3533                            continue;
 3534                        }
 3535                    }
 3536                }
 3537            }
 3538
 3539            // If not handling any auto-close operation, then just replace the selected
 3540            // text with the given input and move the selection to the end of the
 3541            // newly inserted text.
 3542            let anchor = snapshot.anchor_after(selection.end);
 3543            if !self.linked_edit_ranges.is_empty() {
 3544                let start_anchor = snapshot.anchor_before(selection.start);
 3545
 3546                let is_word_char = text.chars().next().map_or(true, |char| {
 3547                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3548                    classifier.is_word(char)
 3549                });
 3550
 3551                if is_word_char {
 3552                    if let Some(ranges) = self
 3553                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3554                    {
 3555                        for (buffer, edits) in ranges {
 3556                            linked_edits
 3557                                .entry(buffer.clone())
 3558                                .or_default()
 3559                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3560                        }
 3561                    }
 3562                }
 3563            }
 3564
 3565            new_selections.push((selection.map(|_| anchor), 0));
 3566            edits.push((selection.start..selection.end, text.clone()));
 3567        }
 3568
 3569        drop(snapshot);
 3570
 3571        self.transact(cx, |this, cx| {
 3572            this.buffer.update(cx, |buffer, cx| {
 3573                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3574            });
 3575            for (buffer, edits) in linked_edits {
 3576                buffer.update(cx, |buffer, cx| {
 3577                    let snapshot = buffer.snapshot();
 3578                    let edits = edits
 3579                        .into_iter()
 3580                        .map(|(range, text)| {
 3581                            use text::ToPoint as TP;
 3582                            let end_point = TP::to_point(&range.end, &snapshot);
 3583                            let start_point = TP::to_point(&range.start, &snapshot);
 3584                            (start_point..end_point, text)
 3585                        })
 3586                        .sorted_by_key(|(range, _)| range.start)
 3587                        .collect::<Vec<_>>();
 3588                    buffer.edit(edits, None, cx);
 3589                })
 3590            }
 3591            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3592            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3593            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3594            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3595                .zip(new_selection_deltas)
 3596                .map(|(selection, delta)| Selection {
 3597                    id: selection.id,
 3598                    start: selection.start + delta,
 3599                    end: selection.end + delta,
 3600                    reversed: selection.reversed,
 3601                    goal: SelectionGoal::None,
 3602                })
 3603                .collect::<Vec<_>>();
 3604
 3605            let mut i = 0;
 3606            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3607                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3608                let start = map.buffer_snapshot.anchor_before(position);
 3609                let end = map.buffer_snapshot.anchor_after(position);
 3610                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3611                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3612                        Ordering::Less => i += 1,
 3613                        Ordering::Greater => break,
 3614                        Ordering::Equal => {
 3615                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3616                                Ordering::Less => i += 1,
 3617                                Ordering::Equal => break,
 3618                                Ordering::Greater => break,
 3619                            }
 3620                        }
 3621                    }
 3622                }
 3623                this.autoclose_regions.insert(
 3624                    i,
 3625                    AutocloseRegion {
 3626                        selection_id,
 3627                        range: start..end,
 3628                        pair,
 3629                    },
 3630                );
 3631            }
 3632
 3633            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3634            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3635                s.select(new_selections)
 3636            });
 3637
 3638            if !bracket_inserted {
 3639                if let Some(on_type_format_task) =
 3640                    this.trigger_on_type_formatting(text.to_string(), cx)
 3641                {
 3642                    on_type_format_task.detach_and_log_err(cx);
 3643                }
 3644            }
 3645
 3646            let editor_settings = EditorSettings::get_global(cx);
 3647            if bracket_inserted
 3648                && (editor_settings.auto_signature_help
 3649                    || editor_settings.show_signature_help_after_edits)
 3650            {
 3651                this.show_signature_help(&ShowSignatureHelp, cx);
 3652            }
 3653
 3654            let trigger_in_words = !had_active_inline_completion;
 3655            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3656            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3657            this.refresh_inline_completion(true, false, cx);
 3658        });
 3659    }
 3660
 3661    fn find_possible_emoji_shortcode_at_position(
 3662        snapshot: &MultiBufferSnapshot,
 3663        position: Point,
 3664    ) -> Option<String> {
 3665        let mut chars = Vec::new();
 3666        let mut found_colon = false;
 3667        for char in snapshot.reversed_chars_at(position).take(100) {
 3668            // Found a possible emoji shortcode in the middle of the buffer
 3669            if found_colon {
 3670                if char.is_whitespace() {
 3671                    chars.reverse();
 3672                    return Some(chars.iter().collect());
 3673                }
 3674                // If the previous character is not a whitespace, we are in the middle of a word
 3675                // and we only want to complete the shortcode if the word is made up of other emojis
 3676                let mut containing_word = String::new();
 3677                for ch in snapshot
 3678                    .reversed_chars_at(position)
 3679                    .skip(chars.len() + 1)
 3680                    .take(100)
 3681                {
 3682                    if ch.is_whitespace() {
 3683                        break;
 3684                    }
 3685                    containing_word.push(ch);
 3686                }
 3687                let containing_word = containing_word.chars().rev().collect::<String>();
 3688                if util::word_consists_of_emojis(containing_word.as_str()) {
 3689                    chars.reverse();
 3690                    return Some(chars.iter().collect());
 3691                }
 3692            }
 3693
 3694            if char.is_whitespace() || !char.is_ascii() {
 3695                return None;
 3696            }
 3697            if char == ':' {
 3698                found_colon = true;
 3699            } else {
 3700                chars.push(char);
 3701            }
 3702        }
 3703        // Found a possible emoji shortcode at the beginning of the buffer
 3704        chars.reverse();
 3705        Some(chars.iter().collect())
 3706    }
 3707
 3708    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3709        self.transact(cx, |this, cx| {
 3710            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3711                let selections = this.selections.all::<usize>(cx);
 3712                let multi_buffer = this.buffer.read(cx);
 3713                let buffer = multi_buffer.snapshot(cx);
 3714                selections
 3715                    .iter()
 3716                    .map(|selection| {
 3717                        let start_point = selection.start.to_point(&buffer);
 3718                        let mut indent =
 3719                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3720                        indent.len = cmp::min(indent.len, start_point.column);
 3721                        let start = selection.start;
 3722                        let end = selection.end;
 3723                        let selection_is_empty = start == end;
 3724                        let language_scope = buffer.language_scope_at(start);
 3725                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3726                            &language_scope
 3727                        {
 3728                            let leading_whitespace_len = buffer
 3729                                .reversed_chars_at(start)
 3730                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3731                                .map(|c| c.len_utf8())
 3732                                .sum::<usize>();
 3733
 3734                            let trailing_whitespace_len = buffer
 3735                                .chars_at(end)
 3736                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3737                                .map(|c| c.len_utf8())
 3738                                .sum::<usize>();
 3739
 3740                            let insert_extra_newline =
 3741                                language.brackets().any(|(pair, enabled)| {
 3742                                    let pair_start = pair.start.trim_end();
 3743                                    let pair_end = pair.end.trim_start();
 3744
 3745                                    enabled
 3746                                        && pair.newline
 3747                                        && buffer.contains_str_at(
 3748                                            end + trailing_whitespace_len,
 3749                                            pair_end,
 3750                                        )
 3751                                        && buffer.contains_str_at(
 3752                                            (start - leading_whitespace_len)
 3753                                                .saturating_sub(pair_start.len()),
 3754                                            pair_start,
 3755                                        )
 3756                                });
 3757
 3758                            // Comment extension on newline is allowed only for cursor selections
 3759                            let comment_delimiter = maybe!({
 3760                                if !selection_is_empty {
 3761                                    return None;
 3762                                }
 3763
 3764                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3765                                    return None;
 3766                                }
 3767
 3768                                let delimiters = language.line_comment_prefixes();
 3769                                let max_len_of_delimiter =
 3770                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3771                                let (snapshot, range) =
 3772                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3773
 3774                                let mut index_of_first_non_whitespace = 0;
 3775                                let comment_candidate = snapshot
 3776                                    .chars_for_range(range)
 3777                                    .skip_while(|c| {
 3778                                        let should_skip = c.is_whitespace();
 3779                                        if should_skip {
 3780                                            index_of_first_non_whitespace += 1;
 3781                                        }
 3782                                        should_skip
 3783                                    })
 3784                                    .take(max_len_of_delimiter)
 3785                                    .collect::<String>();
 3786                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3787                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3788                                })?;
 3789                                let cursor_is_placed_after_comment_marker =
 3790                                    index_of_first_non_whitespace + comment_prefix.len()
 3791                                        <= start_point.column as usize;
 3792                                if cursor_is_placed_after_comment_marker {
 3793                                    Some(comment_prefix.clone())
 3794                                } else {
 3795                                    None
 3796                                }
 3797                            });
 3798                            (comment_delimiter, insert_extra_newline)
 3799                        } else {
 3800                            (None, false)
 3801                        };
 3802
 3803                        let capacity_for_delimiter = comment_delimiter
 3804                            .as_deref()
 3805                            .map(str::len)
 3806                            .unwrap_or_default();
 3807                        let mut new_text =
 3808                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3809                        new_text.push('\n');
 3810                        new_text.extend(indent.chars());
 3811                        if let Some(delimiter) = &comment_delimiter {
 3812                            new_text.push_str(delimiter);
 3813                        }
 3814                        if insert_extra_newline {
 3815                            new_text = new_text.repeat(2);
 3816                        }
 3817
 3818                        let anchor = buffer.anchor_after(end);
 3819                        let new_selection = selection.map(|_| anchor);
 3820                        (
 3821                            (start..end, new_text),
 3822                            (insert_extra_newline, new_selection),
 3823                        )
 3824                    })
 3825                    .unzip()
 3826            };
 3827
 3828            this.edit_with_autoindent(edits, cx);
 3829            let buffer = this.buffer.read(cx).snapshot(cx);
 3830            let new_selections = selection_fixup_info
 3831                .into_iter()
 3832                .map(|(extra_newline_inserted, new_selection)| {
 3833                    let mut cursor = new_selection.end.to_point(&buffer);
 3834                    if extra_newline_inserted {
 3835                        cursor.row -= 1;
 3836                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3837                    }
 3838                    new_selection.map(|_| cursor)
 3839                })
 3840                .collect();
 3841
 3842            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3843            this.refresh_inline_completion(true, false, cx);
 3844        });
 3845    }
 3846
 3847    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3848        let buffer = self.buffer.read(cx);
 3849        let snapshot = buffer.snapshot(cx);
 3850
 3851        let mut edits = Vec::new();
 3852        let mut rows = Vec::new();
 3853
 3854        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3855            let cursor = selection.head();
 3856            let row = cursor.row;
 3857
 3858            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3859
 3860            let newline = "\n".to_string();
 3861            edits.push((start_of_line..start_of_line, newline));
 3862
 3863            rows.push(row + rows_inserted as u32);
 3864        }
 3865
 3866        self.transact(cx, |editor, cx| {
 3867            editor.edit(edits, cx);
 3868
 3869            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3870                let mut index = 0;
 3871                s.move_cursors_with(|map, _, _| {
 3872                    let row = rows[index];
 3873                    index += 1;
 3874
 3875                    let point = Point::new(row, 0);
 3876                    let boundary = map.next_line_boundary(point).1;
 3877                    let clipped = map.clip_point(boundary, Bias::Left);
 3878
 3879                    (clipped, SelectionGoal::None)
 3880                });
 3881            });
 3882
 3883            let mut indent_edits = Vec::new();
 3884            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3885            for row in rows {
 3886                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3887                for (row, indent) in indents {
 3888                    if indent.len == 0 {
 3889                        continue;
 3890                    }
 3891
 3892                    let text = match indent.kind {
 3893                        IndentKind::Space => " ".repeat(indent.len as usize),
 3894                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3895                    };
 3896                    let point = Point::new(row.0, 0);
 3897                    indent_edits.push((point..point, text));
 3898                }
 3899            }
 3900            editor.edit(indent_edits, cx);
 3901        });
 3902    }
 3903
 3904    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3905        let buffer = self.buffer.read(cx);
 3906        let snapshot = buffer.snapshot(cx);
 3907
 3908        let mut edits = Vec::new();
 3909        let mut rows = Vec::new();
 3910        let mut rows_inserted = 0;
 3911
 3912        for selection in self.selections.all_adjusted(cx) {
 3913            let cursor = selection.head();
 3914            let row = cursor.row;
 3915
 3916            let point = Point::new(row + 1, 0);
 3917            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3918
 3919            let newline = "\n".to_string();
 3920            edits.push((start_of_line..start_of_line, newline));
 3921
 3922            rows_inserted += 1;
 3923            rows.push(row + rows_inserted);
 3924        }
 3925
 3926        self.transact(cx, |editor, cx| {
 3927            editor.edit(edits, cx);
 3928
 3929            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3930                let mut index = 0;
 3931                s.move_cursors_with(|map, _, _| {
 3932                    let row = rows[index];
 3933                    index += 1;
 3934
 3935                    let point = Point::new(row, 0);
 3936                    let boundary = map.next_line_boundary(point).1;
 3937                    let clipped = map.clip_point(boundary, Bias::Left);
 3938
 3939                    (clipped, SelectionGoal::None)
 3940                });
 3941            });
 3942
 3943            let mut indent_edits = Vec::new();
 3944            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3945            for row in rows {
 3946                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3947                for (row, indent) in indents {
 3948                    if indent.len == 0 {
 3949                        continue;
 3950                    }
 3951
 3952                    let text = match indent.kind {
 3953                        IndentKind::Space => " ".repeat(indent.len as usize),
 3954                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3955                    };
 3956                    let point = Point::new(row.0, 0);
 3957                    indent_edits.push((point..point, text));
 3958                }
 3959            }
 3960            editor.edit(indent_edits, cx);
 3961        });
 3962    }
 3963
 3964    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3965        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3966            original_indent_columns: Vec::new(),
 3967        });
 3968        self.insert_with_autoindent_mode(text, autoindent, cx);
 3969    }
 3970
 3971    fn insert_with_autoindent_mode(
 3972        &mut self,
 3973        text: &str,
 3974        autoindent_mode: Option<AutoindentMode>,
 3975        cx: &mut ViewContext<Self>,
 3976    ) {
 3977        if self.read_only(cx) {
 3978            return;
 3979        }
 3980
 3981        let text: Arc<str> = text.into();
 3982        self.transact(cx, |this, cx| {
 3983            let old_selections = this.selections.all_adjusted(cx);
 3984            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3985                let anchors = {
 3986                    let snapshot = buffer.read(cx);
 3987                    old_selections
 3988                        .iter()
 3989                        .map(|s| {
 3990                            let anchor = snapshot.anchor_after(s.head());
 3991                            s.map(|_| anchor)
 3992                        })
 3993                        .collect::<Vec<_>>()
 3994                };
 3995                buffer.edit(
 3996                    old_selections
 3997                        .iter()
 3998                        .map(|s| (s.start..s.end, text.clone())),
 3999                    autoindent_mode,
 4000                    cx,
 4001                );
 4002                anchors
 4003            });
 4004
 4005            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4006                s.select_anchors(selection_anchors);
 4007            })
 4008        });
 4009    }
 4010
 4011    fn trigger_completion_on_input(
 4012        &mut self,
 4013        text: &str,
 4014        trigger_in_words: bool,
 4015        cx: &mut ViewContext<Self>,
 4016    ) {
 4017        if self.is_completion_trigger(text, trigger_in_words, cx) {
 4018            self.show_completions(
 4019                &ShowCompletions {
 4020                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4021                },
 4022                cx,
 4023            );
 4024        } else {
 4025            self.hide_context_menu(cx);
 4026        }
 4027    }
 4028
 4029    fn is_completion_trigger(
 4030        &self,
 4031        text: &str,
 4032        trigger_in_words: bool,
 4033        cx: &mut ViewContext<Self>,
 4034    ) -> bool {
 4035        let position = self.selections.newest_anchor().head();
 4036        let multibuffer = self.buffer.read(cx);
 4037        let Some(buffer) = position
 4038            .buffer_id
 4039            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4040        else {
 4041            return false;
 4042        };
 4043
 4044        if let Some(completion_provider) = &self.completion_provider {
 4045            completion_provider.is_completion_trigger(
 4046                &buffer,
 4047                position.text_anchor,
 4048                text,
 4049                trigger_in_words,
 4050                cx,
 4051            )
 4052        } else {
 4053            false
 4054        }
 4055    }
 4056
 4057    /// If any empty selections is touching the start of its innermost containing autoclose
 4058    /// region, expand it to select the brackets.
 4059    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4060        let selections = self.selections.all::<usize>(cx);
 4061        let buffer = self.buffer.read(cx).read(cx);
 4062        let new_selections = self
 4063            .selections_with_autoclose_regions(selections, &buffer)
 4064            .map(|(mut selection, region)| {
 4065                if !selection.is_empty() {
 4066                    return selection;
 4067                }
 4068
 4069                if let Some(region) = region {
 4070                    let mut range = region.range.to_offset(&buffer);
 4071                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4072                        range.start -= region.pair.start.len();
 4073                        if buffer.contains_str_at(range.start, &region.pair.start)
 4074                            && buffer.contains_str_at(range.end, &region.pair.end)
 4075                        {
 4076                            range.end += region.pair.end.len();
 4077                            selection.start = range.start;
 4078                            selection.end = range.end;
 4079
 4080                            return selection;
 4081                        }
 4082                    }
 4083                }
 4084
 4085                let always_treat_brackets_as_autoclosed = buffer
 4086                    .settings_at(selection.start, cx)
 4087                    .always_treat_brackets_as_autoclosed;
 4088
 4089                if !always_treat_brackets_as_autoclosed {
 4090                    return selection;
 4091                }
 4092
 4093                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4094                    for (pair, enabled) in scope.brackets() {
 4095                        if !enabled || !pair.close {
 4096                            continue;
 4097                        }
 4098
 4099                        if buffer.contains_str_at(selection.start, &pair.end) {
 4100                            let pair_start_len = pair.start.len();
 4101                            if buffer.contains_str_at(
 4102                                selection.start.saturating_sub(pair_start_len),
 4103                                &pair.start,
 4104                            ) {
 4105                                selection.start -= pair_start_len;
 4106                                selection.end += pair.end.len();
 4107
 4108                                return selection;
 4109                            }
 4110                        }
 4111                    }
 4112                }
 4113
 4114                selection
 4115            })
 4116            .collect();
 4117
 4118        drop(buffer);
 4119        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4120    }
 4121
 4122    /// Iterate the given selections, and for each one, find the smallest surrounding
 4123    /// autoclose region. This uses the ordering of the selections and the autoclose
 4124    /// regions to avoid repeated comparisons.
 4125    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4126        &'a self,
 4127        selections: impl IntoIterator<Item = Selection<D>>,
 4128        buffer: &'a MultiBufferSnapshot,
 4129    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4130        let mut i = 0;
 4131        let mut regions = self.autoclose_regions.as_slice();
 4132        selections.into_iter().map(move |selection| {
 4133            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4134
 4135            let mut enclosing = None;
 4136            while let Some(pair_state) = regions.get(i) {
 4137                if pair_state.range.end.to_offset(buffer) < range.start {
 4138                    regions = &regions[i + 1..];
 4139                    i = 0;
 4140                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4141                    break;
 4142                } else {
 4143                    if pair_state.selection_id == selection.id {
 4144                        enclosing = Some(pair_state);
 4145                    }
 4146                    i += 1;
 4147                }
 4148            }
 4149
 4150            (selection, enclosing)
 4151        })
 4152    }
 4153
 4154    /// Remove any autoclose regions that no longer contain their selection.
 4155    fn invalidate_autoclose_regions(
 4156        &mut self,
 4157        mut selections: &[Selection<Anchor>],
 4158        buffer: &MultiBufferSnapshot,
 4159    ) {
 4160        self.autoclose_regions.retain(|state| {
 4161            let mut i = 0;
 4162            while let Some(selection) = selections.get(i) {
 4163                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4164                    selections = &selections[1..];
 4165                    continue;
 4166                }
 4167                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4168                    break;
 4169                }
 4170                if selection.id == state.selection_id {
 4171                    return true;
 4172                } else {
 4173                    i += 1;
 4174                }
 4175            }
 4176            false
 4177        });
 4178    }
 4179
 4180    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4181        let offset = position.to_offset(buffer);
 4182        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4183        if offset > word_range.start && kind == Some(CharKind::Word) {
 4184            Some(
 4185                buffer
 4186                    .text_for_range(word_range.start..offset)
 4187                    .collect::<String>(),
 4188            )
 4189        } else {
 4190            None
 4191        }
 4192    }
 4193
 4194    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4195        self.refresh_inlay_hints(
 4196            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4197            cx,
 4198        );
 4199    }
 4200
 4201    pub fn inlay_hints_enabled(&self) -> bool {
 4202        self.inlay_hint_cache.enabled
 4203    }
 4204
 4205    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4206        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4207            return;
 4208        }
 4209
 4210        let reason_description = reason.description();
 4211        let ignore_debounce = matches!(
 4212            reason,
 4213            InlayHintRefreshReason::SettingsChange(_)
 4214                | InlayHintRefreshReason::Toggle(_)
 4215                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4216        );
 4217        let (invalidate_cache, required_languages) = match reason {
 4218            InlayHintRefreshReason::Toggle(enabled) => {
 4219                self.inlay_hint_cache.enabled = enabled;
 4220                if enabled {
 4221                    (InvalidationStrategy::RefreshRequested, None)
 4222                } else {
 4223                    self.inlay_hint_cache.clear();
 4224                    self.splice_inlays(
 4225                        self.visible_inlay_hints(cx)
 4226                            .iter()
 4227                            .map(|inlay| inlay.id)
 4228                            .collect(),
 4229                        Vec::new(),
 4230                        cx,
 4231                    );
 4232                    return;
 4233                }
 4234            }
 4235            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4236                match self.inlay_hint_cache.update_settings(
 4237                    &self.buffer,
 4238                    new_settings,
 4239                    self.visible_inlay_hints(cx),
 4240                    cx,
 4241                ) {
 4242                    ControlFlow::Break(Some(InlaySplice {
 4243                        to_remove,
 4244                        to_insert,
 4245                    })) => {
 4246                        self.splice_inlays(to_remove, to_insert, cx);
 4247                        return;
 4248                    }
 4249                    ControlFlow::Break(None) => return,
 4250                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4251                }
 4252            }
 4253            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4254                if let Some(InlaySplice {
 4255                    to_remove,
 4256                    to_insert,
 4257                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4258                {
 4259                    self.splice_inlays(to_remove, to_insert, cx);
 4260                }
 4261                return;
 4262            }
 4263            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4264            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4265                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4266            }
 4267            InlayHintRefreshReason::RefreshRequested => {
 4268                (InvalidationStrategy::RefreshRequested, None)
 4269            }
 4270        };
 4271
 4272        if let Some(InlaySplice {
 4273            to_remove,
 4274            to_insert,
 4275        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4276            reason_description,
 4277            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4278            invalidate_cache,
 4279            ignore_debounce,
 4280            cx,
 4281        ) {
 4282            self.splice_inlays(to_remove, to_insert, cx);
 4283        }
 4284    }
 4285
 4286    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4287        self.display_map
 4288            .read(cx)
 4289            .current_inlays()
 4290            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4291            .cloned()
 4292            .collect()
 4293    }
 4294
 4295    pub fn excerpts_for_inlay_hints_query(
 4296        &self,
 4297        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4298        cx: &mut ViewContext<Editor>,
 4299    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4300        let Some(project) = self.project.as_ref() else {
 4301            return HashMap::default();
 4302        };
 4303        let project = project.read(cx);
 4304        let multi_buffer = self.buffer().read(cx);
 4305        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4306        let multi_buffer_visible_start = self
 4307            .scroll_manager
 4308            .anchor()
 4309            .anchor
 4310            .to_point(&multi_buffer_snapshot);
 4311        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4312            multi_buffer_visible_start
 4313                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4314            Bias::Left,
 4315        );
 4316        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4317        multi_buffer
 4318            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4319            .into_iter()
 4320            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4321            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4322                let buffer = buffer_handle.read(cx);
 4323                let buffer_file = project::File::from_dyn(buffer.file())?;
 4324                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4325                let worktree_entry = buffer_worktree
 4326                    .read(cx)
 4327                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4328                if worktree_entry.is_ignored {
 4329                    return None;
 4330                }
 4331
 4332                let language = buffer.language()?;
 4333                if let Some(restrict_to_languages) = restrict_to_languages {
 4334                    if !restrict_to_languages.contains(language) {
 4335                        return None;
 4336                    }
 4337                }
 4338                Some((
 4339                    excerpt_id,
 4340                    (
 4341                        buffer_handle,
 4342                        buffer.version().clone(),
 4343                        excerpt_visible_range,
 4344                    ),
 4345                ))
 4346            })
 4347            .collect()
 4348    }
 4349
 4350    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4351        TextLayoutDetails {
 4352            text_system: cx.text_system().clone(),
 4353            editor_style: self.style.clone().unwrap(),
 4354            rem_size: cx.rem_size(),
 4355            scroll_anchor: self.scroll_manager.anchor(),
 4356            visible_rows: self.visible_line_count(),
 4357            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4358        }
 4359    }
 4360
 4361    fn splice_inlays(
 4362        &self,
 4363        to_remove: Vec<InlayId>,
 4364        to_insert: Vec<Inlay>,
 4365        cx: &mut ViewContext<Self>,
 4366    ) {
 4367        self.display_map.update(cx, |display_map, cx| {
 4368            display_map.splice_inlays(to_remove, to_insert, cx);
 4369        });
 4370        cx.notify();
 4371    }
 4372
 4373    fn trigger_on_type_formatting(
 4374        &self,
 4375        input: String,
 4376        cx: &mut ViewContext<Self>,
 4377    ) -> Option<Task<Result<()>>> {
 4378        if input.len() != 1 {
 4379            return None;
 4380        }
 4381
 4382        let project = self.project.as_ref()?;
 4383        let position = self.selections.newest_anchor().head();
 4384        let (buffer, buffer_position) = self
 4385            .buffer
 4386            .read(cx)
 4387            .text_anchor_for_position(position, cx)?;
 4388
 4389        let settings = language_settings::language_settings(
 4390            buffer
 4391                .read(cx)
 4392                .language_at(buffer_position)
 4393                .map(|l| l.name()),
 4394            buffer.read(cx).file(),
 4395            cx,
 4396        );
 4397        if !settings.use_on_type_format {
 4398            return None;
 4399        }
 4400
 4401        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4402        // hence we do LSP request & edit on host side only — add formats to host's history.
 4403        let push_to_lsp_host_history = true;
 4404        // If this is not the host, append its history with new edits.
 4405        let push_to_client_history = project.read(cx).is_via_collab();
 4406
 4407        let on_type_formatting = project.update(cx, |project, cx| {
 4408            project.on_type_format(
 4409                buffer.clone(),
 4410                buffer_position,
 4411                input,
 4412                push_to_lsp_host_history,
 4413                cx,
 4414            )
 4415        });
 4416        Some(cx.spawn(|editor, mut cx| async move {
 4417            if let Some(transaction) = on_type_formatting.await? {
 4418                if push_to_client_history {
 4419                    buffer
 4420                        .update(&mut cx, |buffer, _| {
 4421                            buffer.push_transaction(transaction, Instant::now());
 4422                        })
 4423                        .ok();
 4424                }
 4425                editor.update(&mut cx, |editor, cx| {
 4426                    editor.refresh_document_highlights(cx);
 4427                })?;
 4428            }
 4429            Ok(())
 4430        }))
 4431    }
 4432
 4433    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4434        if self.pending_rename.is_some() {
 4435            return;
 4436        }
 4437
 4438        let Some(provider) = self.completion_provider.as_ref() else {
 4439            return;
 4440        };
 4441
 4442        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4443            return;
 4444        }
 4445
 4446        let position = self.selections.newest_anchor().head();
 4447        let (buffer, buffer_position) =
 4448            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4449                output
 4450            } else {
 4451                return;
 4452            };
 4453
 4454        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4455        let is_followup_invoke = {
 4456            let context_menu_state = self.context_menu.read();
 4457            matches!(
 4458                context_menu_state.deref(),
 4459                Some(ContextMenu::Completions(_))
 4460            )
 4461        };
 4462        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4463            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4464            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4465                CompletionTriggerKind::TRIGGER_CHARACTER
 4466            }
 4467
 4468            _ => CompletionTriggerKind::INVOKED,
 4469        };
 4470        let completion_context = CompletionContext {
 4471            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4472                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4473                    Some(String::from(trigger))
 4474                } else {
 4475                    None
 4476                }
 4477            }),
 4478            trigger_kind,
 4479        };
 4480        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4481        let sort_completions = provider.sort_completions();
 4482
 4483        let id = post_inc(&mut self.next_completion_id);
 4484        let task = cx.spawn(|editor, mut cx| {
 4485            async move {
 4486                editor.update(&mut cx, |this, _| {
 4487                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4488                })?;
 4489                let completions = completions.await.log_err();
 4490                let menu = if let Some(completions) = completions {
 4491                    let mut menu = CompletionsMenu::new(
 4492                        id,
 4493                        sort_completions,
 4494                        position,
 4495                        buffer.clone(),
 4496                        completions.into(),
 4497                    );
 4498                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4499                        .await;
 4500
 4501                    if menu.matches.is_empty() {
 4502                        None
 4503                    } else {
 4504                        Some(menu)
 4505                    }
 4506                } else {
 4507                    None
 4508                };
 4509
 4510                editor.update(&mut cx, |editor, cx| {
 4511                    let mut context_menu = editor.context_menu.write();
 4512                    match context_menu.as_ref() {
 4513                        None => {}
 4514
 4515                        Some(ContextMenu::Completions(prev_menu)) => {
 4516                            if prev_menu.id > id {
 4517                                return;
 4518                            }
 4519                        }
 4520
 4521                        _ => return,
 4522                    }
 4523
 4524                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 4525                        let mut menu = menu.unwrap();
 4526                        menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
 4527                        *context_menu = Some(ContextMenu::Completions(menu));
 4528                        drop(context_menu);
 4529                        editor.discard_inline_completion(false, cx);
 4530                        cx.notify();
 4531                    } else if editor.completion_tasks.len() <= 1 {
 4532                        // If there are no more completion tasks and the last menu was
 4533                        // empty, we should hide it. If it was already hidden, we should
 4534                        // also show the copilot completion when available.
 4535                        drop(context_menu);
 4536                        if editor.hide_context_menu(cx).is_none() {
 4537                            editor.update_visible_inline_completion(cx);
 4538                        }
 4539                    }
 4540                })?;
 4541
 4542                Ok::<_, anyhow::Error>(())
 4543            }
 4544            .log_err()
 4545        });
 4546
 4547        self.completion_tasks.push((id, task));
 4548    }
 4549
 4550    pub fn confirm_completion(
 4551        &mut self,
 4552        action: &ConfirmCompletion,
 4553        cx: &mut ViewContext<Self>,
 4554    ) -> Option<Task<Result<()>>> {
 4555        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4556    }
 4557
 4558    pub fn compose_completion(
 4559        &mut self,
 4560        action: &ComposeCompletion,
 4561        cx: &mut ViewContext<Self>,
 4562    ) -> Option<Task<Result<()>>> {
 4563        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4564    }
 4565
 4566    fn do_completion(
 4567        &mut self,
 4568        item_ix: Option<usize>,
 4569        intent: CompletionIntent,
 4570        cx: &mut ViewContext<Editor>,
 4571    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4572        use language::ToOffset as _;
 4573
 4574        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4575            menu
 4576        } else {
 4577            return None;
 4578        };
 4579
 4580        let mat = completions_menu
 4581            .matches
 4582            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4583        let buffer_handle = completions_menu.buffer;
 4584        let completions = completions_menu.completions.read();
 4585        let completion = completions.get(mat.candidate_id)?;
 4586        cx.stop_propagation();
 4587
 4588        let snippet;
 4589        let text;
 4590
 4591        if completion.is_snippet() {
 4592            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4593            text = snippet.as_ref().unwrap().text.clone();
 4594        } else {
 4595            snippet = None;
 4596            text = completion.new_text.clone();
 4597        };
 4598        let selections = self.selections.all::<usize>(cx);
 4599        let buffer = buffer_handle.read(cx);
 4600        let old_range = completion.old_range.to_offset(buffer);
 4601        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4602
 4603        let newest_selection = self.selections.newest_anchor();
 4604        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4605            return None;
 4606        }
 4607
 4608        let lookbehind = newest_selection
 4609            .start
 4610            .text_anchor
 4611            .to_offset(buffer)
 4612            .saturating_sub(old_range.start);
 4613        let lookahead = old_range
 4614            .end
 4615            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4616        let mut common_prefix_len = old_text
 4617            .bytes()
 4618            .zip(text.bytes())
 4619            .take_while(|(a, b)| a == b)
 4620            .count();
 4621
 4622        let snapshot = self.buffer.read(cx).snapshot(cx);
 4623        let mut range_to_replace: Option<Range<isize>> = None;
 4624        let mut ranges = Vec::new();
 4625        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4626        for selection in &selections {
 4627            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4628                let start = selection.start.saturating_sub(lookbehind);
 4629                let end = selection.end + lookahead;
 4630                if selection.id == newest_selection.id {
 4631                    range_to_replace = Some(
 4632                        ((start + common_prefix_len) as isize - selection.start as isize)
 4633                            ..(end as isize - selection.start as isize),
 4634                    );
 4635                }
 4636                ranges.push(start + common_prefix_len..end);
 4637            } else {
 4638                common_prefix_len = 0;
 4639                ranges.clear();
 4640                ranges.extend(selections.iter().map(|s| {
 4641                    if s.id == newest_selection.id {
 4642                        range_to_replace = Some(
 4643                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4644                                - selection.start as isize
 4645                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4646                                    - selection.start as isize,
 4647                        );
 4648                        old_range.clone()
 4649                    } else {
 4650                        s.start..s.end
 4651                    }
 4652                }));
 4653                break;
 4654            }
 4655            if !self.linked_edit_ranges.is_empty() {
 4656                let start_anchor = snapshot.anchor_before(selection.head());
 4657                let end_anchor = snapshot.anchor_after(selection.tail());
 4658                if let Some(ranges) = self
 4659                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4660                {
 4661                    for (buffer, edits) in ranges {
 4662                        linked_edits.entry(buffer.clone()).or_default().extend(
 4663                            edits
 4664                                .into_iter()
 4665                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4666                        );
 4667                    }
 4668                }
 4669            }
 4670        }
 4671        let text = &text[common_prefix_len..];
 4672
 4673        cx.emit(EditorEvent::InputHandled {
 4674            utf16_range_to_replace: range_to_replace,
 4675            text: text.into(),
 4676        });
 4677
 4678        self.transact(cx, |this, cx| {
 4679            if let Some(mut snippet) = snippet {
 4680                snippet.text = text.to_string();
 4681                for tabstop in snippet
 4682                    .tabstops
 4683                    .iter_mut()
 4684                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4685                {
 4686                    tabstop.start -= common_prefix_len as isize;
 4687                    tabstop.end -= common_prefix_len as isize;
 4688                }
 4689
 4690                this.insert_snippet(&ranges, snippet, cx).log_err();
 4691            } else {
 4692                this.buffer.update(cx, |buffer, cx| {
 4693                    buffer.edit(
 4694                        ranges.iter().map(|range| (range.clone(), text)),
 4695                        this.autoindent_mode.clone(),
 4696                        cx,
 4697                    );
 4698                });
 4699            }
 4700            for (buffer, edits) in linked_edits {
 4701                buffer.update(cx, |buffer, cx| {
 4702                    let snapshot = buffer.snapshot();
 4703                    let edits = edits
 4704                        .into_iter()
 4705                        .map(|(range, text)| {
 4706                            use text::ToPoint as TP;
 4707                            let end_point = TP::to_point(&range.end, &snapshot);
 4708                            let start_point = TP::to_point(&range.start, &snapshot);
 4709                            (start_point..end_point, text)
 4710                        })
 4711                        .sorted_by_key(|(range, _)| range.start)
 4712                        .collect::<Vec<_>>();
 4713                    buffer.edit(edits, None, cx);
 4714                })
 4715            }
 4716
 4717            this.refresh_inline_completion(true, false, cx);
 4718        });
 4719
 4720        let show_new_completions_on_confirm = completion
 4721            .confirm
 4722            .as_ref()
 4723            .map_or(false, |confirm| confirm(intent, cx));
 4724        if show_new_completions_on_confirm {
 4725            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4726        }
 4727
 4728        let provider = self.completion_provider.as_ref()?;
 4729        let apply_edits = provider.apply_additional_edits_for_completion(
 4730            buffer_handle,
 4731            completion.clone(),
 4732            true,
 4733            cx,
 4734        );
 4735
 4736        let editor_settings = EditorSettings::get_global(cx);
 4737        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4738            // After the code completion is finished, users often want to know what signatures are needed.
 4739            // so we should automatically call signature_help
 4740            self.show_signature_help(&ShowSignatureHelp, cx);
 4741        }
 4742
 4743        Some(cx.foreground_executor().spawn(async move {
 4744            apply_edits.await?;
 4745            Ok(())
 4746        }))
 4747    }
 4748
 4749    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4750        let mut context_menu = self.context_menu.write();
 4751        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4752            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4753                // Toggle if we're selecting the same one
 4754                *context_menu = None;
 4755                cx.notify();
 4756                return;
 4757            } else {
 4758                // Otherwise, clear it and start a new one
 4759                *context_menu = None;
 4760                cx.notify();
 4761            }
 4762        }
 4763        drop(context_menu);
 4764        let snapshot = self.snapshot(cx);
 4765        let deployed_from_indicator = action.deployed_from_indicator;
 4766        let mut task = self.code_actions_task.take();
 4767        let action = action.clone();
 4768        cx.spawn(|editor, mut cx| async move {
 4769            while let Some(prev_task) = task {
 4770                prev_task.await.log_err();
 4771                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4772            }
 4773
 4774            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4775                if editor.focus_handle.is_focused(cx) {
 4776                    let multibuffer_point = action
 4777                        .deployed_from_indicator
 4778                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4779                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4780                    let (buffer, buffer_row) = snapshot
 4781                        .buffer_snapshot
 4782                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4783                        .and_then(|(buffer_snapshot, range)| {
 4784                            editor
 4785                                .buffer
 4786                                .read(cx)
 4787                                .buffer(buffer_snapshot.remote_id())
 4788                                .map(|buffer| (buffer, range.start.row))
 4789                        })?;
 4790                    let (_, code_actions) = editor
 4791                        .available_code_actions
 4792                        .clone()
 4793                        .and_then(|(location, code_actions)| {
 4794                            let snapshot = location.buffer.read(cx).snapshot();
 4795                            let point_range = location.range.to_point(&snapshot);
 4796                            let point_range = point_range.start.row..=point_range.end.row;
 4797                            if point_range.contains(&buffer_row) {
 4798                                Some((location, code_actions))
 4799                            } else {
 4800                                None
 4801                            }
 4802                        })
 4803                        .unzip();
 4804                    let buffer_id = buffer.read(cx).remote_id();
 4805                    let tasks = editor
 4806                        .tasks
 4807                        .get(&(buffer_id, buffer_row))
 4808                        .map(|t| Arc::new(t.to_owned()));
 4809                    if tasks.is_none() && code_actions.is_none() {
 4810                        return None;
 4811                    }
 4812
 4813                    editor.completion_tasks.clear();
 4814                    editor.discard_inline_completion(false, cx);
 4815                    let task_context =
 4816                        tasks
 4817                            .as_ref()
 4818                            .zip(editor.project.clone())
 4819                            .map(|(tasks, project)| {
 4820                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4821                            });
 4822
 4823                    Some(cx.spawn(|editor, mut cx| async move {
 4824                        let task_context = match task_context {
 4825                            Some(task_context) => task_context.await,
 4826                            None => None,
 4827                        };
 4828                        let resolved_tasks =
 4829                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4830                                Arc::new(ResolvedTasks {
 4831                                    templates: tasks.resolve(&task_context).collect(),
 4832                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4833                                        multibuffer_point.row,
 4834                                        tasks.column,
 4835                                    )),
 4836                                })
 4837                            });
 4838                        let spawn_straight_away = resolved_tasks
 4839                            .as_ref()
 4840                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4841                            && code_actions
 4842                                .as_ref()
 4843                                .map_or(true, |actions| actions.is_empty());
 4844                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4845                            *editor.context_menu.write() =
 4846                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4847                                    buffer,
 4848                                    actions: CodeActionContents {
 4849                                        tasks: resolved_tasks,
 4850                                        actions: code_actions,
 4851                                    },
 4852                                    selected_item: Default::default(),
 4853                                    scroll_handle: UniformListScrollHandle::default(),
 4854                                    deployed_from_indicator,
 4855                                }));
 4856                            if spawn_straight_away {
 4857                                if let Some(task) = editor.confirm_code_action(
 4858                                    &ConfirmCodeAction { item_ix: Some(0) },
 4859                                    cx,
 4860                                ) {
 4861                                    cx.notify();
 4862                                    return task;
 4863                                }
 4864                            }
 4865                            cx.notify();
 4866                            Task::ready(Ok(()))
 4867                        }) {
 4868                            task.await
 4869                        } else {
 4870                            Ok(())
 4871                        }
 4872                    }))
 4873                } else {
 4874                    Some(Task::ready(Ok(())))
 4875                }
 4876            })?;
 4877            if let Some(task) = spawned_test_task {
 4878                task.await?;
 4879            }
 4880
 4881            Ok::<_, anyhow::Error>(())
 4882        })
 4883        .detach_and_log_err(cx);
 4884    }
 4885
 4886    pub fn confirm_code_action(
 4887        &mut self,
 4888        action: &ConfirmCodeAction,
 4889        cx: &mut ViewContext<Self>,
 4890    ) -> Option<Task<Result<()>>> {
 4891        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4892            menu
 4893        } else {
 4894            return None;
 4895        };
 4896        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4897        let action = actions_menu.actions.get(action_ix)?;
 4898        let title = action.label();
 4899        let buffer = actions_menu.buffer;
 4900        let workspace = self.workspace()?;
 4901
 4902        match action {
 4903            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4904                workspace.update(cx, |workspace, cx| {
 4905                    workspace::tasks::schedule_resolved_task(
 4906                        workspace,
 4907                        task_source_kind,
 4908                        resolved_task,
 4909                        false,
 4910                        cx,
 4911                    );
 4912
 4913                    Some(Task::ready(Ok(())))
 4914                })
 4915            }
 4916            CodeActionsItem::CodeAction {
 4917                excerpt_id,
 4918                action,
 4919                provider,
 4920            } => {
 4921                let apply_code_action =
 4922                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4923                let workspace = workspace.downgrade();
 4924                Some(cx.spawn(|editor, cx| async move {
 4925                    let project_transaction = apply_code_action.await?;
 4926                    Self::open_project_transaction(
 4927                        &editor,
 4928                        workspace,
 4929                        project_transaction,
 4930                        title,
 4931                        cx,
 4932                    )
 4933                    .await
 4934                }))
 4935            }
 4936        }
 4937    }
 4938
 4939    pub async fn open_project_transaction(
 4940        this: &WeakView<Editor>,
 4941        workspace: WeakView<Workspace>,
 4942        transaction: ProjectTransaction,
 4943        title: String,
 4944        mut cx: AsyncWindowContext,
 4945    ) -> Result<()> {
 4946        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4947        cx.update(|cx| {
 4948            entries.sort_unstable_by_key(|(buffer, _)| {
 4949                buffer.read(cx).file().map(|f| f.path().clone())
 4950            });
 4951        })?;
 4952
 4953        // If the project transaction's edits are all contained within this editor, then
 4954        // avoid opening a new editor to display them.
 4955
 4956        if let Some((buffer, transaction)) = entries.first() {
 4957            if entries.len() == 1 {
 4958                let excerpt = this.update(&mut cx, |editor, cx| {
 4959                    editor
 4960                        .buffer()
 4961                        .read(cx)
 4962                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4963                })?;
 4964                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4965                    if excerpted_buffer == *buffer {
 4966                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4967                            let excerpt_range = excerpt_range.to_offset(buffer);
 4968                            buffer
 4969                                .edited_ranges_for_transaction::<usize>(transaction)
 4970                                .all(|range| {
 4971                                    excerpt_range.start <= range.start
 4972                                        && excerpt_range.end >= range.end
 4973                                })
 4974                        })?;
 4975
 4976                        if all_edits_within_excerpt {
 4977                            return Ok(());
 4978                        }
 4979                    }
 4980                }
 4981            }
 4982        } else {
 4983            return Ok(());
 4984        }
 4985
 4986        let mut ranges_to_highlight = Vec::new();
 4987        let excerpt_buffer = cx.new_model(|cx| {
 4988            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4989            for (buffer_handle, transaction) in &entries {
 4990                let buffer = buffer_handle.read(cx);
 4991                ranges_to_highlight.extend(
 4992                    multibuffer.push_excerpts_with_context_lines(
 4993                        buffer_handle.clone(),
 4994                        buffer
 4995                            .edited_ranges_for_transaction::<usize>(transaction)
 4996                            .collect(),
 4997                        DEFAULT_MULTIBUFFER_CONTEXT,
 4998                        cx,
 4999                    ),
 5000                );
 5001            }
 5002            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5003            multibuffer
 5004        })?;
 5005
 5006        workspace.update(&mut cx, |workspace, cx| {
 5007            let project = workspace.project().clone();
 5008            let editor =
 5009                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5010            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5011            editor.update(cx, |editor, cx| {
 5012                editor.highlight_background::<Self>(
 5013                    &ranges_to_highlight,
 5014                    |theme| theme.editor_highlighted_line_background,
 5015                    cx,
 5016                );
 5017            });
 5018        })?;
 5019
 5020        Ok(())
 5021    }
 5022
 5023    pub fn clear_code_action_providers(&mut self) {
 5024        self.code_action_providers.clear();
 5025        self.available_code_actions.take();
 5026    }
 5027
 5028    pub fn push_code_action_provider(
 5029        &mut self,
 5030        provider: Arc<dyn CodeActionProvider>,
 5031        cx: &mut ViewContext<Self>,
 5032    ) {
 5033        self.code_action_providers.push(provider);
 5034        self.refresh_code_actions(cx);
 5035    }
 5036
 5037    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5038        let buffer = self.buffer.read(cx);
 5039        let newest_selection = self.selections.newest_anchor().clone();
 5040        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5041        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5042        if start_buffer != end_buffer {
 5043            return None;
 5044        }
 5045
 5046        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5047            cx.background_executor()
 5048                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5049                .await;
 5050
 5051            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5052                let providers = this.code_action_providers.clone();
 5053                let tasks = this
 5054                    .code_action_providers
 5055                    .iter()
 5056                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5057                    .collect::<Vec<_>>();
 5058                (providers, tasks)
 5059            })?;
 5060
 5061            let mut actions = Vec::new();
 5062            for (provider, provider_actions) in
 5063                providers.into_iter().zip(future::join_all(tasks).await)
 5064            {
 5065                if let Some(provider_actions) = provider_actions.log_err() {
 5066                    actions.extend(provider_actions.into_iter().map(|action| {
 5067                        AvailableCodeAction {
 5068                            excerpt_id: newest_selection.start.excerpt_id,
 5069                            action,
 5070                            provider: provider.clone(),
 5071                        }
 5072                    }));
 5073                }
 5074            }
 5075
 5076            this.update(&mut cx, |this, cx| {
 5077                this.available_code_actions = if actions.is_empty() {
 5078                    None
 5079                } else {
 5080                    Some((
 5081                        Location {
 5082                            buffer: start_buffer,
 5083                            range: start..end,
 5084                        },
 5085                        actions.into(),
 5086                    ))
 5087                };
 5088                cx.notify();
 5089            })
 5090        }));
 5091        None
 5092    }
 5093
 5094    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5095        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5096            self.show_git_blame_inline = false;
 5097
 5098            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5099                cx.background_executor().timer(delay).await;
 5100
 5101                this.update(&mut cx, |this, cx| {
 5102                    this.show_git_blame_inline = true;
 5103                    cx.notify();
 5104                })
 5105                .log_err();
 5106            }));
 5107        }
 5108    }
 5109
 5110    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5111        if self.pending_rename.is_some() {
 5112            return None;
 5113        }
 5114
 5115        let provider = self.semantics_provider.clone()?;
 5116        let buffer = self.buffer.read(cx);
 5117        let newest_selection = self.selections.newest_anchor().clone();
 5118        let cursor_position = newest_selection.head();
 5119        let (cursor_buffer, cursor_buffer_position) =
 5120            buffer.text_anchor_for_position(cursor_position, cx)?;
 5121        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5122        if cursor_buffer != tail_buffer {
 5123            return None;
 5124        }
 5125
 5126        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5127            cx.background_executor()
 5128                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5129                .await;
 5130
 5131            let highlights = if let Some(highlights) = cx
 5132                .update(|cx| {
 5133                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5134                })
 5135                .ok()
 5136                .flatten()
 5137            {
 5138                highlights.await.log_err()
 5139            } else {
 5140                None
 5141            };
 5142
 5143            if let Some(highlights) = highlights {
 5144                this.update(&mut cx, |this, cx| {
 5145                    if this.pending_rename.is_some() {
 5146                        return;
 5147                    }
 5148
 5149                    let buffer_id = cursor_position.buffer_id;
 5150                    let buffer = this.buffer.read(cx);
 5151                    if !buffer
 5152                        .text_anchor_for_position(cursor_position, cx)
 5153                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5154                    {
 5155                        return;
 5156                    }
 5157
 5158                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5159                    let mut write_ranges = Vec::new();
 5160                    let mut read_ranges = Vec::new();
 5161                    for highlight in highlights {
 5162                        for (excerpt_id, excerpt_range) in
 5163                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5164                        {
 5165                            let start = highlight
 5166                                .range
 5167                                .start
 5168                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5169                            let end = highlight
 5170                                .range
 5171                                .end
 5172                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5173                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5174                                continue;
 5175                            }
 5176
 5177                            let range = Anchor {
 5178                                buffer_id,
 5179                                excerpt_id,
 5180                                text_anchor: start,
 5181                            }..Anchor {
 5182                                buffer_id,
 5183                                excerpt_id,
 5184                                text_anchor: end,
 5185                            };
 5186                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5187                                write_ranges.push(range);
 5188                            } else {
 5189                                read_ranges.push(range);
 5190                            }
 5191                        }
 5192                    }
 5193
 5194                    this.highlight_background::<DocumentHighlightRead>(
 5195                        &read_ranges,
 5196                        |theme| theme.editor_document_highlight_read_background,
 5197                        cx,
 5198                    );
 5199                    this.highlight_background::<DocumentHighlightWrite>(
 5200                        &write_ranges,
 5201                        |theme| theme.editor_document_highlight_write_background,
 5202                        cx,
 5203                    );
 5204                    cx.notify();
 5205                })
 5206                .log_err();
 5207            }
 5208        }));
 5209        None
 5210    }
 5211
 5212    pub fn refresh_inline_completion(
 5213        &mut self,
 5214        debounce: bool,
 5215        user_requested: bool,
 5216        cx: &mut ViewContext<Self>,
 5217    ) -> Option<()> {
 5218        let provider = self.inline_completion_provider()?;
 5219        let cursor = self.selections.newest_anchor().head();
 5220        let (buffer, cursor_buffer_position) =
 5221            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5222
 5223        if !user_requested
 5224            && (!self.enable_inline_completions
 5225                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5226        {
 5227            self.discard_inline_completion(false, cx);
 5228            return None;
 5229        }
 5230
 5231        self.update_visible_inline_completion(cx);
 5232        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5233        Some(())
 5234    }
 5235
 5236    fn cycle_inline_completion(
 5237        &mut self,
 5238        direction: Direction,
 5239        cx: &mut ViewContext<Self>,
 5240    ) -> Option<()> {
 5241        let provider = self.inline_completion_provider()?;
 5242        let cursor = self.selections.newest_anchor().head();
 5243        let (buffer, cursor_buffer_position) =
 5244            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5245        if !self.enable_inline_completions
 5246            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5247        {
 5248            return None;
 5249        }
 5250
 5251        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5252        self.update_visible_inline_completion(cx);
 5253
 5254        Some(())
 5255    }
 5256
 5257    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5258        if !self.has_active_inline_completion(cx) {
 5259            self.refresh_inline_completion(false, true, cx);
 5260            return;
 5261        }
 5262
 5263        self.update_visible_inline_completion(cx);
 5264    }
 5265
 5266    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5267        self.show_cursor_names(cx);
 5268    }
 5269
 5270    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5271        self.show_cursor_names = true;
 5272        cx.notify();
 5273        cx.spawn(|this, mut cx| async move {
 5274            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5275            this.update(&mut cx, |this, cx| {
 5276                this.show_cursor_names = false;
 5277                cx.notify()
 5278            })
 5279            .ok()
 5280        })
 5281        .detach();
 5282    }
 5283
 5284    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5285        if self.has_active_inline_completion(cx) {
 5286            self.cycle_inline_completion(Direction::Next, cx);
 5287        } else {
 5288            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5289            if is_copilot_disabled {
 5290                cx.propagate();
 5291            }
 5292        }
 5293    }
 5294
 5295    pub fn previous_inline_completion(
 5296        &mut self,
 5297        _: &PreviousInlineCompletion,
 5298        cx: &mut ViewContext<Self>,
 5299    ) {
 5300        if self.has_active_inline_completion(cx) {
 5301            self.cycle_inline_completion(Direction::Prev, cx);
 5302        } else {
 5303            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5304            if is_copilot_disabled {
 5305                cx.propagate();
 5306            }
 5307        }
 5308    }
 5309
 5310    pub fn accept_inline_completion(
 5311        &mut self,
 5312        _: &AcceptInlineCompletion,
 5313        cx: &mut ViewContext<Self>,
 5314    ) {
 5315        let Some(completion) = self.take_active_inline_completion(cx) else {
 5316            return;
 5317        };
 5318        if let Some(provider) = self.inline_completion_provider() {
 5319            provider.accept(cx);
 5320        }
 5321
 5322        cx.emit(EditorEvent::InputHandled {
 5323            utf16_range_to_replace: None,
 5324            text: completion.text.to_string().into(),
 5325        });
 5326
 5327        if let Some(range) = completion.delete_range {
 5328            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5329        }
 5330        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5331        self.refresh_inline_completion(true, true, cx);
 5332        cx.notify();
 5333    }
 5334
 5335    pub fn accept_partial_inline_completion(
 5336        &mut self,
 5337        _: &AcceptPartialInlineCompletion,
 5338        cx: &mut ViewContext<Self>,
 5339    ) {
 5340        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5341            if let Some(completion) = self.take_active_inline_completion(cx) {
 5342                let mut partial_completion = completion
 5343                    .text
 5344                    .chars()
 5345                    .by_ref()
 5346                    .take_while(|c| c.is_alphabetic())
 5347                    .collect::<String>();
 5348                if partial_completion.is_empty() {
 5349                    partial_completion = completion
 5350                        .text
 5351                        .chars()
 5352                        .by_ref()
 5353                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5354                        .collect::<String>();
 5355                }
 5356
 5357                cx.emit(EditorEvent::InputHandled {
 5358                    utf16_range_to_replace: None,
 5359                    text: partial_completion.clone().into(),
 5360                });
 5361
 5362                if let Some(range) = completion.delete_range {
 5363                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5364                }
 5365                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5366
 5367                self.refresh_inline_completion(true, true, cx);
 5368                cx.notify();
 5369            }
 5370        }
 5371    }
 5372
 5373    fn discard_inline_completion(
 5374        &mut self,
 5375        should_report_inline_completion_event: bool,
 5376        cx: &mut ViewContext<Self>,
 5377    ) -> bool {
 5378        if let Some(provider) = self.inline_completion_provider() {
 5379            provider.discard(should_report_inline_completion_event, cx);
 5380        }
 5381
 5382        self.take_active_inline_completion(cx).is_some()
 5383    }
 5384
 5385    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5386        if let Some(completion) = self.active_inline_completion.as_ref() {
 5387            let buffer = self.buffer.read(cx).read(cx);
 5388            completion.position.is_valid(&buffer)
 5389        } else {
 5390            false
 5391        }
 5392    }
 5393
 5394    fn take_active_inline_completion(
 5395        &mut self,
 5396        cx: &mut ViewContext<Self>,
 5397    ) -> Option<CompletionState> {
 5398        let completion = self.active_inline_completion.take()?;
 5399        let render_inlay_ids = completion.render_inlay_ids.clone();
 5400        self.display_map.update(cx, |map, cx| {
 5401            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5402        });
 5403        let buffer = self.buffer.read(cx).read(cx);
 5404
 5405        if completion.position.is_valid(&buffer) {
 5406            Some(completion)
 5407        } else {
 5408            None
 5409        }
 5410    }
 5411
 5412    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5413        let selection = self.selections.newest_anchor();
 5414        let cursor = selection.head();
 5415
 5416        let excerpt_id = cursor.excerpt_id;
 5417
 5418        if self.context_menu.read().is_none()
 5419            && self.completion_tasks.is_empty()
 5420            && selection.start == selection.end
 5421        {
 5422            if let Some(provider) = self.inline_completion_provider() {
 5423                if let Some((buffer, cursor_buffer_position)) =
 5424                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5425                {
 5426                    if let Some(proposal) =
 5427                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5428                    {
 5429                        let mut to_remove = Vec::new();
 5430                        if let Some(completion) = self.active_inline_completion.take() {
 5431                            to_remove.extend(completion.render_inlay_ids.iter());
 5432                        }
 5433
 5434                        let to_add = proposal
 5435                            .inlays
 5436                            .iter()
 5437                            .filter_map(|inlay| {
 5438                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5439                                let id = post_inc(&mut self.next_inlay_id);
 5440                                match inlay {
 5441                                    InlayProposal::Hint(position, hint) => {
 5442                                        let position =
 5443                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5444                                        Some(Inlay::hint(id, position, hint))
 5445                                    }
 5446                                    InlayProposal::Suggestion(position, text) => {
 5447                                        let position =
 5448                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5449                                        Some(Inlay::suggestion(id, position, text.clone()))
 5450                                    }
 5451                                }
 5452                            })
 5453                            .collect_vec();
 5454
 5455                        self.active_inline_completion = Some(CompletionState {
 5456                            position: cursor,
 5457                            text: proposal.text,
 5458                            delete_range: proposal.delete_range.and_then(|range| {
 5459                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5460                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5461                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5462                                Some(start?..end?)
 5463                            }),
 5464                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5465                        });
 5466
 5467                        self.display_map
 5468                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5469
 5470                        cx.notify();
 5471                        return;
 5472                    }
 5473                }
 5474            }
 5475        }
 5476
 5477        self.discard_inline_completion(false, cx);
 5478    }
 5479
 5480    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5481        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5482    }
 5483
 5484    fn render_code_actions_indicator(
 5485        &self,
 5486        _style: &EditorStyle,
 5487        row: DisplayRow,
 5488        is_active: bool,
 5489        cx: &mut ViewContext<Self>,
 5490    ) -> Option<IconButton> {
 5491        if self.available_code_actions.is_some() {
 5492            Some(
 5493                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5494                    .shape(ui::IconButtonShape::Square)
 5495                    .icon_size(IconSize::XSmall)
 5496                    .icon_color(Color::Muted)
 5497                    .selected(is_active)
 5498                    .tooltip({
 5499                        let focus_handle = self.focus_handle.clone();
 5500                        move |cx| {
 5501                            Tooltip::for_action_in(
 5502                                "Toggle Code Actions",
 5503                                &ToggleCodeActions {
 5504                                    deployed_from_indicator: None,
 5505                                },
 5506                                &focus_handle,
 5507                                cx,
 5508                            )
 5509                        }
 5510                    })
 5511                    .on_click(cx.listener(move |editor, _e, cx| {
 5512                        editor.focus(cx);
 5513                        editor.toggle_code_actions(
 5514                            &ToggleCodeActions {
 5515                                deployed_from_indicator: Some(row),
 5516                            },
 5517                            cx,
 5518                        );
 5519                    })),
 5520            )
 5521        } else {
 5522            None
 5523        }
 5524    }
 5525
 5526    fn clear_tasks(&mut self) {
 5527        self.tasks.clear()
 5528    }
 5529
 5530    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5531        if self.tasks.insert(key, value).is_some() {
 5532            // This case should hopefully be rare, but just in case...
 5533            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5534        }
 5535    }
 5536
 5537    fn build_tasks_context(
 5538        project: &Model<Project>,
 5539        buffer: &Model<Buffer>,
 5540        buffer_row: u32,
 5541        tasks: &Arc<RunnableTasks>,
 5542        cx: &mut ViewContext<Self>,
 5543    ) -> Task<Option<task::TaskContext>> {
 5544        let position = Point::new(buffer_row, tasks.column);
 5545        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5546        let location = Location {
 5547            buffer: buffer.clone(),
 5548            range: range_start..range_start,
 5549        };
 5550        // Fill in the environmental variables from the tree-sitter captures
 5551        let mut captured_task_variables = TaskVariables::default();
 5552        for (capture_name, value) in tasks.extra_variables.clone() {
 5553            captured_task_variables.insert(
 5554                task::VariableName::Custom(capture_name.into()),
 5555                value.clone(),
 5556            );
 5557        }
 5558        project.update(cx, |project, cx| {
 5559            project.task_store().update(cx, |task_store, cx| {
 5560                task_store.task_context_for_location(captured_task_variables, location, cx)
 5561            })
 5562        })
 5563    }
 5564
 5565    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5566        let Some((workspace, _)) = self.workspace.clone() else {
 5567            return;
 5568        };
 5569        let Some(project) = self.project.clone() else {
 5570            return;
 5571        };
 5572
 5573        // Try to find a closest, enclosing node using tree-sitter that has a
 5574        // task
 5575        let Some((buffer, buffer_row, tasks)) = self
 5576            .find_enclosing_node_task(cx)
 5577            // Or find the task that's closest in row-distance.
 5578            .or_else(|| self.find_closest_task(cx))
 5579        else {
 5580            return;
 5581        };
 5582
 5583        let reveal_strategy = action.reveal;
 5584        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5585        cx.spawn(|_, mut cx| async move {
 5586            let context = task_context.await?;
 5587            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5588
 5589            let resolved = resolved_task.resolved.as_mut()?;
 5590            resolved.reveal = reveal_strategy;
 5591
 5592            workspace
 5593                .update(&mut cx, |workspace, cx| {
 5594                    workspace::tasks::schedule_resolved_task(
 5595                        workspace,
 5596                        task_source_kind,
 5597                        resolved_task,
 5598                        false,
 5599                        cx,
 5600                    );
 5601                })
 5602                .ok()
 5603        })
 5604        .detach();
 5605    }
 5606
 5607    fn find_closest_task(
 5608        &mut self,
 5609        cx: &mut ViewContext<Self>,
 5610    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5611        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5612
 5613        let ((buffer_id, row), tasks) = self
 5614            .tasks
 5615            .iter()
 5616            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5617
 5618        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5619        let tasks = Arc::new(tasks.to_owned());
 5620        Some((buffer, *row, tasks))
 5621    }
 5622
 5623    fn find_enclosing_node_task(
 5624        &mut self,
 5625        cx: &mut ViewContext<Self>,
 5626    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5627        let snapshot = self.buffer.read(cx).snapshot(cx);
 5628        let offset = self.selections.newest::<usize>(cx).head();
 5629        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5630        let buffer_id = excerpt.buffer().remote_id();
 5631
 5632        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5633        let mut cursor = layer.node().walk();
 5634
 5635        while cursor.goto_first_child_for_byte(offset).is_some() {
 5636            if cursor.node().end_byte() == offset {
 5637                cursor.goto_next_sibling();
 5638            }
 5639        }
 5640
 5641        // Ascend to the smallest ancestor that contains the range and has a task.
 5642        loop {
 5643            let node = cursor.node();
 5644            let node_range = node.byte_range();
 5645            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5646
 5647            // Check if this node contains our offset
 5648            if node_range.start <= offset && node_range.end >= offset {
 5649                // If it contains offset, check for task
 5650                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5651                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5652                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5653                }
 5654            }
 5655
 5656            if !cursor.goto_parent() {
 5657                break;
 5658            }
 5659        }
 5660        None
 5661    }
 5662
 5663    fn render_run_indicator(
 5664        &self,
 5665        _style: &EditorStyle,
 5666        is_active: bool,
 5667        row: DisplayRow,
 5668        cx: &mut ViewContext<Self>,
 5669    ) -> IconButton {
 5670        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5671            .shape(ui::IconButtonShape::Square)
 5672            .icon_size(IconSize::XSmall)
 5673            .icon_color(Color::Muted)
 5674            .selected(is_active)
 5675            .on_click(cx.listener(move |editor, _e, cx| {
 5676                editor.focus(cx);
 5677                editor.toggle_code_actions(
 5678                    &ToggleCodeActions {
 5679                        deployed_from_indicator: Some(row),
 5680                    },
 5681                    cx,
 5682                );
 5683            }))
 5684    }
 5685
 5686    pub fn context_menu_visible(&self) -> bool {
 5687        self.context_menu
 5688            .read()
 5689            .as_ref()
 5690            .map_or(false, |menu| menu.visible())
 5691    }
 5692
 5693    fn render_context_menu(
 5694        &self,
 5695        cursor_position: DisplayPoint,
 5696        style: &EditorStyle,
 5697        max_height: Pixels,
 5698        cx: &mut ViewContext<Editor>,
 5699    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5700        self.context_menu.read().as_ref().map(|menu| {
 5701            menu.render(
 5702                cursor_position,
 5703                style,
 5704                max_height,
 5705                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5706                cx,
 5707            )
 5708        })
 5709    }
 5710
 5711    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5712        cx.notify();
 5713        self.completion_tasks.clear();
 5714        let context_menu = self.context_menu.write().take();
 5715        if context_menu.is_some() {
 5716            self.update_visible_inline_completion(cx);
 5717        }
 5718        context_menu
 5719    }
 5720
 5721    fn show_snippet_choices(
 5722        &mut self,
 5723        choices: &Vec<String>,
 5724        selection: Range<Anchor>,
 5725        cx: &mut ViewContext<Self>,
 5726    ) {
 5727        if selection.start.buffer_id.is_none() {
 5728            return;
 5729        }
 5730        let buffer_id = selection.start.buffer_id.unwrap();
 5731        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5732        let id = post_inc(&mut self.next_completion_id);
 5733
 5734        if let Some(buffer) = buffer {
 5735            *self.context_menu.write() = Some(ContextMenu::Completions(
 5736                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
 5737                    .suppress_documentation_resolution(),
 5738            ));
 5739        }
 5740    }
 5741
 5742    pub fn insert_snippet(
 5743        &mut self,
 5744        insertion_ranges: &[Range<usize>],
 5745        snippet: Snippet,
 5746        cx: &mut ViewContext<Self>,
 5747    ) -> Result<()> {
 5748        struct Tabstop<T> {
 5749            is_end_tabstop: bool,
 5750            ranges: Vec<Range<T>>,
 5751            choices: Option<Vec<String>>,
 5752        }
 5753
 5754        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5755            let snippet_text: Arc<str> = snippet.text.clone().into();
 5756            buffer.edit(
 5757                insertion_ranges
 5758                    .iter()
 5759                    .cloned()
 5760                    .map(|range| (range, snippet_text.clone())),
 5761                Some(AutoindentMode::EachLine),
 5762                cx,
 5763            );
 5764
 5765            let snapshot = &*buffer.read(cx);
 5766            let snippet = &snippet;
 5767            snippet
 5768                .tabstops
 5769                .iter()
 5770                .map(|tabstop| {
 5771                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5772                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5773                    });
 5774                    let mut tabstop_ranges = tabstop
 5775                        .ranges
 5776                        .iter()
 5777                        .flat_map(|tabstop_range| {
 5778                            let mut delta = 0_isize;
 5779                            insertion_ranges.iter().map(move |insertion_range| {
 5780                                let insertion_start = insertion_range.start as isize + delta;
 5781                                delta +=
 5782                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5783
 5784                                let start = ((insertion_start + tabstop_range.start) as usize)
 5785                                    .min(snapshot.len());
 5786                                let end = ((insertion_start + tabstop_range.end) as usize)
 5787                                    .min(snapshot.len());
 5788                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5789                            })
 5790                        })
 5791                        .collect::<Vec<_>>();
 5792                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5793
 5794                    Tabstop {
 5795                        is_end_tabstop,
 5796                        ranges: tabstop_ranges,
 5797                        choices: tabstop.choices.clone(),
 5798                    }
 5799                })
 5800                .collect::<Vec<_>>()
 5801        });
 5802        if let Some(tabstop) = tabstops.first() {
 5803            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5804                s.select_ranges(tabstop.ranges.iter().cloned());
 5805            });
 5806
 5807            if let Some(choices) = &tabstop.choices {
 5808                if let Some(selection) = tabstop.ranges.first() {
 5809                    self.show_snippet_choices(choices, selection.clone(), cx)
 5810                }
 5811            }
 5812
 5813            // If we're already at the last tabstop and it's at the end of the snippet,
 5814            // we're done, we don't need to keep the state around.
 5815            if !tabstop.is_end_tabstop {
 5816                let choices = tabstops
 5817                    .iter()
 5818                    .map(|tabstop| tabstop.choices.clone())
 5819                    .collect();
 5820
 5821                let ranges = tabstops
 5822                    .into_iter()
 5823                    .map(|tabstop| tabstop.ranges)
 5824                    .collect::<Vec<_>>();
 5825
 5826                self.snippet_stack.push(SnippetState {
 5827                    active_index: 0,
 5828                    ranges,
 5829                    choices,
 5830                });
 5831            }
 5832
 5833            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5834            if self.autoclose_regions.is_empty() {
 5835                let snapshot = self.buffer.read(cx).snapshot(cx);
 5836                for selection in &mut self.selections.all::<Point>(cx) {
 5837                    let selection_head = selection.head();
 5838                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5839                        continue;
 5840                    };
 5841
 5842                    let mut bracket_pair = None;
 5843                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5844                    let prev_chars = snapshot
 5845                        .reversed_chars_at(selection_head)
 5846                        .collect::<String>();
 5847                    for (pair, enabled) in scope.brackets() {
 5848                        if enabled
 5849                            && pair.close
 5850                            && prev_chars.starts_with(pair.start.as_str())
 5851                            && next_chars.starts_with(pair.end.as_str())
 5852                        {
 5853                            bracket_pair = Some(pair.clone());
 5854                            break;
 5855                        }
 5856                    }
 5857                    if let Some(pair) = bracket_pair {
 5858                        let start = snapshot.anchor_after(selection_head);
 5859                        let end = snapshot.anchor_after(selection_head);
 5860                        self.autoclose_regions.push(AutocloseRegion {
 5861                            selection_id: selection.id,
 5862                            range: start..end,
 5863                            pair,
 5864                        });
 5865                    }
 5866                }
 5867            }
 5868        }
 5869        Ok(())
 5870    }
 5871
 5872    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5873        self.move_to_snippet_tabstop(Bias::Right, cx)
 5874    }
 5875
 5876    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5877        self.move_to_snippet_tabstop(Bias::Left, cx)
 5878    }
 5879
 5880    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5881        if let Some(mut snippet) = self.snippet_stack.pop() {
 5882            match bias {
 5883                Bias::Left => {
 5884                    if snippet.active_index > 0 {
 5885                        snippet.active_index -= 1;
 5886                    } else {
 5887                        self.snippet_stack.push(snippet);
 5888                        return false;
 5889                    }
 5890                }
 5891                Bias::Right => {
 5892                    if snippet.active_index + 1 < snippet.ranges.len() {
 5893                        snippet.active_index += 1;
 5894                    } else {
 5895                        self.snippet_stack.push(snippet);
 5896                        return false;
 5897                    }
 5898                }
 5899            }
 5900            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5901                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5902                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5903                });
 5904
 5905                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5906                    if let Some(selection) = current_ranges.first() {
 5907                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5908                    }
 5909                }
 5910
 5911                // If snippet state is not at the last tabstop, push it back on the stack
 5912                if snippet.active_index + 1 < snippet.ranges.len() {
 5913                    self.snippet_stack.push(snippet);
 5914                }
 5915                return true;
 5916            }
 5917        }
 5918
 5919        false
 5920    }
 5921
 5922    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5923        self.transact(cx, |this, cx| {
 5924            this.select_all(&SelectAll, cx);
 5925            this.insert("", cx);
 5926        });
 5927    }
 5928
 5929    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5930        self.transact(cx, |this, cx| {
 5931            this.select_autoclose_pair(cx);
 5932            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5933            if !this.linked_edit_ranges.is_empty() {
 5934                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5935                let snapshot = this.buffer.read(cx).snapshot(cx);
 5936
 5937                for selection in selections.iter() {
 5938                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5939                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5940                    if selection_start.buffer_id != selection_end.buffer_id {
 5941                        continue;
 5942                    }
 5943                    if let Some(ranges) =
 5944                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5945                    {
 5946                        for (buffer, entries) in ranges {
 5947                            linked_ranges.entry(buffer).or_default().extend(entries);
 5948                        }
 5949                    }
 5950                }
 5951            }
 5952
 5953            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5954            if !this.selections.line_mode {
 5955                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5956                for selection in &mut selections {
 5957                    if selection.is_empty() {
 5958                        let old_head = selection.head();
 5959                        let mut new_head =
 5960                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5961                                .to_point(&display_map);
 5962                        if let Some((buffer, line_buffer_range)) = display_map
 5963                            .buffer_snapshot
 5964                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5965                        {
 5966                            let indent_size =
 5967                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5968                            let indent_len = match indent_size.kind {
 5969                                IndentKind::Space => {
 5970                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5971                                }
 5972                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5973                            };
 5974                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5975                                let indent_len = indent_len.get();
 5976                                new_head = cmp::min(
 5977                                    new_head,
 5978                                    MultiBufferPoint::new(
 5979                                        old_head.row,
 5980                                        ((old_head.column - 1) / indent_len) * indent_len,
 5981                                    ),
 5982                                );
 5983                            }
 5984                        }
 5985
 5986                        selection.set_head(new_head, SelectionGoal::None);
 5987                    }
 5988                }
 5989            }
 5990
 5991            this.signature_help_state.set_backspace_pressed(true);
 5992            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5993            this.insert("", cx);
 5994            let empty_str: Arc<str> = Arc::from("");
 5995            for (buffer, edits) in linked_ranges {
 5996                let snapshot = buffer.read(cx).snapshot();
 5997                use text::ToPoint as TP;
 5998
 5999                let edits = edits
 6000                    .into_iter()
 6001                    .map(|range| {
 6002                        let end_point = TP::to_point(&range.end, &snapshot);
 6003                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6004
 6005                        if end_point == start_point {
 6006                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6007                                .saturating_sub(1);
 6008                            start_point = TP::to_point(&offset, &snapshot);
 6009                        };
 6010
 6011                        (start_point..end_point, empty_str.clone())
 6012                    })
 6013                    .sorted_by_key(|(range, _)| range.start)
 6014                    .collect::<Vec<_>>();
 6015                buffer.update(cx, |this, cx| {
 6016                    this.edit(edits, None, cx);
 6017                })
 6018            }
 6019            this.refresh_inline_completion(true, false, cx);
 6020            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6021        });
 6022    }
 6023
 6024    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6025        self.transact(cx, |this, cx| {
 6026            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6027                let line_mode = s.line_mode;
 6028                s.move_with(|map, selection| {
 6029                    if selection.is_empty() && !line_mode {
 6030                        let cursor = movement::right(map, selection.head());
 6031                        selection.end = cursor;
 6032                        selection.reversed = true;
 6033                        selection.goal = SelectionGoal::None;
 6034                    }
 6035                })
 6036            });
 6037            this.insert("", cx);
 6038            this.refresh_inline_completion(true, false, cx);
 6039        });
 6040    }
 6041
 6042    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6043        if self.move_to_prev_snippet_tabstop(cx) {
 6044            return;
 6045        }
 6046
 6047        self.outdent(&Outdent, cx);
 6048    }
 6049
 6050    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6051        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6052            return;
 6053        }
 6054
 6055        let mut selections = self.selections.all_adjusted(cx);
 6056        let buffer = self.buffer.read(cx);
 6057        let snapshot = buffer.snapshot(cx);
 6058        let rows_iter = selections.iter().map(|s| s.head().row);
 6059        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6060
 6061        let mut edits = Vec::new();
 6062        let mut prev_edited_row = 0;
 6063        let mut row_delta = 0;
 6064        for selection in &mut selections {
 6065            if selection.start.row != prev_edited_row {
 6066                row_delta = 0;
 6067            }
 6068            prev_edited_row = selection.end.row;
 6069
 6070            // If the selection is non-empty, then increase the indentation of the selected lines.
 6071            if !selection.is_empty() {
 6072                row_delta =
 6073                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6074                continue;
 6075            }
 6076
 6077            // If the selection is empty and the cursor is in the leading whitespace before the
 6078            // suggested indentation, then auto-indent the line.
 6079            let cursor = selection.head();
 6080            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6081            if let Some(suggested_indent) =
 6082                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6083            {
 6084                if cursor.column < suggested_indent.len
 6085                    && cursor.column <= current_indent.len
 6086                    && current_indent.len <= suggested_indent.len
 6087                {
 6088                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6089                    selection.end = selection.start;
 6090                    if row_delta == 0 {
 6091                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6092                            cursor.row,
 6093                            current_indent,
 6094                            suggested_indent,
 6095                        ));
 6096                        row_delta = suggested_indent.len - current_indent.len;
 6097                    }
 6098                    continue;
 6099                }
 6100            }
 6101
 6102            // Otherwise, insert a hard or soft tab.
 6103            let settings = buffer.settings_at(cursor, cx);
 6104            let tab_size = if settings.hard_tabs {
 6105                IndentSize::tab()
 6106            } else {
 6107                let tab_size = settings.tab_size.get();
 6108                let char_column = snapshot
 6109                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6110                    .flat_map(str::chars)
 6111                    .count()
 6112                    + row_delta as usize;
 6113                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6114                IndentSize::spaces(chars_to_next_tab_stop)
 6115            };
 6116            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6117            selection.end = selection.start;
 6118            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6119            row_delta += tab_size.len;
 6120        }
 6121
 6122        self.transact(cx, |this, cx| {
 6123            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6124            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6125            this.refresh_inline_completion(true, false, cx);
 6126        });
 6127    }
 6128
 6129    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6130        if self.read_only(cx) {
 6131            return;
 6132        }
 6133        let mut selections = self.selections.all::<Point>(cx);
 6134        let mut prev_edited_row = 0;
 6135        let mut row_delta = 0;
 6136        let mut edits = Vec::new();
 6137        let buffer = self.buffer.read(cx);
 6138        let snapshot = buffer.snapshot(cx);
 6139        for selection in &mut selections {
 6140            if selection.start.row != prev_edited_row {
 6141                row_delta = 0;
 6142            }
 6143            prev_edited_row = selection.end.row;
 6144
 6145            row_delta =
 6146                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6147        }
 6148
 6149        self.transact(cx, |this, cx| {
 6150            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6151            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6152        });
 6153    }
 6154
 6155    fn indent_selection(
 6156        buffer: &MultiBuffer,
 6157        snapshot: &MultiBufferSnapshot,
 6158        selection: &mut Selection<Point>,
 6159        edits: &mut Vec<(Range<Point>, String)>,
 6160        delta_for_start_row: u32,
 6161        cx: &AppContext,
 6162    ) -> u32 {
 6163        let settings = buffer.settings_at(selection.start, cx);
 6164        let tab_size = settings.tab_size.get();
 6165        let indent_kind = if settings.hard_tabs {
 6166            IndentKind::Tab
 6167        } else {
 6168            IndentKind::Space
 6169        };
 6170        let mut start_row = selection.start.row;
 6171        let mut end_row = selection.end.row + 1;
 6172
 6173        // If a selection ends at the beginning of a line, don't indent
 6174        // that last line.
 6175        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6176            end_row -= 1;
 6177        }
 6178
 6179        // Avoid re-indenting a row that has already been indented by a
 6180        // previous selection, but still update this selection's column
 6181        // to reflect that indentation.
 6182        if delta_for_start_row > 0 {
 6183            start_row += 1;
 6184            selection.start.column += delta_for_start_row;
 6185            if selection.end.row == selection.start.row {
 6186                selection.end.column += delta_for_start_row;
 6187            }
 6188        }
 6189
 6190        let mut delta_for_end_row = 0;
 6191        let has_multiple_rows = start_row + 1 != end_row;
 6192        for row in start_row..end_row {
 6193            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6194            let indent_delta = match (current_indent.kind, indent_kind) {
 6195                (IndentKind::Space, IndentKind::Space) => {
 6196                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6197                    IndentSize::spaces(columns_to_next_tab_stop)
 6198                }
 6199                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6200                (_, IndentKind::Tab) => IndentSize::tab(),
 6201            };
 6202
 6203            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6204                0
 6205            } else {
 6206                selection.start.column
 6207            };
 6208            let row_start = Point::new(row, start);
 6209            edits.push((
 6210                row_start..row_start,
 6211                indent_delta.chars().collect::<String>(),
 6212            ));
 6213
 6214            // Update this selection's endpoints to reflect the indentation.
 6215            if row == selection.start.row {
 6216                selection.start.column += indent_delta.len;
 6217            }
 6218            if row == selection.end.row {
 6219                selection.end.column += indent_delta.len;
 6220                delta_for_end_row = indent_delta.len;
 6221            }
 6222        }
 6223
 6224        if selection.start.row == selection.end.row {
 6225            delta_for_start_row + delta_for_end_row
 6226        } else {
 6227            delta_for_end_row
 6228        }
 6229    }
 6230
 6231    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6232        if self.read_only(cx) {
 6233            return;
 6234        }
 6235        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6236        let selections = self.selections.all::<Point>(cx);
 6237        let mut deletion_ranges = Vec::new();
 6238        let mut last_outdent = None;
 6239        {
 6240            let buffer = self.buffer.read(cx);
 6241            let snapshot = buffer.snapshot(cx);
 6242            for selection in &selections {
 6243                let settings = buffer.settings_at(selection.start, cx);
 6244                let tab_size = settings.tab_size.get();
 6245                let mut rows = selection.spanned_rows(false, &display_map);
 6246
 6247                // Avoid re-outdenting a row that has already been outdented by a
 6248                // previous selection.
 6249                if let Some(last_row) = last_outdent {
 6250                    if last_row == rows.start {
 6251                        rows.start = rows.start.next_row();
 6252                    }
 6253                }
 6254                let has_multiple_rows = rows.len() > 1;
 6255                for row in rows.iter_rows() {
 6256                    let indent_size = snapshot.indent_size_for_line(row);
 6257                    if indent_size.len > 0 {
 6258                        let deletion_len = match indent_size.kind {
 6259                            IndentKind::Space => {
 6260                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6261                                if columns_to_prev_tab_stop == 0 {
 6262                                    tab_size
 6263                                } else {
 6264                                    columns_to_prev_tab_stop
 6265                                }
 6266                            }
 6267                            IndentKind::Tab => 1,
 6268                        };
 6269                        let start = if has_multiple_rows
 6270                            || deletion_len > selection.start.column
 6271                            || indent_size.len < selection.start.column
 6272                        {
 6273                            0
 6274                        } else {
 6275                            selection.start.column - deletion_len
 6276                        };
 6277                        deletion_ranges.push(
 6278                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6279                        );
 6280                        last_outdent = Some(row);
 6281                    }
 6282                }
 6283            }
 6284        }
 6285
 6286        self.transact(cx, |this, cx| {
 6287            this.buffer.update(cx, |buffer, cx| {
 6288                let empty_str: Arc<str> = Arc::default();
 6289                buffer.edit(
 6290                    deletion_ranges
 6291                        .into_iter()
 6292                        .map(|range| (range, empty_str.clone())),
 6293                    None,
 6294                    cx,
 6295                );
 6296            });
 6297            let selections = this.selections.all::<usize>(cx);
 6298            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6299        });
 6300    }
 6301
 6302    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 6303        if self.read_only(cx) {
 6304            return;
 6305        }
 6306        let selections = self
 6307            .selections
 6308            .all::<usize>(cx)
 6309            .into_iter()
 6310            .map(|s| s.range());
 6311
 6312        self.transact(cx, |this, cx| {
 6313            this.buffer.update(cx, |buffer, cx| {
 6314                buffer.autoindent_ranges(selections, cx);
 6315            });
 6316            let selections = this.selections.all::<usize>(cx);
 6317            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6318        });
 6319    }
 6320
 6321    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6322        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6323        let selections = self.selections.all::<Point>(cx);
 6324
 6325        let mut new_cursors = Vec::new();
 6326        let mut edit_ranges = Vec::new();
 6327        let mut selections = selections.iter().peekable();
 6328        while let Some(selection) = selections.next() {
 6329            let mut rows = selection.spanned_rows(false, &display_map);
 6330            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6331
 6332            // Accumulate contiguous regions of rows that we want to delete.
 6333            while let Some(next_selection) = selections.peek() {
 6334                let next_rows = next_selection.spanned_rows(false, &display_map);
 6335                if next_rows.start <= rows.end {
 6336                    rows.end = next_rows.end;
 6337                    selections.next().unwrap();
 6338                } else {
 6339                    break;
 6340                }
 6341            }
 6342
 6343            let buffer = &display_map.buffer_snapshot;
 6344            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6345            let edit_end;
 6346            let cursor_buffer_row;
 6347            if buffer.max_point().row >= rows.end.0 {
 6348                // If there's a line after the range, delete the \n from the end of the row range
 6349                // and position the cursor on the next line.
 6350                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6351                cursor_buffer_row = rows.end;
 6352            } else {
 6353                // If there isn't a line after the range, delete the \n from the line before the
 6354                // start of the row range and position the cursor there.
 6355                edit_start = edit_start.saturating_sub(1);
 6356                edit_end = buffer.len();
 6357                cursor_buffer_row = rows.start.previous_row();
 6358            }
 6359
 6360            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6361            *cursor.column_mut() =
 6362                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6363
 6364            new_cursors.push((
 6365                selection.id,
 6366                buffer.anchor_after(cursor.to_point(&display_map)),
 6367            ));
 6368            edit_ranges.push(edit_start..edit_end);
 6369        }
 6370
 6371        self.transact(cx, |this, cx| {
 6372            let buffer = this.buffer.update(cx, |buffer, cx| {
 6373                let empty_str: Arc<str> = Arc::default();
 6374                buffer.edit(
 6375                    edit_ranges
 6376                        .into_iter()
 6377                        .map(|range| (range, empty_str.clone())),
 6378                    None,
 6379                    cx,
 6380                );
 6381                buffer.snapshot(cx)
 6382            });
 6383            let new_selections = new_cursors
 6384                .into_iter()
 6385                .map(|(id, cursor)| {
 6386                    let cursor = cursor.to_point(&buffer);
 6387                    Selection {
 6388                        id,
 6389                        start: cursor,
 6390                        end: cursor,
 6391                        reversed: false,
 6392                        goal: SelectionGoal::None,
 6393                    }
 6394                })
 6395                .collect();
 6396
 6397            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6398                s.select(new_selections);
 6399            });
 6400        });
 6401    }
 6402
 6403    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6404        if self.read_only(cx) {
 6405            return;
 6406        }
 6407        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6408        for selection in self.selections.all::<Point>(cx) {
 6409            let start = MultiBufferRow(selection.start.row);
 6410            // Treat single line selections as if they include the next line. Otherwise this action
 6411            // would do nothing for single line selections individual cursors.
 6412            let end = if selection.start.row == selection.end.row {
 6413                MultiBufferRow(selection.start.row + 1)
 6414            } else {
 6415                MultiBufferRow(selection.end.row)
 6416            };
 6417
 6418            if let Some(last_row_range) = row_ranges.last_mut() {
 6419                if start <= last_row_range.end {
 6420                    last_row_range.end = end;
 6421                    continue;
 6422                }
 6423            }
 6424            row_ranges.push(start..end);
 6425        }
 6426
 6427        let snapshot = self.buffer.read(cx).snapshot(cx);
 6428        let mut cursor_positions = Vec::new();
 6429        for row_range in &row_ranges {
 6430            let anchor = snapshot.anchor_before(Point::new(
 6431                row_range.end.previous_row().0,
 6432                snapshot.line_len(row_range.end.previous_row()),
 6433            ));
 6434            cursor_positions.push(anchor..anchor);
 6435        }
 6436
 6437        self.transact(cx, |this, cx| {
 6438            for row_range in row_ranges.into_iter().rev() {
 6439                for row in row_range.iter_rows().rev() {
 6440                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6441                    let next_line_row = row.next_row();
 6442                    let indent = snapshot.indent_size_for_line(next_line_row);
 6443                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6444
 6445                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6446                        " "
 6447                    } else {
 6448                        ""
 6449                    };
 6450
 6451                    this.buffer.update(cx, |buffer, cx| {
 6452                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6453                    });
 6454                }
 6455            }
 6456
 6457            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6458                s.select_anchor_ranges(cursor_positions)
 6459            });
 6460        });
 6461    }
 6462
 6463    pub fn sort_lines_case_sensitive(
 6464        &mut self,
 6465        _: &SortLinesCaseSensitive,
 6466        cx: &mut ViewContext<Self>,
 6467    ) {
 6468        self.manipulate_lines(cx, |lines| lines.sort())
 6469    }
 6470
 6471    pub fn sort_lines_case_insensitive(
 6472        &mut self,
 6473        _: &SortLinesCaseInsensitive,
 6474        cx: &mut ViewContext<Self>,
 6475    ) {
 6476        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6477    }
 6478
 6479    pub fn unique_lines_case_insensitive(
 6480        &mut self,
 6481        _: &UniqueLinesCaseInsensitive,
 6482        cx: &mut ViewContext<Self>,
 6483    ) {
 6484        self.manipulate_lines(cx, |lines| {
 6485            let mut seen = HashSet::default();
 6486            lines.retain(|line| seen.insert(line.to_lowercase()));
 6487        })
 6488    }
 6489
 6490    pub fn unique_lines_case_sensitive(
 6491        &mut self,
 6492        _: &UniqueLinesCaseSensitive,
 6493        cx: &mut ViewContext<Self>,
 6494    ) {
 6495        self.manipulate_lines(cx, |lines| {
 6496            let mut seen = HashSet::default();
 6497            lines.retain(|line| seen.insert(*line));
 6498        })
 6499    }
 6500
 6501    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6502        let mut revert_changes = HashMap::default();
 6503        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6504        for hunk in hunks_for_rows(
 6505            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_row()).into_iter(),
 6506            &multi_buffer_snapshot,
 6507        ) {
 6508            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6509        }
 6510        if !revert_changes.is_empty() {
 6511            self.transact(cx, |editor, cx| {
 6512                editor.revert(revert_changes, cx);
 6513            });
 6514        }
 6515    }
 6516
 6517    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6518        let Some(project) = self.project.clone() else {
 6519            return;
 6520        };
 6521        self.reload(project, cx).detach_and_notify_err(cx);
 6522    }
 6523
 6524    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6525        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6526        if !revert_changes.is_empty() {
 6527            self.transact(cx, |editor, cx| {
 6528                editor.revert(revert_changes, cx);
 6529            });
 6530        }
 6531    }
 6532
 6533    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6534        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6535            let project_path = buffer.read(cx).project_path(cx)?;
 6536            let project = self.project.as_ref()?.read(cx);
 6537            let entry = project.entry_for_path(&project_path, cx)?;
 6538            let parent = match &entry.canonical_path {
 6539                Some(canonical_path) => canonical_path.to_path_buf(),
 6540                None => project.absolute_path(&project_path, cx)?,
 6541            }
 6542            .parent()?
 6543            .to_path_buf();
 6544            Some(parent)
 6545        }) {
 6546            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6547        }
 6548    }
 6549
 6550    fn gather_revert_changes(
 6551        &mut self,
 6552        selections: &[Selection<Anchor>],
 6553        cx: &mut ViewContext<'_, Editor>,
 6554    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6555        let mut revert_changes = HashMap::default();
 6556        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6557        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6558            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6559        }
 6560        revert_changes
 6561    }
 6562
 6563    pub fn prepare_revert_change(
 6564        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6565        multi_buffer: &Model<MultiBuffer>,
 6566        hunk: &MultiBufferDiffHunk,
 6567        cx: &AppContext,
 6568    ) -> Option<()> {
 6569        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6570        let buffer = buffer.read(cx);
 6571        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6572        let buffer_snapshot = buffer.snapshot();
 6573        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6574        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6575            probe
 6576                .0
 6577                .start
 6578                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6579                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6580        }) {
 6581            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6582            Some(())
 6583        } else {
 6584            None
 6585        }
 6586    }
 6587
 6588    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6589        self.manipulate_lines(cx, |lines| lines.reverse())
 6590    }
 6591
 6592    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6593        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6594    }
 6595
 6596    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6597    where
 6598        Fn: FnMut(&mut Vec<&str>),
 6599    {
 6600        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6601        let buffer = self.buffer.read(cx).snapshot(cx);
 6602
 6603        let mut edits = Vec::new();
 6604
 6605        let selections = self.selections.all::<Point>(cx);
 6606        let mut selections = selections.iter().peekable();
 6607        let mut contiguous_row_selections = Vec::new();
 6608        let mut new_selections = Vec::new();
 6609        let mut added_lines = 0;
 6610        let mut removed_lines = 0;
 6611
 6612        while let Some(selection) = selections.next() {
 6613            let (start_row, end_row) = consume_contiguous_rows(
 6614                &mut contiguous_row_selections,
 6615                selection,
 6616                &display_map,
 6617                &mut selections,
 6618            );
 6619
 6620            let start_point = Point::new(start_row.0, 0);
 6621            let end_point = Point::new(
 6622                end_row.previous_row().0,
 6623                buffer.line_len(end_row.previous_row()),
 6624            );
 6625            let text = buffer
 6626                .text_for_range(start_point..end_point)
 6627                .collect::<String>();
 6628
 6629            let mut lines = text.split('\n').collect_vec();
 6630
 6631            let lines_before = lines.len();
 6632            callback(&mut lines);
 6633            let lines_after = lines.len();
 6634
 6635            edits.push((start_point..end_point, lines.join("\n")));
 6636
 6637            // Selections must change based on added and removed line count
 6638            let start_row =
 6639                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6640            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6641            new_selections.push(Selection {
 6642                id: selection.id,
 6643                start: start_row,
 6644                end: end_row,
 6645                goal: SelectionGoal::None,
 6646                reversed: selection.reversed,
 6647            });
 6648
 6649            if lines_after > lines_before {
 6650                added_lines += lines_after - lines_before;
 6651            } else if lines_before > lines_after {
 6652                removed_lines += lines_before - lines_after;
 6653            }
 6654        }
 6655
 6656        self.transact(cx, |this, cx| {
 6657            let buffer = this.buffer.update(cx, |buffer, cx| {
 6658                buffer.edit(edits, None, cx);
 6659                buffer.snapshot(cx)
 6660            });
 6661
 6662            // Recalculate offsets on newly edited buffer
 6663            let new_selections = new_selections
 6664                .iter()
 6665                .map(|s| {
 6666                    let start_point = Point::new(s.start.0, 0);
 6667                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6668                    Selection {
 6669                        id: s.id,
 6670                        start: buffer.point_to_offset(start_point),
 6671                        end: buffer.point_to_offset(end_point),
 6672                        goal: s.goal,
 6673                        reversed: s.reversed,
 6674                    }
 6675                })
 6676                .collect();
 6677
 6678            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6679                s.select(new_selections);
 6680            });
 6681
 6682            this.request_autoscroll(Autoscroll::fit(), cx);
 6683        });
 6684    }
 6685
 6686    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6687        self.manipulate_text(cx, |text| text.to_uppercase())
 6688    }
 6689
 6690    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6691        self.manipulate_text(cx, |text| text.to_lowercase())
 6692    }
 6693
 6694    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6695        self.manipulate_text(cx, |text| {
 6696            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6697            // https://github.com/rutrum/convert-case/issues/16
 6698            text.split('\n')
 6699                .map(|line| line.to_case(Case::Title))
 6700                .join("\n")
 6701        })
 6702    }
 6703
 6704    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6705        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6706    }
 6707
 6708    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6709        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6710    }
 6711
 6712    pub fn convert_to_upper_camel_case(
 6713        &mut self,
 6714        _: &ConvertToUpperCamelCase,
 6715        cx: &mut ViewContext<Self>,
 6716    ) {
 6717        self.manipulate_text(cx, |text| {
 6718            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6719            // https://github.com/rutrum/convert-case/issues/16
 6720            text.split('\n')
 6721                .map(|line| line.to_case(Case::UpperCamel))
 6722                .join("\n")
 6723        })
 6724    }
 6725
 6726    pub fn convert_to_lower_camel_case(
 6727        &mut self,
 6728        _: &ConvertToLowerCamelCase,
 6729        cx: &mut ViewContext<Self>,
 6730    ) {
 6731        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6732    }
 6733
 6734    pub fn convert_to_opposite_case(
 6735        &mut self,
 6736        _: &ConvertToOppositeCase,
 6737        cx: &mut ViewContext<Self>,
 6738    ) {
 6739        self.manipulate_text(cx, |text| {
 6740            text.chars()
 6741                .fold(String::with_capacity(text.len()), |mut t, c| {
 6742                    if c.is_uppercase() {
 6743                        t.extend(c.to_lowercase());
 6744                    } else {
 6745                        t.extend(c.to_uppercase());
 6746                    }
 6747                    t
 6748                })
 6749        })
 6750    }
 6751
 6752    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6753    where
 6754        Fn: FnMut(&str) -> String,
 6755    {
 6756        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6757        let buffer = self.buffer.read(cx).snapshot(cx);
 6758
 6759        let mut new_selections = Vec::new();
 6760        let mut edits = Vec::new();
 6761        let mut selection_adjustment = 0i32;
 6762
 6763        for selection in self.selections.all::<usize>(cx) {
 6764            let selection_is_empty = selection.is_empty();
 6765
 6766            let (start, end) = if selection_is_empty {
 6767                let word_range = movement::surrounding_word(
 6768                    &display_map,
 6769                    selection.start.to_display_point(&display_map),
 6770                );
 6771                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6772                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6773                (start, end)
 6774            } else {
 6775                (selection.start, selection.end)
 6776            };
 6777
 6778            let text = buffer.text_for_range(start..end).collect::<String>();
 6779            let old_length = text.len() as i32;
 6780            let text = callback(&text);
 6781
 6782            new_selections.push(Selection {
 6783                start: (start as i32 - selection_adjustment) as usize,
 6784                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6785                goal: SelectionGoal::None,
 6786                ..selection
 6787            });
 6788
 6789            selection_adjustment += old_length - text.len() as i32;
 6790
 6791            edits.push((start..end, text));
 6792        }
 6793
 6794        self.transact(cx, |this, cx| {
 6795            this.buffer.update(cx, |buffer, cx| {
 6796                buffer.edit(edits, None, cx);
 6797            });
 6798
 6799            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6800                s.select(new_selections);
 6801            });
 6802
 6803            this.request_autoscroll(Autoscroll::fit(), cx);
 6804        });
 6805    }
 6806
 6807    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6809        let buffer = &display_map.buffer_snapshot;
 6810        let selections = self.selections.all::<Point>(cx);
 6811
 6812        let mut edits = Vec::new();
 6813        let mut selections_iter = selections.iter().peekable();
 6814        while let Some(selection) = selections_iter.next() {
 6815            // Avoid duplicating the same lines twice.
 6816            let mut rows = selection.spanned_rows(false, &display_map);
 6817
 6818            while let Some(next_selection) = selections_iter.peek() {
 6819                let next_rows = next_selection.spanned_rows(false, &display_map);
 6820                if next_rows.start < rows.end {
 6821                    rows.end = next_rows.end;
 6822                    selections_iter.next().unwrap();
 6823                } else {
 6824                    break;
 6825                }
 6826            }
 6827
 6828            // Copy the text from the selected row region and splice it either at the start
 6829            // or end of the region.
 6830            let start = Point::new(rows.start.0, 0);
 6831            let end = Point::new(
 6832                rows.end.previous_row().0,
 6833                buffer.line_len(rows.end.previous_row()),
 6834            );
 6835            let text = buffer
 6836                .text_for_range(start..end)
 6837                .chain(Some("\n"))
 6838                .collect::<String>();
 6839            let insert_location = if upwards {
 6840                Point::new(rows.end.0, 0)
 6841            } else {
 6842                start
 6843            };
 6844            edits.push((insert_location..insert_location, text));
 6845        }
 6846
 6847        self.transact(cx, |this, cx| {
 6848            this.buffer.update(cx, |buffer, cx| {
 6849                buffer.edit(edits, None, cx);
 6850            });
 6851
 6852            this.request_autoscroll(Autoscroll::fit(), cx);
 6853        });
 6854    }
 6855
 6856    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6857        self.duplicate_line(true, cx);
 6858    }
 6859
 6860    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6861        self.duplicate_line(false, cx);
 6862    }
 6863
 6864    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6865        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6866        let buffer = self.buffer.read(cx).snapshot(cx);
 6867
 6868        let mut edits = Vec::new();
 6869        let mut unfold_ranges = Vec::new();
 6870        let mut refold_creases = Vec::new();
 6871
 6872        let selections = self.selections.all::<Point>(cx);
 6873        let mut selections = selections.iter().peekable();
 6874        let mut contiguous_row_selections = Vec::new();
 6875        let mut new_selections = Vec::new();
 6876
 6877        while let Some(selection) = selections.next() {
 6878            // Find all the selections that span a contiguous row range
 6879            let (start_row, end_row) = consume_contiguous_rows(
 6880                &mut contiguous_row_selections,
 6881                selection,
 6882                &display_map,
 6883                &mut selections,
 6884            );
 6885
 6886            // Move the text spanned by the row range to be before the line preceding the row range
 6887            if start_row.0 > 0 {
 6888                let range_to_move = Point::new(
 6889                    start_row.previous_row().0,
 6890                    buffer.line_len(start_row.previous_row()),
 6891                )
 6892                    ..Point::new(
 6893                        end_row.previous_row().0,
 6894                        buffer.line_len(end_row.previous_row()),
 6895                    );
 6896                let insertion_point = display_map
 6897                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6898                    .0;
 6899
 6900                // Don't move lines across excerpts
 6901                if buffer
 6902                    .excerpt_boundaries_in_range((
 6903                        Bound::Excluded(insertion_point),
 6904                        Bound::Included(range_to_move.end),
 6905                    ))
 6906                    .next()
 6907                    .is_none()
 6908                {
 6909                    let text = buffer
 6910                        .text_for_range(range_to_move.clone())
 6911                        .flat_map(|s| s.chars())
 6912                        .skip(1)
 6913                        .chain(['\n'])
 6914                        .collect::<String>();
 6915
 6916                    edits.push((
 6917                        buffer.anchor_after(range_to_move.start)
 6918                            ..buffer.anchor_before(range_to_move.end),
 6919                        String::new(),
 6920                    ));
 6921                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6922                    edits.push((insertion_anchor..insertion_anchor, text));
 6923
 6924                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6925
 6926                    // Move selections up
 6927                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6928                        |mut selection| {
 6929                            selection.start.row -= row_delta;
 6930                            selection.end.row -= row_delta;
 6931                            selection
 6932                        },
 6933                    ));
 6934
 6935                    // Move folds up
 6936                    unfold_ranges.push(range_to_move.clone());
 6937                    for fold in display_map.folds_in_range(
 6938                        buffer.anchor_before(range_to_move.start)
 6939                            ..buffer.anchor_after(range_to_move.end),
 6940                    ) {
 6941                        let mut start = fold.range.start.to_point(&buffer);
 6942                        let mut end = fold.range.end.to_point(&buffer);
 6943                        start.row -= row_delta;
 6944                        end.row -= row_delta;
 6945                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6946                    }
 6947                }
 6948            }
 6949
 6950            // If we didn't move line(s), preserve the existing selections
 6951            new_selections.append(&mut contiguous_row_selections);
 6952        }
 6953
 6954        self.transact(cx, |this, cx| {
 6955            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6956            this.buffer.update(cx, |buffer, cx| {
 6957                for (range, text) in edits {
 6958                    buffer.edit([(range, text)], None, cx);
 6959                }
 6960            });
 6961            this.fold_creases(refold_creases, true, cx);
 6962            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6963                s.select(new_selections);
 6964            })
 6965        });
 6966    }
 6967
 6968    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6969        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6970        let buffer = self.buffer.read(cx).snapshot(cx);
 6971
 6972        let mut edits = Vec::new();
 6973        let mut unfold_ranges = Vec::new();
 6974        let mut refold_creases = Vec::new();
 6975
 6976        let selections = self.selections.all::<Point>(cx);
 6977        let mut selections = selections.iter().peekable();
 6978        let mut contiguous_row_selections = Vec::new();
 6979        let mut new_selections = Vec::new();
 6980
 6981        while let Some(selection) = selections.next() {
 6982            // Find all the selections that span a contiguous row range
 6983            let (start_row, end_row) = consume_contiguous_rows(
 6984                &mut contiguous_row_selections,
 6985                selection,
 6986                &display_map,
 6987                &mut selections,
 6988            );
 6989
 6990            // Move the text spanned by the row range to be after the last line of the row range
 6991            if end_row.0 <= buffer.max_point().row {
 6992                let range_to_move =
 6993                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6994                let insertion_point = display_map
 6995                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6996                    .0;
 6997
 6998                // Don't move lines across excerpt boundaries
 6999                if buffer
 7000                    .excerpt_boundaries_in_range((
 7001                        Bound::Excluded(range_to_move.start),
 7002                        Bound::Included(insertion_point),
 7003                    ))
 7004                    .next()
 7005                    .is_none()
 7006                {
 7007                    let mut text = String::from("\n");
 7008                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7009                    text.pop(); // Drop trailing newline
 7010                    edits.push((
 7011                        buffer.anchor_after(range_to_move.start)
 7012                            ..buffer.anchor_before(range_to_move.end),
 7013                        String::new(),
 7014                    ));
 7015                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7016                    edits.push((insertion_anchor..insertion_anchor, text));
 7017
 7018                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7019
 7020                    // Move selections down
 7021                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7022                        |mut selection| {
 7023                            selection.start.row += row_delta;
 7024                            selection.end.row += row_delta;
 7025                            selection
 7026                        },
 7027                    ));
 7028
 7029                    // Move folds down
 7030                    unfold_ranges.push(range_to_move.clone());
 7031                    for fold in display_map.folds_in_range(
 7032                        buffer.anchor_before(range_to_move.start)
 7033                            ..buffer.anchor_after(range_to_move.end),
 7034                    ) {
 7035                        let mut start = fold.range.start.to_point(&buffer);
 7036                        let mut end = fold.range.end.to_point(&buffer);
 7037                        start.row += row_delta;
 7038                        end.row += row_delta;
 7039                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7040                    }
 7041                }
 7042            }
 7043
 7044            // If we didn't move line(s), preserve the existing selections
 7045            new_selections.append(&mut contiguous_row_selections);
 7046        }
 7047
 7048        self.transact(cx, |this, cx| {
 7049            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7050            this.buffer.update(cx, |buffer, cx| {
 7051                for (range, text) in edits {
 7052                    buffer.edit([(range, text)], None, cx);
 7053                }
 7054            });
 7055            this.fold_creases(refold_creases, true, cx);
 7056            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7057        });
 7058    }
 7059
 7060    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7061        let text_layout_details = &self.text_layout_details(cx);
 7062        self.transact(cx, |this, cx| {
 7063            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7064                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7065                let line_mode = s.line_mode;
 7066                s.move_with(|display_map, selection| {
 7067                    if !selection.is_empty() || line_mode {
 7068                        return;
 7069                    }
 7070
 7071                    let mut head = selection.head();
 7072                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7073                    if head.column() == display_map.line_len(head.row()) {
 7074                        transpose_offset = display_map
 7075                            .buffer_snapshot
 7076                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7077                    }
 7078
 7079                    if transpose_offset == 0 {
 7080                        return;
 7081                    }
 7082
 7083                    *head.column_mut() += 1;
 7084                    head = display_map.clip_point(head, Bias::Right);
 7085                    let goal = SelectionGoal::HorizontalPosition(
 7086                        display_map
 7087                            .x_for_display_point(head, text_layout_details)
 7088                            .into(),
 7089                    );
 7090                    selection.collapse_to(head, goal);
 7091
 7092                    let transpose_start = display_map
 7093                        .buffer_snapshot
 7094                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7095                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7096                        let transpose_end = display_map
 7097                            .buffer_snapshot
 7098                            .clip_offset(transpose_offset + 1, Bias::Right);
 7099                        if let Some(ch) =
 7100                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7101                        {
 7102                            edits.push((transpose_start..transpose_offset, String::new()));
 7103                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7104                        }
 7105                    }
 7106                });
 7107                edits
 7108            });
 7109            this.buffer
 7110                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7111            let selections = this.selections.all::<usize>(cx);
 7112            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7113                s.select(selections);
 7114            });
 7115        });
 7116    }
 7117
 7118    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7119        self.rewrap_impl(IsVimMode::No, cx)
 7120    }
 7121
 7122    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7123        let buffer = self.buffer.read(cx).snapshot(cx);
 7124        let selections = self.selections.all::<Point>(cx);
 7125        let mut selections = selections.iter().peekable();
 7126
 7127        let mut edits = Vec::new();
 7128        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7129
 7130        while let Some(selection) = selections.next() {
 7131            let mut start_row = selection.start.row;
 7132            let mut end_row = selection.end.row;
 7133
 7134            // Skip selections that overlap with a range that has already been rewrapped.
 7135            let selection_range = start_row..end_row;
 7136            if rewrapped_row_ranges
 7137                .iter()
 7138                .any(|range| range.overlaps(&selection_range))
 7139            {
 7140                continue;
 7141            }
 7142
 7143            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7144
 7145            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7146                match language_scope.language_name().0.as_ref() {
 7147                    "Markdown" | "Plain Text" => {
 7148                        should_rewrap = true;
 7149                    }
 7150                    _ => {}
 7151                }
 7152            }
 7153
 7154            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7155
 7156            // Since not all lines in the selection may be at the same indent
 7157            // level, choose the indent size that is the most common between all
 7158            // of the lines.
 7159            //
 7160            // If there is a tie, we use the deepest indent.
 7161            let (indent_size, indent_end) = {
 7162                let mut indent_size_occurrences = HashMap::default();
 7163                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7164
 7165                for row in start_row..=end_row {
 7166                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7167                    rows_by_indent_size.entry(indent).or_default().push(row);
 7168                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7169                }
 7170
 7171                let indent_size = indent_size_occurrences
 7172                    .into_iter()
 7173                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7174                    .map(|(indent, _)| indent)
 7175                    .unwrap_or_default();
 7176                let row = rows_by_indent_size[&indent_size][0];
 7177                let indent_end = Point::new(row, indent_size.len);
 7178
 7179                (indent_size, indent_end)
 7180            };
 7181
 7182            let mut line_prefix = indent_size.chars().collect::<String>();
 7183
 7184            if let Some(comment_prefix) =
 7185                buffer
 7186                    .language_scope_at(selection.head())
 7187                    .and_then(|language| {
 7188                        language
 7189                            .line_comment_prefixes()
 7190                            .iter()
 7191                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7192                            .cloned()
 7193                    })
 7194            {
 7195                line_prefix.push_str(&comment_prefix);
 7196                should_rewrap = true;
 7197            }
 7198
 7199            if !should_rewrap {
 7200                continue;
 7201            }
 7202
 7203            if selection.is_empty() {
 7204                'expand_upwards: while start_row > 0 {
 7205                    let prev_row = start_row - 1;
 7206                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7207                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7208                    {
 7209                        start_row = prev_row;
 7210                    } else {
 7211                        break 'expand_upwards;
 7212                    }
 7213                }
 7214
 7215                'expand_downwards: while end_row < buffer.max_point().row {
 7216                    let next_row = end_row + 1;
 7217                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7218                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7219                    {
 7220                        end_row = next_row;
 7221                    } else {
 7222                        break 'expand_downwards;
 7223                    }
 7224                }
 7225            }
 7226
 7227            let start = Point::new(start_row, 0);
 7228            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7229            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7230            let Some(lines_without_prefixes) = selection_text
 7231                .lines()
 7232                .map(|line| {
 7233                    line.strip_prefix(&line_prefix)
 7234                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7235                        .ok_or_else(|| {
 7236                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7237                        })
 7238                })
 7239                .collect::<Result<Vec<_>, _>>()
 7240                .log_err()
 7241            else {
 7242                continue;
 7243            };
 7244
 7245            let wrap_column = buffer
 7246                .settings_at(Point::new(start_row, 0), cx)
 7247                .preferred_line_length as usize;
 7248            let wrapped_text = wrap_with_prefix(
 7249                line_prefix,
 7250                lines_without_prefixes.join(" "),
 7251                wrap_column,
 7252                tab_size,
 7253            );
 7254
 7255            // TODO: should always use char-based diff while still supporting cursor behavior that
 7256            // matches vim.
 7257            let diff = match is_vim_mode {
 7258                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7259                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7260            };
 7261            let mut offset = start.to_offset(&buffer);
 7262            let mut moved_since_edit = true;
 7263
 7264            for change in diff.iter_all_changes() {
 7265                let value = change.value();
 7266                match change.tag() {
 7267                    ChangeTag::Equal => {
 7268                        offset += value.len();
 7269                        moved_since_edit = true;
 7270                    }
 7271                    ChangeTag::Delete => {
 7272                        let start = buffer.anchor_after(offset);
 7273                        let end = buffer.anchor_before(offset + value.len());
 7274
 7275                        if moved_since_edit {
 7276                            edits.push((start..end, String::new()));
 7277                        } else {
 7278                            edits.last_mut().unwrap().0.end = end;
 7279                        }
 7280
 7281                        offset += value.len();
 7282                        moved_since_edit = false;
 7283                    }
 7284                    ChangeTag::Insert => {
 7285                        if moved_since_edit {
 7286                            let anchor = buffer.anchor_after(offset);
 7287                            edits.push((anchor..anchor, value.to_string()));
 7288                        } else {
 7289                            edits.last_mut().unwrap().1.push_str(value);
 7290                        }
 7291
 7292                        moved_since_edit = false;
 7293                    }
 7294                }
 7295            }
 7296
 7297            rewrapped_row_ranges.push(start_row..=end_row);
 7298        }
 7299
 7300        self.buffer
 7301            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7302    }
 7303
 7304    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 7305        let mut text = String::new();
 7306        let buffer = self.buffer.read(cx).snapshot(cx);
 7307        let mut selections = self.selections.all::<Point>(cx);
 7308        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7309        {
 7310            let max_point = buffer.max_point();
 7311            let mut is_first = true;
 7312            for selection in &mut selections {
 7313                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7314                if is_entire_line {
 7315                    selection.start = Point::new(selection.start.row, 0);
 7316                    if !selection.is_empty() && selection.end.column == 0 {
 7317                        selection.end = cmp::min(max_point, selection.end);
 7318                    } else {
 7319                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7320                    }
 7321                    selection.goal = SelectionGoal::None;
 7322                }
 7323                if is_first {
 7324                    is_first = false;
 7325                } else {
 7326                    text += "\n";
 7327                }
 7328                let mut len = 0;
 7329                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7330                    text.push_str(chunk);
 7331                    len += chunk.len();
 7332                }
 7333                clipboard_selections.push(ClipboardSelection {
 7334                    len,
 7335                    is_entire_line,
 7336                    first_line_indent: buffer
 7337                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7338                        .len,
 7339                });
 7340            }
 7341        }
 7342
 7343        self.transact(cx, |this, cx| {
 7344            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7345                s.select(selections);
 7346            });
 7347            this.insert("", cx);
 7348        });
 7349        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7350    }
 7351
 7352    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7353        let item = self.cut_common(cx);
 7354        cx.write_to_clipboard(item);
 7355    }
 7356
 7357    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 7358        self.change_selections(None, cx, |s| {
 7359            s.move_with(|snapshot, sel| {
 7360                if sel.is_empty() {
 7361                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7362                }
 7363            });
 7364        });
 7365        let item = self.cut_common(cx);
 7366        cx.set_global(KillRing(item))
 7367    }
 7368
 7369    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 7370        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7371            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7372                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7373            } else {
 7374                return;
 7375            }
 7376        } else {
 7377            return;
 7378        };
 7379        self.do_paste(&text, metadata, false, cx);
 7380    }
 7381
 7382    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7383        let selections = self.selections.all::<Point>(cx);
 7384        let buffer = self.buffer.read(cx).read(cx);
 7385        let mut text = String::new();
 7386
 7387        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7388        {
 7389            let max_point = buffer.max_point();
 7390            let mut is_first = true;
 7391            for selection in selections.iter() {
 7392                let mut start = selection.start;
 7393                let mut end = selection.end;
 7394                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7395                if is_entire_line {
 7396                    start = Point::new(start.row, 0);
 7397                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7398                }
 7399                if is_first {
 7400                    is_first = false;
 7401                } else {
 7402                    text += "\n";
 7403                }
 7404                let mut len = 0;
 7405                for chunk in buffer.text_for_range(start..end) {
 7406                    text.push_str(chunk);
 7407                    len += chunk.len();
 7408                }
 7409                clipboard_selections.push(ClipboardSelection {
 7410                    len,
 7411                    is_entire_line,
 7412                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7413                });
 7414            }
 7415        }
 7416
 7417        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7418            text,
 7419            clipboard_selections,
 7420        ));
 7421    }
 7422
 7423    pub fn do_paste(
 7424        &mut self,
 7425        text: &String,
 7426        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7427        handle_entire_lines: bool,
 7428        cx: &mut ViewContext<Self>,
 7429    ) {
 7430        if self.read_only(cx) {
 7431            return;
 7432        }
 7433
 7434        let clipboard_text = Cow::Borrowed(text);
 7435
 7436        self.transact(cx, |this, cx| {
 7437            if let Some(mut clipboard_selections) = clipboard_selections {
 7438                let old_selections = this.selections.all::<usize>(cx);
 7439                let all_selections_were_entire_line =
 7440                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7441                let first_selection_indent_column =
 7442                    clipboard_selections.first().map(|s| s.first_line_indent);
 7443                if clipboard_selections.len() != old_selections.len() {
 7444                    clipboard_selections.drain(..);
 7445                }
 7446                let cursor_offset = this.selections.last::<usize>(cx).head();
 7447                let mut auto_indent_on_paste = true;
 7448
 7449                this.buffer.update(cx, |buffer, cx| {
 7450                    let snapshot = buffer.read(cx);
 7451                    auto_indent_on_paste =
 7452                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7453
 7454                    let mut start_offset = 0;
 7455                    let mut edits = Vec::new();
 7456                    let mut original_indent_columns = Vec::new();
 7457                    for (ix, selection) in old_selections.iter().enumerate() {
 7458                        let to_insert;
 7459                        let entire_line;
 7460                        let original_indent_column;
 7461                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7462                            let end_offset = start_offset + clipboard_selection.len;
 7463                            to_insert = &clipboard_text[start_offset..end_offset];
 7464                            entire_line = clipboard_selection.is_entire_line;
 7465                            start_offset = end_offset + 1;
 7466                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7467                        } else {
 7468                            to_insert = clipboard_text.as_str();
 7469                            entire_line = all_selections_were_entire_line;
 7470                            original_indent_column = first_selection_indent_column
 7471                        }
 7472
 7473                        // If the corresponding selection was empty when this slice of the
 7474                        // clipboard text was written, then the entire line containing the
 7475                        // selection was copied. If this selection is also currently empty,
 7476                        // then paste the line before the current line of the buffer.
 7477                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7478                            let column = selection.start.to_point(&snapshot).column as usize;
 7479                            let line_start = selection.start - column;
 7480                            line_start..line_start
 7481                        } else {
 7482                            selection.range()
 7483                        };
 7484
 7485                        edits.push((range, to_insert));
 7486                        original_indent_columns.extend(original_indent_column);
 7487                    }
 7488                    drop(snapshot);
 7489
 7490                    buffer.edit(
 7491                        edits,
 7492                        if auto_indent_on_paste {
 7493                            Some(AutoindentMode::Block {
 7494                                original_indent_columns,
 7495                            })
 7496                        } else {
 7497                            None
 7498                        },
 7499                        cx,
 7500                    );
 7501                });
 7502
 7503                let selections = this.selections.all::<usize>(cx);
 7504                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7505            } else {
 7506                this.insert(&clipboard_text, cx);
 7507            }
 7508        });
 7509    }
 7510
 7511    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7512        if let Some(item) = cx.read_from_clipboard() {
 7513            let entries = item.entries();
 7514
 7515            match entries.first() {
 7516                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7517                // of all the pasted entries.
 7518                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7519                    .do_paste(
 7520                        clipboard_string.text(),
 7521                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7522                        true,
 7523                        cx,
 7524                    ),
 7525                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7526            }
 7527        }
 7528    }
 7529
 7530    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7531        if self.read_only(cx) {
 7532            return;
 7533        }
 7534
 7535        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7536            if let Some((selections, _)) =
 7537                self.selection_history.transaction(transaction_id).cloned()
 7538            {
 7539                self.change_selections(None, cx, |s| {
 7540                    s.select_anchors(selections.to_vec());
 7541                });
 7542            }
 7543            self.request_autoscroll(Autoscroll::fit(), cx);
 7544            self.unmark_text(cx);
 7545            self.refresh_inline_completion(true, false, cx);
 7546            cx.emit(EditorEvent::Edited { transaction_id });
 7547            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7548        }
 7549    }
 7550
 7551    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7552        if self.read_only(cx) {
 7553            return;
 7554        }
 7555
 7556        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7557            if let Some((_, Some(selections))) =
 7558                self.selection_history.transaction(transaction_id).cloned()
 7559            {
 7560                self.change_selections(None, cx, |s| {
 7561                    s.select_anchors(selections.to_vec());
 7562                });
 7563            }
 7564            self.request_autoscroll(Autoscroll::fit(), cx);
 7565            self.unmark_text(cx);
 7566            self.refresh_inline_completion(true, false, cx);
 7567            cx.emit(EditorEvent::Edited { transaction_id });
 7568        }
 7569    }
 7570
 7571    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7572        self.buffer
 7573            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7574    }
 7575
 7576    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7577        self.buffer
 7578            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7579    }
 7580
 7581    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7582        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7583            let line_mode = s.line_mode;
 7584            s.move_with(|map, selection| {
 7585                let cursor = if selection.is_empty() && !line_mode {
 7586                    movement::left(map, selection.start)
 7587                } else {
 7588                    selection.start
 7589                };
 7590                selection.collapse_to(cursor, SelectionGoal::None);
 7591            });
 7592        })
 7593    }
 7594
 7595    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7596        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7597            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7598        })
 7599    }
 7600
 7601    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7602        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7603            let line_mode = s.line_mode;
 7604            s.move_with(|map, selection| {
 7605                let cursor = if selection.is_empty() && !line_mode {
 7606                    movement::right(map, selection.end)
 7607                } else {
 7608                    selection.end
 7609                };
 7610                selection.collapse_to(cursor, SelectionGoal::None)
 7611            });
 7612        })
 7613    }
 7614
 7615    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7616        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7617            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7618        })
 7619    }
 7620
 7621    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7622        if self.take_rename(true, cx).is_some() {
 7623            return;
 7624        }
 7625
 7626        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7627            cx.propagate();
 7628            return;
 7629        }
 7630
 7631        let text_layout_details = &self.text_layout_details(cx);
 7632        let selection_count = self.selections.count();
 7633        let first_selection = self.selections.first_anchor();
 7634
 7635        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7636            let line_mode = s.line_mode;
 7637            s.move_with(|map, selection| {
 7638                if !selection.is_empty() && !line_mode {
 7639                    selection.goal = SelectionGoal::None;
 7640                }
 7641                let (cursor, goal) = movement::up(
 7642                    map,
 7643                    selection.start,
 7644                    selection.goal,
 7645                    false,
 7646                    text_layout_details,
 7647                );
 7648                selection.collapse_to(cursor, goal);
 7649            });
 7650        });
 7651
 7652        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7653        {
 7654            cx.propagate();
 7655        }
 7656    }
 7657
 7658    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7659        if self.take_rename(true, cx).is_some() {
 7660            return;
 7661        }
 7662
 7663        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7664            cx.propagate();
 7665            return;
 7666        }
 7667
 7668        let text_layout_details = &self.text_layout_details(cx);
 7669
 7670        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7671            let line_mode = s.line_mode;
 7672            s.move_with(|map, selection| {
 7673                if !selection.is_empty() && !line_mode {
 7674                    selection.goal = SelectionGoal::None;
 7675                }
 7676                let (cursor, goal) = movement::up_by_rows(
 7677                    map,
 7678                    selection.start,
 7679                    action.lines,
 7680                    selection.goal,
 7681                    false,
 7682                    text_layout_details,
 7683                );
 7684                selection.collapse_to(cursor, goal);
 7685            });
 7686        })
 7687    }
 7688
 7689    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7690        if self.take_rename(true, cx).is_some() {
 7691            return;
 7692        }
 7693
 7694        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7695            cx.propagate();
 7696            return;
 7697        }
 7698
 7699        let text_layout_details = &self.text_layout_details(cx);
 7700
 7701        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7702            let line_mode = s.line_mode;
 7703            s.move_with(|map, selection| {
 7704                if !selection.is_empty() && !line_mode {
 7705                    selection.goal = SelectionGoal::None;
 7706                }
 7707                let (cursor, goal) = movement::down_by_rows(
 7708                    map,
 7709                    selection.start,
 7710                    action.lines,
 7711                    selection.goal,
 7712                    false,
 7713                    text_layout_details,
 7714                );
 7715                selection.collapse_to(cursor, goal);
 7716            });
 7717        })
 7718    }
 7719
 7720    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7721        let text_layout_details = &self.text_layout_details(cx);
 7722        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7723            s.move_heads_with(|map, head, goal| {
 7724                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7725            })
 7726        })
 7727    }
 7728
 7729    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7730        let text_layout_details = &self.text_layout_details(cx);
 7731        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7732            s.move_heads_with(|map, head, goal| {
 7733                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7734            })
 7735        })
 7736    }
 7737
 7738    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7739        let Some(row_count) = self.visible_row_count() else {
 7740            return;
 7741        };
 7742
 7743        let text_layout_details = &self.text_layout_details(cx);
 7744
 7745        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7746            s.move_heads_with(|map, head, goal| {
 7747                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7748            })
 7749        })
 7750    }
 7751
 7752    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7753        if self.take_rename(true, cx).is_some() {
 7754            return;
 7755        }
 7756
 7757        if self
 7758            .context_menu
 7759            .write()
 7760            .as_mut()
 7761            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7762            .unwrap_or(false)
 7763        {
 7764            return;
 7765        }
 7766
 7767        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7768            cx.propagate();
 7769            return;
 7770        }
 7771
 7772        let Some(row_count) = self.visible_row_count() else {
 7773            return;
 7774        };
 7775
 7776        let autoscroll = if action.center_cursor {
 7777            Autoscroll::center()
 7778        } else {
 7779            Autoscroll::fit()
 7780        };
 7781
 7782        let text_layout_details = &self.text_layout_details(cx);
 7783
 7784        self.change_selections(Some(autoscroll), cx, |s| {
 7785            let line_mode = s.line_mode;
 7786            s.move_with(|map, selection| {
 7787                if !selection.is_empty() && !line_mode {
 7788                    selection.goal = SelectionGoal::None;
 7789                }
 7790                let (cursor, goal) = movement::up_by_rows(
 7791                    map,
 7792                    selection.end,
 7793                    row_count,
 7794                    selection.goal,
 7795                    false,
 7796                    text_layout_details,
 7797                );
 7798                selection.collapse_to(cursor, goal);
 7799            });
 7800        });
 7801    }
 7802
 7803    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7804        let text_layout_details = &self.text_layout_details(cx);
 7805        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7806            s.move_heads_with(|map, head, goal| {
 7807                movement::up(map, head, goal, false, text_layout_details)
 7808            })
 7809        })
 7810    }
 7811
 7812    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7813        self.take_rename(true, cx);
 7814
 7815        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7816            cx.propagate();
 7817            return;
 7818        }
 7819
 7820        let text_layout_details = &self.text_layout_details(cx);
 7821        let selection_count = self.selections.count();
 7822        let first_selection = self.selections.first_anchor();
 7823
 7824        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7825            let line_mode = s.line_mode;
 7826            s.move_with(|map, selection| {
 7827                if !selection.is_empty() && !line_mode {
 7828                    selection.goal = SelectionGoal::None;
 7829                }
 7830                let (cursor, goal) = movement::down(
 7831                    map,
 7832                    selection.end,
 7833                    selection.goal,
 7834                    false,
 7835                    text_layout_details,
 7836                );
 7837                selection.collapse_to(cursor, goal);
 7838            });
 7839        });
 7840
 7841        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7842        {
 7843            cx.propagate();
 7844        }
 7845    }
 7846
 7847    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7848        let Some(row_count) = self.visible_row_count() else {
 7849            return;
 7850        };
 7851
 7852        let text_layout_details = &self.text_layout_details(cx);
 7853
 7854        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7855            s.move_heads_with(|map, head, goal| {
 7856                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7857            })
 7858        })
 7859    }
 7860
 7861    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7862        if self.take_rename(true, cx).is_some() {
 7863            return;
 7864        }
 7865
 7866        if self
 7867            .context_menu
 7868            .write()
 7869            .as_mut()
 7870            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7871            .unwrap_or(false)
 7872        {
 7873            return;
 7874        }
 7875
 7876        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7877            cx.propagate();
 7878            return;
 7879        }
 7880
 7881        let Some(row_count) = self.visible_row_count() else {
 7882            return;
 7883        };
 7884
 7885        let autoscroll = if action.center_cursor {
 7886            Autoscroll::center()
 7887        } else {
 7888            Autoscroll::fit()
 7889        };
 7890
 7891        let text_layout_details = &self.text_layout_details(cx);
 7892        self.change_selections(Some(autoscroll), cx, |s| {
 7893            let line_mode = s.line_mode;
 7894            s.move_with(|map, selection| {
 7895                if !selection.is_empty() && !line_mode {
 7896                    selection.goal = SelectionGoal::None;
 7897                }
 7898                let (cursor, goal) = movement::down_by_rows(
 7899                    map,
 7900                    selection.end,
 7901                    row_count,
 7902                    selection.goal,
 7903                    false,
 7904                    text_layout_details,
 7905                );
 7906                selection.collapse_to(cursor, goal);
 7907            });
 7908        });
 7909    }
 7910
 7911    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7912        let text_layout_details = &self.text_layout_details(cx);
 7913        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7914            s.move_heads_with(|map, head, goal| {
 7915                movement::down(map, head, goal, false, text_layout_details)
 7916            })
 7917        });
 7918    }
 7919
 7920    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7921        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7922            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7923        }
 7924    }
 7925
 7926    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7927        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7928            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7929        }
 7930    }
 7931
 7932    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7933        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7934            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7935        }
 7936    }
 7937
 7938    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7939        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7940            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7941        }
 7942    }
 7943
 7944    pub fn move_to_previous_word_start(
 7945        &mut self,
 7946        _: &MoveToPreviousWordStart,
 7947        cx: &mut ViewContext<Self>,
 7948    ) {
 7949        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7950            s.move_cursors_with(|map, head, _| {
 7951                (
 7952                    movement::previous_word_start(map, head),
 7953                    SelectionGoal::None,
 7954                )
 7955            });
 7956        })
 7957    }
 7958
 7959    pub fn move_to_previous_subword_start(
 7960        &mut self,
 7961        _: &MoveToPreviousSubwordStart,
 7962        cx: &mut ViewContext<Self>,
 7963    ) {
 7964        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7965            s.move_cursors_with(|map, head, _| {
 7966                (
 7967                    movement::previous_subword_start(map, head),
 7968                    SelectionGoal::None,
 7969                )
 7970            });
 7971        })
 7972    }
 7973
 7974    pub fn select_to_previous_word_start(
 7975        &mut self,
 7976        _: &SelectToPreviousWordStart,
 7977        cx: &mut ViewContext<Self>,
 7978    ) {
 7979        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7980            s.move_heads_with(|map, head, _| {
 7981                (
 7982                    movement::previous_word_start(map, head),
 7983                    SelectionGoal::None,
 7984                )
 7985            });
 7986        })
 7987    }
 7988
 7989    pub fn select_to_previous_subword_start(
 7990        &mut self,
 7991        _: &SelectToPreviousSubwordStart,
 7992        cx: &mut ViewContext<Self>,
 7993    ) {
 7994        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7995            s.move_heads_with(|map, head, _| {
 7996                (
 7997                    movement::previous_subword_start(map, head),
 7998                    SelectionGoal::None,
 7999                )
 8000            });
 8001        })
 8002    }
 8003
 8004    pub fn delete_to_previous_word_start(
 8005        &mut self,
 8006        action: &DeleteToPreviousWordStart,
 8007        cx: &mut ViewContext<Self>,
 8008    ) {
 8009        self.transact(cx, |this, cx| {
 8010            this.select_autoclose_pair(cx);
 8011            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8012                let line_mode = s.line_mode;
 8013                s.move_with(|map, selection| {
 8014                    if selection.is_empty() && !line_mode {
 8015                        let cursor = if action.ignore_newlines {
 8016                            movement::previous_word_start(map, selection.head())
 8017                        } else {
 8018                            movement::previous_word_start_or_newline(map, selection.head())
 8019                        };
 8020                        selection.set_head(cursor, SelectionGoal::None);
 8021                    }
 8022                });
 8023            });
 8024            this.insert("", cx);
 8025        });
 8026    }
 8027
 8028    pub fn delete_to_previous_subword_start(
 8029        &mut self,
 8030        _: &DeleteToPreviousSubwordStart,
 8031        cx: &mut ViewContext<Self>,
 8032    ) {
 8033        self.transact(cx, |this, cx| {
 8034            this.select_autoclose_pair(cx);
 8035            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8036                let line_mode = s.line_mode;
 8037                s.move_with(|map, selection| {
 8038                    if selection.is_empty() && !line_mode {
 8039                        let cursor = movement::previous_subword_start(map, selection.head());
 8040                        selection.set_head(cursor, SelectionGoal::None);
 8041                    }
 8042                });
 8043            });
 8044            this.insert("", cx);
 8045        });
 8046    }
 8047
 8048    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8049        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8050            s.move_cursors_with(|map, head, _| {
 8051                (movement::next_word_end(map, head), SelectionGoal::None)
 8052            });
 8053        })
 8054    }
 8055
 8056    pub fn move_to_next_subword_end(
 8057        &mut self,
 8058        _: &MoveToNextSubwordEnd,
 8059        cx: &mut ViewContext<Self>,
 8060    ) {
 8061        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8062            s.move_cursors_with(|map, head, _| {
 8063                (movement::next_subword_end(map, head), SelectionGoal::None)
 8064            });
 8065        })
 8066    }
 8067
 8068    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8069        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8070            s.move_heads_with(|map, head, _| {
 8071                (movement::next_word_end(map, head), SelectionGoal::None)
 8072            });
 8073        })
 8074    }
 8075
 8076    pub fn select_to_next_subword_end(
 8077        &mut self,
 8078        _: &SelectToNextSubwordEnd,
 8079        cx: &mut ViewContext<Self>,
 8080    ) {
 8081        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8082            s.move_heads_with(|map, head, _| {
 8083                (movement::next_subword_end(map, head), SelectionGoal::None)
 8084            });
 8085        })
 8086    }
 8087
 8088    pub fn delete_to_next_word_end(
 8089        &mut self,
 8090        action: &DeleteToNextWordEnd,
 8091        cx: &mut ViewContext<Self>,
 8092    ) {
 8093        self.transact(cx, |this, cx| {
 8094            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8095                let line_mode = s.line_mode;
 8096                s.move_with(|map, selection| {
 8097                    if selection.is_empty() && !line_mode {
 8098                        let cursor = if action.ignore_newlines {
 8099                            movement::next_word_end(map, selection.head())
 8100                        } else {
 8101                            movement::next_word_end_or_newline(map, selection.head())
 8102                        };
 8103                        selection.set_head(cursor, SelectionGoal::None);
 8104                    }
 8105                });
 8106            });
 8107            this.insert("", cx);
 8108        });
 8109    }
 8110
 8111    pub fn delete_to_next_subword_end(
 8112        &mut self,
 8113        _: &DeleteToNextSubwordEnd,
 8114        cx: &mut ViewContext<Self>,
 8115    ) {
 8116        self.transact(cx, |this, cx| {
 8117            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8118                s.move_with(|map, selection| {
 8119                    if selection.is_empty() {
 8120                        let cursor = movement::next_subword_end(map, selection.head());
 8121                        selection.set_head(cursor, SelectionGoal::None);
 8122                    }
 8123                });
 8124            });
 8125            this.insert("", cx);
 8126        });
 8127    }
 8128
 8129    pub fn move_to_beginning_of_line(
 8130        &mut self,
 8131        action: &MoveToBeginningOfLine,
 8132        cx: &mut ViewContext<Self>,
 8133    ) {
 8134        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8135            s.move_cursors_with(|map, head, _| {
 8136                (
 8137                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8138                    SelectionGoal::None,
 8139                )
 8140            });
 8141        })
 8142    }
 8143
 8144    pub fn select_to_beginning_of_line(
 8145        &mut self,
 8146        action: &SelectToBeginningOfLine,
 8147        cx: &mut ViewContext<Self>,
 8148    ) {
 8149        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8150            s.move_heads_with(|map, head, _| {
 8151                (
 8152                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8153                    SelectionGoal::None,
 8154                )
 8155            });
 8156        });
 8157    }
 8158
 8159    pub fn delete_to_beginning_of_line(
 8160        &mut self,
 8161        _: &DeleteToBeginningOfLine,
 8162        cx: &mut ViewContext<Self>,
 8163    ) {
 8164        self.transact(cx, |this, cx| {
 8165            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8166                s.move_with(|_, selection| {
 8167                    selection.reversed = true;
 8168                });
 8169            });
 8170
 8171            this.select_to_beginning_of_line(
 8172                &SelectToBeginningOfLine {
 8173                    stop_at_soft_wraps: false,
 8174                },
 8175                cx,
 8176            );
 8177            this.backspace(&Backspace, cx);
 8178        });
 8179    }
 8180
 8181    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8182        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8183            s.move_cursors_with(|map, head, _| {
 8184                (
 8185                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8186                    SelectionGoal::None,
 8187                )
 8188            });
 8189        })
 8190    }
 8191
 8192    pub fn select_to_end_of_line(
 8193        &mut self,
 8194        action: &SelectToEndOfLine,
 8195        cx: &mut ViewContext<Self>,
 8196    ) {
 8197        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8198            s.move_heads_with(|map, head, _| {
 8199                (
 8200                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8201                    SelectionGoal::None,
 8202                )
 8203            });
 8204        })
 8205    }
 8206
 8207    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8208        self.transact(cx, |this, cx| {
 8209            this.select_to_end_of_line(
 8210                &SelectToEndOfLine {
 8211                    stop_at_soft_wraps: false,
 8212                },
 8213                cx,
 8214            );
 8215            this.delete(&Delete, cx);
 8216        });
 8217    }
 8218
 8219    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8220        self.transact(cx, |this, cx| {
 8221            this.select_to_end_of_line(
 8222                &SelectToEndOfLine {
 8223                    stop_at_soft_wraps: false,
 8224                },
 8225                cx,
 8226            );
 8227            this.cut(&Cut, cx);
 8228        });
 8229    }
 8230
 8231    pub fn move_to_start_of_paragraph(
 8232        &mut self,
 8233        _: &MoveToStartOfParagraph,
 8234        cx: &mut ViewContext<Self>,
 8235    ) {
 8236        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8237            cx.propagate();
 8238            return;
 8239        }
 8240
 8241        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8242            s.move_with(|map, selection| {
 8243                selection.collapse_to(
 8244                    movement::start_of_paragraph(map, selection.head(), 1),
 8245                    SelectionGoal::None,
 8246                )
 8247            });
 8248        })
 8249    }
 8250
 8251    pub fn move_to_end_of_paragraph(
 8252        &mut self,
 8253        _: &MoveToEndOfParagraph,
 8254        cx: &mut ViewContext<Self>,
 8255    ) {
 8256        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8257            cx.propagate();
 8258            return;
 8259        }
 8260
 8261        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8262            s.move_with(|map, selection| {
 8263                selection.collapse_to(
 8264                    movement::end_of_paragraph(map, selection.head(), 1),
 8265                    SelectionGoal::None,
 8266                )
 8267            });
 8268        })
 8269    }
 8270
 8271    pub fn select_to_start_of_paragraph(
 8272        &mut self,
 8273        _: &SelectToStartOfParagraph,
 8274        cx: &mut ViewContext<Self>,
 8275    ) {
 8276        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8277            cx.propagate();
 8278            return;
 8279        }
 8280
 8281        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8282            s.move_heads_with(|map, head, _| {
 8283                (
 8284                    movement::start_of_paragraph(map, head, 1),
 8285                    SelectionGoal::None,
 8286                )
 8287            });
 8288        })
 8289    }
 8290
 8291    pub fn select_to_end_of_paragraph(
 8292        &mut self,
 8293        _: &SelectToEndOfParagraph,
 8294        cx: &mut ViewContext<Self>,
 8295    ) {
 8296        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8297            cx.propagate();
 8298            return;
 8299        }
 8300
 8301        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8302            s.move_heads_with(|map, head, _| {
 8303                (
 8304                    movement::end_of_paragraph(map, head, 1),
 8305                    SelectionGoal::None,
 8306                )
 8307            });
 8308        })
 8309    }
 8310
 8311    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8312        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8313            cx.propagate();
 8314            return;
 8315        }
 8316
 8317        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8318            s.select_ranges(vec![0..0]);
 8319        });
 8320    }
 8321
 8322    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8323        let mut selection = self.selections.last::<Point>(cx);
 8324        selection.set_head(Point::zero(), SelectionGoal::None);
 8325
 8326        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8327            s.select(vec![selection]);
 8328        });
 8329    }
 8330
 8331    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8332        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8333            cx.propagate();
 8334            return;
 8335        }
 8336
 8337        let cursor = self.buffer.read(cx).read(cx).len();
 8338        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8339            s.select_ranges(vec![cursor..cursor])
 8340        });
 8341    }
 8342
 8343    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8344        self.nav_history = nav_history;
 8345    }
 8346
 8347    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8348        self.nav_history.as_ref()
 8349    }
 8350
 8351    fn push_to_nav_history(
 8352        &mut self,
 8353        cursor_anchor: Anchor,
 8354        new_position: Option<Point>,
 8355        cx: &mut ViewContext<Self>,
 8356    ) {
 8357        if let Some(nav_history) = self.nav_history.as_mut() {
 8358            let buffer = self.buffer.read(cx).read(cx);
 8359            let cursor_position = cursor_anchor.to_point(&buffer);
 8360            let scroll_state = self.scroll_manager.anchor();
 8361            let scroll_top_row = scroll_state.top_row(&buffer);
 8362            drop(buffer);
 8363
 8364            if let Some(new_position) = new_position {
 8365                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8366                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8367                    return;
 8368                }
 8369            }
 8370
 8371            nav_history.push(
 8372                Some(NavigationData {
 8373                    cursor_anchor,
 8374                    cursor_position,
 8375                    scroll_anchor: scroll_state,
 8376                    scroll_top_row,
 8377                }),
 8378                cx,
 8379            );
 8380        }
 8381    }
 8382
 8383    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8384        let buffer = self.buffer.read(cx).snapshot(cx);
 8385        let mut selection = self.selections.first::<usize>(cx);
 8386        selection.set_head(buffer.len(), SelectionGoal::None);
 8387        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8388            s.select(vec![selection]);
 8389        });
 8390    }
 8391
 8392    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8393        let end = self.buffer.read(cx).read(cx).len();
 8394        self.change_selections(None, cx, |s| {
 8395            s.select_ranges(vec![0..end]);
 8396        });
 8397    }
 8398
 8399    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8400        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8401        let mut selections = self.selections.all::<Point>(cx);
 8402        let max_point = display_map.buffer_snapshot.max_point();
 8403        for selection in &mut selections {
 8404            let rows = selection.spanned_rows(true, &display_map);
 8405            selection.start = Point::new(rows.start.0, 0);
 8406            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8407            selection.reversed = false;
 8408        }
 8409        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8410            s.select(selections);
 8411        });
 8412    }
 8413
 8414    pub fn split_selection_into_lines(
 8415        &mut self,
 8416        _: &SplitSelectionIntoLines,
 8417        cx: &mut ViewContext<Self>,
 8418    ) {
 8419        let mut to_unfold = Vec::new();
 8420        let mut new_selection_ranges = Vec::new();
 8421        {
 8422            let selections = self.selections.all::<Point>(cx);
 8423            let buffer = self.buffer.read(cx).read(cx);
 8424            for selection in selections {
 8425                for row in selection.start.row..selection.end.row {
 8426                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8427                    new_selection_ranges.push(cursor..cursor);
 8428                }
 8429                new_selection_ranges.push(selection.end..selection.end);
 8430                to_unfold.push(selection.start..selection.end);
 8431            }
 8432        }
 8433        self.unfold_ranges(&to_unfold, true, true, cx);
 8434        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8435            s.select_ranges(new_selection_ranges);
 8436        });
 8437    }
 8438
 8439    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8440        self.add_selection(true, cx);
 8441    }
 8442
 8443    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8444        self.add_selection(false, cx);
 8445    }
 8446
 8447    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8448        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8449        let mut selections = self.selections.all::<Point>(cx);
 8450        let text_layout_details = self.text_layout_details(cx);
 8451        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8452            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8453            let range = oldest_selection.display_range(&display_map).sorted();
 8454
 8455            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8456            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8457            let positions = start_x.min(end_x)..start_x.max(end_x);
 8458
 8459            selections.clear();
 8460            let mut stack = Vec::new();
 8461            for row in range.start.row().0..=range.end.row().0 {
 8462                if let Some(selection) = self.selections.build_columnar_selection(
 8463                    &display_map,
 8464                    DisplayRow(row),
 8465                    &positions,
 8466                    oldest_selection.reversed,
 8467                    &text_layout_details,
 8468                ) {
 8469                    stack.push(selection.id);
 8470                    selections.push(selection);
 8471                }
 8472            }
 8473
 8474            if above {
 8475                stack.reverse();
 8476            }
 8477
 8478            AddSelectionsState { above, stack }
 8479        });
 8480
 8481        let last_added_selection = *state.stack.last().unwrap();
 8482        let mut new_selections = Vec::new();
 8483        if above == state.above {
 8484            let end_row = if above {
 8485                DisplayRow(0)
 8486            } else {
 8487                display_map.max_point().row()
 8488            };
 8489
 8490            'outer: for selection in selections {
 8491                if selection.id == last_added_selection {
 8492                    let range = selection.display_range(&display_map).sorted();
 8493                    debug_assert_eq!(range.start.row(), range.end.row());
 8494                    let mut row = range.start.row();
 8495                    let positions =
 8496                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8497                            px(start)..px(end)
 8498                        } else {
 8499                            let start_x =
 8500                                display_map.x_for_display_point(range.start, &text_layout_details);
 8501                            let end_x =
 8502                                display_map.x_for_display_point(range.end, &text_layout_details);
 8503                            start_x.min(end_x)..start_x.max(end_x)
 8504                        };
 8505
 8506                    while row != end_row {
 8507                        if above {
 8508                            row.0 -= 1;
 8509                        } else {
 8510                            row.0 += 1;
 8511                        }
 8512
 8513                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8514                            &display_map,
 8515                            row,
 8516                            &positions,
 8517                            selection.reversed,
 8518                            &text_layout_details,
 8519                        ) {
 8520                            state.stack.push(new_selection.id);
 8521                            if above {
 8522                                new_selections.push(new_selection);
 8523                                new_selections.push(selection);
 8524                            } else {
 8525                                new_selections.push(selection);
 8526                                new_selections.push(new_selection);
 8527                            }
 8528
 8529                            continue 'outer;
 8530                        }
 8531                    }
 8532                }
 8533
 8534                new_selections.push(selection);
 8535            }
 8536        } else {
 8537            new_selections = selections;
 8538            new_selections.retain(|s| s.id != last_added_selection);
 8539            state.stack.pop();
 8540        }
 8541
 8542        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8543            s.select(new_selections);
 8544        });
 8545        if state.stack.len() > 1 {
 8546            self.add_selections_state = Some(state);
 8547        }
 8548    }
 8549
 8550    pub fn select_next_match_internal(
 8551        &mut self,
 8552        display_map: &DisplaySnapshot,
 8553        replace_newest: bool,
 8554        autoscroll: Option<Autoscroll>,
 8555        cx: &mut ViewContext<Self>,
 8556    ) -> Result<()> {
 8557        fn select_next_match_ranges(
 8558            this: &mut Editor,
 8559            range: Range<usize>,
 8560            replace_newest: bool,
 8561            auto_scroll: Option<Autoscroll>,
 8562            cx: &mut ViewContext<Editor>,
 8563        ) {
 8564            this.unfold_ranges(&[range.clone()], false, true, cx);
 8565            this.change_selections(auto_scroll, cx, |s| {
 8566                if replace_newest {
 8567                    s.delete(s.newest_anchor().id);
 8568                }
 8569                s.insert_range(range.clone());
 8570            });
 8571        }
 8572
 8573        let buffer = &display_map.buffer_snapshot;
 8574        let mut selections = self.selections.all::<usize>(cx);
 8575        if let Some(mut select_next_state) = self.select_next_state.take() {
 8576            let query = &select_next_state.query;
 8577            if !select_next_state.done {
 8578                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8579                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8580                let mut next_selected_range = None;
 8581
 8582                let bytes_after_last_selection =
 8583                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8584                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8585                let query_matches = query
 8586                    .stream_find_iter(bytes_after_last_selection)
 8587                    .map(|result| (last_selection.end, result))
 8588                    .chain(
 8589                        query
 8590                            .stream_find_iter(bytes_before_first_selection)
 8591                            .map(|result| (0, result)),
 8592                    );
 8593
 8594                for (start_offset, query_match) in query_matches {
 8595                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8596                    let offset_range =
 8597                        start_offset + query_match.start()..start_offset + query_match.end();
 8598                    let display_range = offset_range.start.to_display_point(display_map)
 8599                        ..offset_range.end.to_display_point(display_map);
 8600
 8601                    if !select_next_state.wordwise
 8602                        || (!movement::is_inside_word(display_map, display_range.start)
 8603                            && !movement::is_inside_word(display_map, display_range.end))
 8604                    {
 8605                        // TODO: This is n^2, because we might check all the selections
 8606                        if !selections
 8607                            .iter()
 8608                            .any(|selection| selection.range().overlaps(&offset_range))
 8609                        {
 8610                            next_selected_range = Some(offset_range);
 8611                            break;
 8612                        }
 8613                    }
 8614                }
 8615
 8616                if let Some(next_selected_range) = next_selected_range {
 8617                    select_next_match_ranges(
 8618                        self,
 8619                        next_selected_range,
 8620                        replace_newest,
 8621                        autoscroll,
 8622                        cx,
 8623                    );
 8624                } else {
 8625                    select_next_state.done = true;
 8626                }
 8627            }
 8628
 8629            self.select_next_state = Some(select_next_state);
 8630        } else {
 8631            let mut only_carets = true;
 8632            let mut same_text_selected = true;
 8633            let mut selected_text = None;
 8634
 8635            let mut selections_iter = selections.iter().peekable();
 8636            while let Some(selection) = selections_iter.next() {
 8637                if selection.start != selection.end {
 8638                    only_carets = false;
 8639                }
 8640
 8641                if same_text_selected {
 8642                    if selected_text.is_none() {
 8643                        selected_text =
 8644                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8645                    }
 8646
 8647                    if let Some(next_selection) = selections_iter.peek() {
 8648                        if next_selection.range().len() == selection.range().len() {
 8649                            let next_selected_text = buffer
 8650                                .text_for_range(next_selection.range())
 8651                                .collect::<String>();
 8652                            if Some(next_selected_text) != selected_text {
 8653                                same_text_selected = false;
 8654                                selected_text = None;
 8655                            }
 8656                        } else {
 8657                            same_text_selected = false;
 8658                            selected_text = None;
 8659                        }
 8660                    }
 8661                }
 8662            }
 8663
 8664            if only_carets {
 8665                for selection in &mut selections {
 8666                    let word_range = movement::surrounding_word(
 8667                        display_map,
 8668                        selection.start.to_display_point(display_map),
 8669                    );
 8670                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8671                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8672                    selection.goal = SelectionGoal::None;
 8673                    selection.reversed = false;
 8674                    select_next_match_ranges(
 8675                        self,
 8676                        selection.start..selection.end,
 8677                        replace_newest,
 8678                        autoscroll,
 8679                        cx,
 8680                    );
 8681                }
 8682
 8683                if selections.len() == 1 {
 8684                    let selection = selections
 8685                        .last()
 8686                        .expect("ensured that there's only one selection");
 8687                    let query = buffer
 8688                        .text_for_range(selection.start..selection.end)
 8689                        .collect::<String>();
 8690                    let is_empty = query.is_empty();
 8691                    let select_state = SelectNextState {
 8692                        query: AhoCorasick::new(&[query])?,
 8693                        wordwise: true,
 8694                        done: is_empty,
 8695                    };
 8696                    self.select_next_state = Some(select_state);
 8697                } else {
 8698                    self.select_next_state = None;
 8699                }
 8700            } else if let Some(selected_text) = selected_text {
 8701                self.select_next_state = Some(SelectNextState {
 8702                    query: AhoCorasick::new(&[selected_text])?,
 8703                    wordwise: false,
 8704                    done: false,
 8705                });
 8706                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8707            }
 8708        }
 8709        Ok(())
 8710    }
 8711
 8712    pub fn select_all_matches(
 8713        &mut self,
 8714        _action: &SelectAllMatches,
 8715        cx: &mut ViewContext<Self>,
 8716    ) -> Result<()> {
 8717        self.push_to_selection_history();
 8718        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8719
 8720        self.select_next_match_internal(&display_map, false, None, cx)?;
 8721        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8722            return Ok(());
 8723        };
 8724        if select_next_state.done {
 8725            return Ok(());
 8726        }
 8727
 8728        let mut new_selections = self.selections.all::<usize>(cx);
 8729
 8730        let buffer = &display_map.buffer_snapshot;
 8731        let query_matches = select_next_state
 8732            .query
 8733            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8734
 8735        for query_match in query_matches {
 8736            let query_match = query_match.unwrap(); // can only fail due to I/O
 8737            let offset_range = query_match.start()..query_match.end();
 8738            let display_range = offset_range.start.to_display_point(&display_map)
 8739                ..offset_range.end.to_display_point(&display_map);
 8740
 8741            if !select_next_state.wordwise
 8742                || (!movement::is_inside_word(&display_map, display_range.start)
 8743                    && !movement::is_inside_word(&display_map, display_range.end))
 8744            {
 8745                self.selections.change_with(cx, |selections| {
 8746                    new_selections.push(Selection {
 8747                        id: selections.new_selection_id(),
 8748                        start: offset_range.start,
 8749                        end: offset_range.end,
 8750                        reversed: false,
 8751                        goal: SelectionGoal::None,
 8752                    });
 8753                });
 8754            }
 8755        }
 8756
 8757        new_selections.sort_by_key(|selection| selection.start);
 8758        let mut ix = 0;
 8759        while ix + 1 < new_selections.len() {
 8760            let current_selection = &new_selections[ix];
 8761            let next_selection = &new_selections[ix + 1];
 8762            if current_selection.range().overlaps(&next_selection.range()) {
 8763                if current_selection.id < next_selection.id {
 8764                    new_selections.remove(ix + 1);
 8765                } else {
 8766                    new_selections.remove(ix);
 8767                }
 8768            } else {
 8769                ix += 1;
 8770            }
 8771        }
 8772
 8773        select_next_state.done = true;
 8774        self.unfold_ranges(
 8775            &new_selections
 8776                .iter()
 8777                .map(|selection| selection.range())
 8778                .collect::<Vec<_>>(),
 8779            false,
 8780            false,
 8781            cx,
 8782        );
 8783        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8784            selections.select(new_selections)
 8785        });
 8786
 8787        Ok(())
 8788    }
 8789
 8790    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8791        self.push_to_selection_history();
 8792        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8793        self.select_next_match_internal(
 8794            &display_map,
 8795            action.replace_newest,
 8796            Some(Autoscroll::newest()),
 8797            cx,
 8798        )?;
 8799        Ok(())
 8800    }
 8801
 8802    pub fn select_previous(
 8803        &mut self,
 8804        action: &SelectPrevious,
 8805        cx: &mut ViewContext<Self>,
 8806    ) -> Result<()> {
 8807        self.push_to_selection_history();
 8808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8809        let buffer = &display_map.buffer_snapshot;
 8810        let mut selections = self.selections.all::<usize>(cx);
 8811        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8812            let query = &select_prev_state.query;
 8813            if !select_prev_state.done {
 8814                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8815                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8816                let mut next_selected_range = None;
 8817                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8818                let bytes_before_last_selection =
 8819                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8820                let bytes_after_first_selection =
 8821                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8822                let query_matches = query
 8823                    .stream_find_iter(bytes_before_last_selection)
 8824                    .map(|result| (last_selection.start, result))
 8825                    .chain(
 8826                        query
 8827                            .stream_find_iter(bytes_after_first_selection)
 8828                            .map(|result| (buffer.len(), result)),
 8829                    );
 8830                for (end_offset, query_match) in query_matches {
 8831                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8832                    let offset_range =
 8833                        end_offset - query_match.end()..end_offset - query_match.start();
 8834                    let display_range = offset_range.start.to_display_point(&display_map)
 8835                        ..offset_range.end.to_display_point(&display_map);
 8836
 8837                    if !select_prev_state.wordwise
 8838                        || (!movement::is_inside_word(&display_map, display_range.start)
 8839                            && !movement::is_inside_word(&display_map, display_range.end))
 8840                    {
 8841                        next_selected_range = Some(offset_range);
 8842                        break;
 8843                    }
 8844                }
 8845
 8846                if let Some(next_selected_range) = next_selected_range {
 8847                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8848                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8849                        if action.replace_newest {
 8850                            s.delete(s.newest_anchor().id);
 8851                        }
 8852                        s.insert_range(next_selected_range);
 8853                    });
 8854                } else {
 8855                    select_prev_state.done = true;
 8856                }
 8857            }
 8858
 8859            self.select_prev_state = Some(select_prev_state);
 8860        } else {
 8861            let mut only_carets = true;
 8862            let mut same_text_selected = true;
 8863            let mut selected_text = None;
 8864
 8865            let mut selections_iter = selections.iter().peekable();
 8866            while let Some(selection) = selections_iter.next() {
 8867                if selection.start != selection.end {
 8868                    only_carets = false;
 8869                }
 8870
 8871                if same_text_selected {
 8872                    if selected_text.is_none() {
 8873                        selected_text =
 8874                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8875                    }
 8876
 8877                    if let Some(next_selection) = selections_iter.peek() {
 8878                        if next_selection.range().len() == selection.range().len() {
 8879                            let next_selected_text = buffer
 8880                                .text_for_range(next_selection.range())
 8881                                .collect::<String>();
 8882                            if Some(next_selected_text) != selected_text {
 8883                                same_text_selected = false;
 8884                                selected_text = None;
 8885                            }
 8886                        } else {
 8887                            same_text_selected = false;
 8888                            selected_text = None;
 8889                        }
 8890                    }
 8891                }
 8892            }
 8893
 8894            if only_carets {
 8895                for selection in &mut selections {
 8896                    let word_range = movement::surrounding_word(
 8897                        &display_map,
 8898                        selection.start.to_display_point(&display_map),
 8899                    );
 8900                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8901                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8902                    selection.goal = SelectionGoal::None;
 8903                    selection.reversed = false;
 8904                }
 8905                if selections.len() == 1 {
 8906                    let selection = selections
 8907                        .last()
 8908                        .expect("ensured that there's only one selection");
 8909                    let query = buffer
 8910                        .text_for_range(selection.start..selection.end)
 8911                        .collect::<String>();
 8912                    let is_empty = query.is_empty();
 8913                    let select_state = SelectNextState {
 8914                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8915                        wordwise: true,
 8916                        done: is_empty,
 8917                    };
 8918                    self.select_prev_state = Some(select_state);
 8919                } else {
 8920                    self.select_prev_state = None;
 8921                }
 8922
 8923                self.unfold_ranges(
 8924                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8925                    false,
 8926                    true,
 8927                    cx,
 8928                );
 8929                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8930                    s.select(selections);
 8931                });
 8932            } else if let Some(selected_text) = selected_text {
 8933                self.select_prev_state = Some(SelectNextState {
 8934                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8935                    wordwise: false,
 8936                    done: false,
 8937                });
 8938                self.select_previous(action, cx)?;
 8939            }
 8940        }
 8941        Ok(())
 8942    }
 8943
 8944    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8945        if self.read_only(cx) {
 8946            return;
 8947        }
 8948        let text_layout_details = &self.text_layout_details(cx);
 8949        self.transact(cx, |this, cx| {
 8950            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8951            let mut edits = Vec::new();
 8952            let mut selection_edit_ranges = Vec::new();
 8953            let mut last_toggled_row = None;
 8954            let snapshot = this.buffer.read(cx).read(cx);
 8955            let empty_str: Arc<str> = Arc::default();
 8956            let mut suffixes_inserted = Vec::new();
 8957            let ignore_indent = action.ignore_indent;
 8958
 8959            fn comment_prefix_range(
 8960                snapshot: &MultiBufferSnapshot,
 8961                row: MultiBufferRow,
 8962                comment_prefix: &str,
 8963                comment_prefix_whitespace: &str,
 8964                ignore_indent: bool,
 8965            ) -> Range<Point> {
 8966                let indent_size = if ignore_indent {
 8967                    0
 8968                } else {
 8969                    snapshot.indent_size_for_line(row).len
 8970                };
 8971
 8972                let start = Point::new(row.0, indent_size);
 8973
 8974                let mut line_bytes = snapshot
 8975                    .bytes_in_range(start..snapshot.max_point())
 8976                    .flatten()
 8977                    .copied();
 8978
 8979                // If this line currently begins with the line comment prefix, then record
 8980                // the range containing the prefix.
 8981                if line_bytes
 8982                    .by_ref()
 8983                    .take(comment_prefix.len())
 8984                    .eq(comment_prefix.bytes())
 8985                {
 8986                    // Include any whitespace that matches the comment prefix.
 8987                    let matching_whitespace_len = line_bytes
 8988                        .zip(comment_prefix_whitespace.bytes())
 8989                        .take_while(|(a, b)| a == b)
 8990                        .count() as u32;
 8991                    let end = Point::new(
 8992                        start.row,
 8993                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8994                    );
 8995                    start..end
 8996                } else {
 8997                    start..start
 8998                }
 8999            }
 9000
 9001            fn comment_suffix_range(
 9002                snapshot: &MultiBufferSnapshot,
 9003                row: MultiBufferRow,
 9004                comment_suffix: &str,
 9005                comment_suffix_has_leading_space: bool,
 9006            ) -> Range<Point> {
 9007                let end = Point::new(row.0, snapshot.line_len(row));
 9008                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9009
 9010                let mut line_end_bytes = snapshot
 9011                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9012                    .flatten()
 9013                    .copied();
 9014
 9015                let leading_space_len = if suffix_start_column > 0
 9016                    && line_end_bytes.next() == Some(b' ')
 9017                    && comment_suffix_has_leading_space
 9018                {
 9019                    1
 9020                } else {
 9021                    0
 9022                };
 9023
 9024                // If this line currently begins with the line comment prefix, then record
 9025                // the range containing the prefix.
 9026                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9027                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9028                    start..end
 9029                } else {
 9030                    end..end
 9031                }
 9032            }
 9033
 9034            // TODO: Handle selections that cross excerpts
 9035            for selection in &mut selections {
 9036                let start_column = snapshot
 9037                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9038                    .len;
 9039                let language = if let Some(language) =
 9040                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9041                {
 9042                    language
 9043                } else {
 9044                    continue;
 9045                };
 9046
 9047                selection_edit_ranges.clear();
 9048
 9049                // If multiple selections contain a given row, avoid processing that
 9050                // row more than once.
 9051                let mut start_row = MultiBufferRow(selection.start.row);
 9052                if last_toggled_row == Some(start_row) {
 9053                    start_row = start_row.next_row();
 9054                }
 9055                let end_row =
 9056                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9057                        MultiBufferRow(selection.end.row - 1)
 9058                    } else {
 9059                        MultiBufferRow(selection.end.row)
 9060                    };
 9061                last_toggled_row = Some(end_row);
 9062
 9063                if start_row > end_row {
 9064                    continue;
 9065                }
 9066
 9067                // If the language has line comments, toggle those.
 9068                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9069
 9070                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9071                if ignore_indent {
 9072                    full_comment_prefixes = full_comment_prefixes
 9073                        .into_iter()
 9074                        .map(|s| Arc::from(s.trim_end()))
 9075                        .collect();
 9076                }
 9077
 9078                if !full_comment_prefixes.is_empty() {
 9079                    let first_prefix = full_comment_prefixes
 9080                        .first()
 9081                        .expect("prefixes is non-empty");
 9082                    let prefix_trimmed_lengths = full_comment_prefixes
 9083                        .iter()
 9084                        .map(|p| p.trim_end_matches(' ').len())
 9085                        .collect::<SmallVec<[usize; 4]>>();
 9086
 9087                    let mut all_selection_lines_are_comments = true;
 9088
 9089                    for row in start_row.0..=end_row.0 {
 9090                        let row = MultiBufferRow(row);
 9091                        if start_row < end_row && snapshot.is_line_blank(row) {
 9092                            continue;
 9093                        }
 9094
 9095                        let prefix_range = full_comment_prefixes
 9096                            .iter()
 9097                            .zip(prefix_trimmed_lengths.iter().copied())
 9098                            .map(|(prefix, trimmed_prefix_len)| {
 9099                                comment_prefix_range(
 9100                                    snapshot.deref(),
 9101                                    row,
 9102                                    &prefix[..trimmed_prefix_len],
 9103                                    &prefix[trimmed_prefix_len..],
 9104                                    ignore_indent,
 9105                                )
 9106                            })
 9107                            .max_by_key(|range| range.end.column - range.start.column)
 9108                            .expect("prefixes is non-empty");
 9109
 9110                        if prefix_range.is_empty() {
 9111                            all_selection_lines_are_comments = false;
 9112                        }
 9113
 9114                        selection_edit_ranges.push(prefix_range);
 9115                    }
 9116
 9117                    if all_selection_lines_are_comments {
 9118                        edits.extend(
 9119                            selection_edit_ranges
 9120                                .iter()
 9121                                .cloned()
 9122                                .map(|range| (range, empty_str.clone())),
 9123                        );
 9124                    } else {
 9125                        let min_column = selection_edit_ranges
 9126                            .iter()
 9127                            .map(|range| range.start.column)
 9128                            .min()
 9129                            .unwrap_or(0);
 9130                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9131                            let position = Point::new(range.start.row, min_column);
 9132                            (position..position, first_prefix.clone())
 9133                        }));
 9134                    }
 9135                } else if let Some((full_comment_prefix, comment_suffix)) =
 9136                    language.block_comment_delimiters()
 9137                {
 9138                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9139                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9140                    let prefix_range = comment_prefix_range(
 9141                        snapshot.deref(),
 9142                        start_row,
 9143                        comment_prefix,
 9144                        comment_prefix_whitespace,
 9145                        ignore_indent,
 9146                    );
 9147                    let suffix_range = comment_suffix_range(
 9148                        snapshot.deref(),
 9149                        end_row,
 9150                        comment_suffix.trim_start_matches(' '),
 9151                        comment_suffix.starts_with(' '),
 9152                    );
 9153
 9154                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9155                        edits.push((
 9156                            prefix_range.start..prefix_range.start,
 9157                            full_comment_prefix.clone(),
 9158                        ));
 9159                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9160                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9161                    } else {
 9162                        edits.push((prefix_range, empty_str.clone()));
 9163                        edits.push((suffix_range, empty_str.clone()));
 9164                    }
 9165                } else {
 9166                    continue;
 9167                }
 9168            }
 9169
 9170            drop(snapshot);
 9171            this.buffer.update(cx, |buffer, cx| {
 9172                buffer.edit(edits, None, cx);
 9173            });
 9174
 9175            // Adjust selections so that they end before any comment suffixes that
 9176            // were inserted.
 9177            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9178            let mut selections = this.selections.all::<Point>(cx);
 9179            let snapshot = this.buffer.read(cx).read(cx);
 9180            for selection in &mut selections {
 9181                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9182                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9183                        Ordering::Less => {
 9184                            suffixes_inserted.next();
 9185                            continue;
 9186                        }
 9187                        Ordering::Greater => break,
 9188                        Ordering::Equal => {
 9189                            if selection.end.column == snapshot.line_len(row) {
 9190                                if selection.is_empty() {
 9191                                    selection.start.column -= suffix_len as u32;
 9192                                }
 9193                                selection.end.column -= suffix_len as u32;
 9194                            }
 9195                            break;
 9196                        }
 9197                    }
 9198                }
 9199            }
 9200
 9201            drop(snapshot);
 9202            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9203
 9204            let selections = this.selections.all::<Point>(cx);
 9205            let selections_on_single_row = selections.windows(2).all(|selections| {
 9206                selections[0].start.row == selections[1].start.row
 9207                    && selections[0].end.row == selections[1].end.row
 9208                    && selections[0].start.row == selections[0].end.row
 9209            });
 9210            let selections_selecting = selections
 9211                .iter()
 9212                .any(|selection| selection.start != selection.end);
 9213            let advance_downwards = action.advance_downwards
 9214                && selections_on_single_row
 9215                && !selections_selecting
 9216                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9217
 9218            if advance_downwards {
 9219                let snapshot = this.buffer.read(cx).snapshot(cx);
 9220
 9221                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9222                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9223                        let mut point = display_point.to_point(display_snapshot);
 9224                        point.row += 1;
 9225                        point = snapshot.clip_point(point, Bias::Left);
 9226                        let display_point = point.to_display_point(display_snapshot);
 9227                        let goal = SelectionGoal::HorizontalPosition(
 9228                            display_snapshot
 9229                                .x_for_display_point(display_point, text_layout_details)
 9230                                .into(),
 9231                        );
 9232                        (display_point, goal)
 9233                    })
 9234                });
 9235            }
 9236        });
 9237    }
 9238
 9239    pub fn select_enclosing_symbol(
 9240        &mut self,
 9241        _: &SelectEnclosingSymbol,
 9242        cx: &mut ViewContext<Self>,
 9243    ) {
 9244        let buffer = self.buffer.read(cx).snapshot(cx);
 9245        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9246
 9247        fn update_selection(
 9248            selection: &Selection<usize>,
 9249            buffer_snap: &MultiBufferSnapshot,
 9250        ) -> Option<Selection<usize>> {
 9251            let cursor = selection.head();
 9252            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9253            for symbol in symbols.iter().rev() {
 9254                let start = symbol.range.start.to_offset(buffer_snap);
 9255                let end = symbol.range.end.to_offset(buffer_snap);
 9256                let new_range = start..end;
 9257                if start < selection.start || end > selection.end {
 9258                    return Some(Selection {
 9259                        id: selection.id,
 9260                        start: new_range.start,
 9261                        end: new_range.end,
 9262                        goal: SelectionGoal::None,
 9263                        reversed: selection.reversed,
 9264                    });
 9265                }
 9266            }
 9267            None
 9268        }
 9269
 9270        let mut selected_larger_symbol = false;
 9271        let new_selections = old_selections
 9272            .iter()
 9273            .map(|selection| match update_selection(selection, &buffer) {
 9274                Some(new_selection) => {
 9275                    if new_selection.range() != selection.range() {
 9276                        selected_larger_symbol = true;
 9277                    }
 9278                    new_selection
 9279                }
 9280                None => selection.clone(),
 9281            })
 9282            .collect::<Vec<_>>();
 9283
 9284        if selected_larger_symbol {
 9285            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9286                s.select(new_selections);
 9287            });
 9288        }
 9289    }
 9290
 9291    pub fn select_larger_syntax_node(
 9292        &mut self,
 9293        _: &SelectLargerSyntaxNode,
 9294        cx: &mut ViewContext<Self>,
 9295    ) {
 9296        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9297        let buffer = self.buffer.read(cx).snapshot(cx);
 9298        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9299
 9300        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9301        let mut selected_larger_node = false;
 9302        let new_selections = old_selections
 9303            .iter()
 9304            .map(|selection| {
 9305                let old_range = selection.start..selection.end;
 9306                let mut new_range = old_range.clone();
 9307                while let Some(containing_range) =
 9308                    buffer.range_for_syntax_ancestor(new_range.clone())
 9309                {
 9310                    new_range = containing_range;
 9311                    if !display_map.intersects_fold(new_range.start)
 9312                        && !display_map.intersects_fold(new_range.end)
 9313                    {
 9314                        break;
 9315                    }
 9316                }
 9317
 9318                selected_larger_node |= new_range != old_range;
 9319                Selection {
 9320                    id: selection.id,
 9321                    start: new_range.start,
 9322                    end: new_range.end,
 9323                    goal: SelectionGoal::None,
 9324                    reversed: selection.reversed,
 9325                }
 9326            })
 9327            .collect::<Vec<_>>();
 9328
 9329        if selected_larger_node {
 9330            stack.push(old_selections);
 9331            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9332                s.select(new_selections);
 9333            });
 9334        }
 9335        self.select_larger_syntax_node_stack = stack;
 9336    }
 9337
 9338    pub fn select_smaller_syntax_node(
 9339        &mut self,
 9340        _: &SelectSmallerSyntaxNode,
 9341        cx: &mut ViewContext<Self>,
 9342    ) {
 9343        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9344        if let Some(selections) = stack.pop() {
 9345            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9346                s.select(selections.to_vec());
 9347            });
 9348        }
 9349        self.select_larger_syntax_node_stack = stack;
 9350    }
 9351
 9352    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9353        if !EditorSettings::get_global(cx).gutter.runnables {
 9354            self.clear_tasks();
 9355            return Task::ready(());
 9356        }
 9357        let project = self.project.as_ref().map(Model::downgrade);
 9358        cx.spawn(|this, mut cx| async move {
 9359            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9360            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9361                return;
 9362            };
 9363            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9364                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9365            }) else {
 9366                return;
 9367            };
 9368
 9369            let hide_runnables = project
 9370                .update(&mut cx, |project, cx| {
 9371                    // Do not display any test indicators in non-dev server remote projects.
 9372                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9373                })
 9374                .unwrap_or(true);
 9375            if hide_runnables {
 9376                return;
 9377            }
 9378            let new_rows =
 9379                cx.background_executor()
 9380                    .spawn({
 9381                        let snapshot = display_snapshot.clone();
 9382                        async move {
 9383                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9384                        }
 9385                    })
 9386                    .await;
 9387            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9388
 9389            this.update(&mut cx, |this, _| {
 9390                this.clear_tasks();
 9391                for (key, value) in rows {
 9392                    this.insert_tasks(key, value);
 9393                }
 9394            })
 9395            .ok();
 9396        })
 9397    }
 9398    fn fetch_runnable_ranges(
 9399        snapshot: &DisplaySnapshot,
 9400        range: Range<Anchor>,
 9401    ) -> Vec<language::RunnableRange> {
 9402        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9403    }
 9404
 9405    fn runnable_rows(
 9406        project: Model<Project>,
 9407        snapshot: DisplaySnapshot,
 9408        runnable_ranges: Vec<RunnableRange>,
 9409        mut cx: AsyncWindowContext,
 9410    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9411        runnable_ranges
 9412            .into_iter()
 9413            .filter_map(|mut runnable| {
 9414                let tasks = cx
 9415                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9416                    .ok()?;
 9417                if tasks.is_empty() {
 9418                    return None;
 9419                }
 9420
 9421                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9422
 9423                let row = snapshot
 9424                    .buffer_snapshot
 9425                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9426                    .1
 9427                    .start
 9428                    .row;
 9429
 9430                let context_range =
 9431                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9432                Some((
 9433                    (runnable.buffer_id, row),
 9434                    RunnableTasks {
 9435                        templates: tasks,
 9436                        offset: MultiBufferOffset(runnable.run_range.start),
 9437                        context_range,
 9438                        column: point.column,
 9439                        extra_variables: runnable.extra_captures,
 9440                    },
 9441                ))
 9442            })
 9443            .collect()
 9444    }
 9445
 9446    fn templates_with_tags(
 9447        project: &Model<Project>,
 9448        runnable: &mut Runnable,
 9449        cx: &WindowContext<'_>,
 9450    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9451        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9452            let (worktree_id, file) = project
 9453                .buffer_for_id(runnable.buffer, cx)
 9454                .and_then(|buffer| buffer.read(cx).file())
 9455                .map(|file| (file.worktree_id(cx), file.clone()))
 9456                .unzip();
 9457
 9458            (
 9459                project.task_store().read(cx).task_inventory().cloned(),
 9460                worktree_id,
 9461                file,
 9462            )
 9463        });
 9464
 9465        let tags = mem::take(&mut runnable.tags);
 9466        let mut tags: Vec<_> = tags
 9467            .into_iter()
 9468            .flat_map(|tag| {
 9469                let tag = tag.0.clone();
 9470                inventory
 9471                    .as_ref()
 9472                    .into_iter()
 9473                    .flat_map(|inventory| {
 9474                        inventory.read(cx).list_tasks(
 9475                            file.clone(),
 9476                            Some(runnable.language.clone()),
 9477                            worktree_id,
 9478                            cx,
 9479                        )
 9480                    })
 9481                    .filter(move |(_, template)| {
 9482                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9483                    })
 9484            })
 9485            .sorted_by_key(|(kind, _)| kind.to_owned())
 9486            .collect();
 9487        if let Some((leading_tag_source, _)) = tags.first() {
 9488            // Strongest source wins; if we have worktree tag binding, prefer that to
 9489            // global and language bindings;
 9490            // if we have a global binding, prefer that to language binding.
 9491            let first_mismatch = tags
 9492                .iter()
 9493                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9494            if let Some(index) = first_mismatch {
 9495                tags.truncate(index);
 9496            }
 9497        }
 9498
 9499        tags
 9500    }
 9501
 9502    pub fn move_to_enclosing_bracket(
 9503        &mut self,
 9504        _: &MoveToEnclosingBracket,
 9505        cx: &mut ViewContext<Self>,
 9506    ) {
 9507        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9508            s.move_offsets_with(|snapshot, selection| {
 9509                let Some(enclosing_bracket_ranges) =
 9510                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9511                else {
 9512                    return;
 9513                };
 9514
 9515                let mut best_length = usize::MAX;
 9516                let mut best_inside = false;
 9517                let mut best_in_bracket_range = false;
 9518                let mut best_destination = None;
 9519                for (open, close) in enclosing_bracket_ranges {
 9520                    let close = close.to_inclusive();
 9521                    let length = close.end() - open.start;
 9522                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9523                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9524                        || close.contains(&selection.head());
 9525
 9526                    // If best is next to a bracket and current isn't, skip
 9527                    if !in_bracket_range && best_in_bracket_range {
 9528                        continue;
 9529                    }
 9530
 9531                    // Prefer smaller lengths unless best is inside and current isn't
 9532                    if length > best_length && (best_inside || !inside) {
 9533                        continue;
 9534                    }
 9535
 9536                    best_length = length;
 9537                    best_inside = inside;
 9538                    best_in_bracket_range = in_bracket_range;
 9539                    best_destination = Some(
 9540                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9541                            if inside {
 9542                                open.end
 9543                            } else {
 9544                                open.start
 9545                            }
 9546                        } else if inside {
 9547                            *close.start()
 9548                        } else {
 9549                            *close.end()
 9550                        },
 9551                    );
 9552                }
 9553
 9554                if let Some(destination) = best_destination {
 9555                    selection.collapse_to(destination, SelectionGoal::None);
 9556                }
 9557            })
 9558        });
 9559    }
 9560
 9561    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9562        self.end_selection(cx);
 9563        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9564        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9565            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9566            self.select_next_state = entry.select_next_state;
 9567            self.select_prev_state = entry.select_prev_state;
 9568            self.add_selections_state = entry.add_selections_state;
 9569            self.request_autoscroll(Autoscroll::newest(), cx);
 9570        }
 9571        self.selection_history.mode = SelectionHistoryMode::Normal;
 9572    }
 9573
 9574    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9575        self.end_selection(cx);
 9576        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9577        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9578            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9579            self.select_next_state = entry.select_next_state;
 9580            self.select_prev_state = entry.select_prev_state;
 9581            self.add_selections_state = entry.add_selections_state;
 9582            self.request_autoscroll(Autoscroll::newest(), cx);
 9583        }
 9584        self.selection_history.mode = SelectionHistoryMode::Normal;
 9585    }
 9586
 9587    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9588        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9589    }
 9590
 9591    pub fn expand_excerpts_down(
 9592        &mut self,
 9593        action: &ExpandExcerptsDown,
 9594        cx: &mut ViewContext<Self>,
 9595    ) {
 9596        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9597    }
 9598
 9599    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9600        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9601    }
 9602
 9603    pub fn expand_excerpts_for_direction(
 9604        &mut self,
 9605        lines: u32,
 9606        direction: ExpandExcerptDirection,
 9607        cx: &mut ViewContext<Self>,
 9608    ) {
 9609        let selections = self.selections.disjoint_anchors();
 9610
 9611        let lines = if lines == 0 {
 9612            EditorSettings::get_global(cx).expand_excerpt_lines
 9613        } else {
 9614            lines
 9615        };
 9616
 9617        self.buffer.update(cx, |buffer, cx| {
 9618            buffer.expand_excerpts(
 9619                selections
 9620                    .iter()
 9621                    .map(|selection| selection.head().excerpt_id)
 9622                    .dedup(),
 9623                lines,
 9624                direction,
 9625                cx,
 9626            )
 9627        })
 9628    }
 9629
 9630    pub fn expand_excerpt(
 9631        &mut self,
 9632        excerpt: ExcerptId,
 9633        direction: ExpandExcerptDirection,
 9634        cx: &mut ViewContext<Self>,
 9635    ) {
 9636        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9637        self.buffer.update(cx, |buffer, cx| {
 9638            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9639        })
 9640    }
 9641
 9642    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9643        self.go_to_diagnostic_impl(Direction::Next, cx)
 9644    }
 9645
 9646    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9647        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9648    }
 9649
 9650    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9651        let buffer = self.buffer.read(cx).snapshot(cx);
 9652        let selection = self.selections.newest::<usize>(cx);
 9653
 9654        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9655        if direction == Direction::Next {
 9656            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9657                let (group_id, jump_to) = popover.activation_info();
 9658                if self.activate_diagnostics(group_id, cx) {
 9659                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9660                        let mut new_selection = s.newest_anchor().clone();
 9661                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9662                        s.select_anchors(vec![new_selection.clone()]);
 9663                    });
 9664                }
 9665                return;
 9666            }
 9667        }
 9668
 9669        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9670            active_diagnostics
 9671                .primary_range
 9672                .to_offset(&buffer)
 9673                .to_inclusive()
 9674        });
 9675        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9676            if active_primary_range.contains(&selection.head()) {
 9677                *active_primary_range.start()
 9678            } else {
 9679                selection.head()
 9680            }
 9681        } else {
 9682            selection.head()
 9683        };
 9684        let snapshot = self.snapshot(cx);
 9685        loop {
 9686            let diagnostics = if direction == Direction::Prev {
 9687                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9688            } else {
 9689                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9690            }
 9691            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9692            let group = diagnostics
 9693                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9694                // be sorted in a stable way
 9695                // skip until we are at current active diagnostic, if it exists
 9696                .skip_while(|entry| {
 9697                    (match direction {
 9698                        Direction::Prev => entry.range.start >= search_start,
 9699                        Direction::Next => entry.range.start <= search_start,
 9700                    }) && self
 9701                        .active_diagnostics
 9702                        .as_ref()
 9703                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9704                })
 9705                .find_map(|entry| {
 9706                    if entry.diagnostic.is_primary
 9707                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9708                        && !entry.range.is_empty()
 9709                        // if we match with the active diagnostic, skip it
 9710                        && Some(entry.diagnostic.group_id)
 9711                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9712                    {
 9713                        Some((entry.range, entry.diagnostic.group_id))
 9714                    } else {
 9715                        None
 9716                    }
 9717                });
 9718
 9719            if let Some((primary_range, group_id)) = group {
 9720                if self.activate_diagnostics(group_id, cx) {
 9721                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9722                        s.select(vec![Selection {
 9723                            id: selection.id,
 9724                            start: primary_range.start,
 9725                            end: primary_range.start,
 9726                            reversed: false,
 9727                            goal: SelectionGoal::None,
 9728                        }]);
 9729                    });
 9730                }
 9731                break;
 9732            } else {
 9733                // Cycle around to the start of the buffer, potentially moving back to the start of
 9734                // the currently active diagnostic.
 9735                active_primary_range.take();
 9736                if direction == Direction::Prev {
 9737                    if search_start == buffer.len() {
 9738                        break;
 9739                    } else {
 9740                        search_start = buffer.len();
 9741                    }
 9742                } else if search_start == 0 {
 9743                    break;
 9744                } else {
 9745                    search_start = 0;
 9746                }
 9747            }
 9748        }
 9749    }
 9750
 9751    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9752        let snapshot = self
 9753            .display_map
 9754            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9755        let selection = self.selections.newest::<Point>(cx);
 9756        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9757    }
 9758
 9759    fn go_to_hunk_after_position(
 9760        &mut self,
 9761        snapshot: &DisplaySnapshot,
 9762        position: Point,
 9763        cx: &mut ViewContext<'_, Editor>,
 9764    ) -> Option<MultiBufferDiffHunk> {
 9765        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9766            snapshot,
 9767            position,
 9768            false,
 9769            snapshot
 9770                .buffer_snapshot
 9771                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9772            cx,
 9773        ) {
 9774            return Some(hunk);
 9775        }
 9776
 9777        let wrapped_point = Point::zero();
 9778        self.go_to_next_hunk_in_direction(
 9779            snapshot,
 9780            wrapped_point,
 9781            true,
 9782            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9783                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9784            ),
 9785            cx,
 9786        )
 9787    }
 9788
 9789    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9790        let snapshot = self
 9791            .display_map
 9792            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9793        let selection = self.selections.newest::<Point>(cx);
 9794
 9795        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9796    }
 9797
 9798    fn go_to_hunk_before_position(
 9799        &mut self,
 9800        snapshot: &DisplaySnapshot,
 9801        position: Point,
 9802        cx: &mut ViewContext<'_, Editor>,
 9803    ) -> Option<MultiBufferDiffHunk> {
 9804        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9805            snapshot,
 9806            position,
 9807            false,
 9808            snapshot
 9809                .buffer_snapshot
 9810                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9811            cx,
 9812        ) {
 9813            return Some(hunk);
 9814        }
 9815
 9816        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9817        self.go_to_next_hunk_in_direction(
 9818            snapshot,
 9819            wrapped_point,
 9820            true,
 9821            snapshot
 9822                .buffer_snapshot
 9823                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9824            cx,
 9825        )
 9826    }
 9827
 9828    fn go_to_next_hunk_in_direction(
 9829        &mut self,
 9830        snapshot: &DisplaySnapshot,
 9831        initial_point: Point,
 9832        is_wrapped: bool,
 9833        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9834        cx: &mut ViewContext<Editor>,
 9835    ) -> Option<MultiBufferDiffHunk> {
 9836        let display_point = initial_point.to_display_point(snapshot);
 9837        let mut hunks = hunks
 9838            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9839            .filter(|(display_hunk, _)| {
 9840                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9841            })
 9842            .dedup();
 9843
 9844        if let Some((display_hunk, hunk)) = hunks.next() {
 9845            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9846                let row = display_hunk.start_display_row();
 9847                let point = DisplayPoint::new(row, 0);
 9848                s.select_display_ranges([point..point]);
 9849            });
 9850
 9851            Some(hunk)
 9852        } else {
 9853            None
 9854        }
 9855    }
 9856
 9857    pub fn go_to_definition(
 9858        &mut self,
 9859        _: &GoToDefinition,
 9860        cx: &mut ViewContext<Self>,
 9861    ) -> Task<Result<Navigated>> {
 9862        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9863        cx.spawn(|editor, mut cx| async move {
 9864            if definition.await? == Navigated::Yes {
 9865                return Ok(Navigated::Yes);
 9866            }
 9867            match editor.update(&mut cx, |editor, cx| {
 9868                editor.find_all_references(&FindAllReferences, cx)
 9869            })? {
 9870                Some(references) => references.await,
 9871                None => Ok(Navigated::No),
 9872            }
 9873        })
 9874    }
 9875
 9876    pub fn go_to_declaration(
 9877        &mut self,
 9878        _: &GoToDeclaration,
 9879        cx: &mut ViewContext<Self>,
 9880    ) -> Task<Result<Navigated>> {
 9881        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9882    }
 9883
 9884    pub fn go_to_declaration_split(
 9885        &mut self,
 9886        _: &GoToDeclaration,
 9887        cx: &mut ViewContext<Self>,
 9888    ) -> Task<Result<Navigated>> {
 9889        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9890    }
 9891
 9892    pub fn go_to_implementation(
 9893        &mut self,
 9894        _: &GoToImplementation,
 9895        cx: &mut ViewContext<Self>,
 9896    ) -> Task<Result<Navigated>> {
 9897        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9898    }
 9899
 9900    pub fn go_to_implementation_split(
 9901        &mut self,
 9902        _: &GoToImplementationSplit,
 9903        cx: &mut ViewContext<Self>,
 9904    ) -> Task<Result<Navigated>> {
 9905        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9906    }
 9907
 9908    pub fn go_to_type_definition(
 9909        &mut self,
 9910        _: &GoToTypeDefinition,
 9911        cx: &mut ViewContext<Self>,
 9912    ) -> Task<Result<Navigated>> {
 9913        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9914    }
 9915
 9916    pub fn go_to_definition_split(
 9917        &mut self,
 9918        _: &GoToDefinitionSplit,
 9919        cx: &mut ViewContext<Self>,
 9920    ) -> Task<Result<Navigated>> {
 9921        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9922    }
 9923
 9924    pub fn go_to_type_definition_split(
 9925        &mut self,
 9926        _: &GoToTypeDefinitionSplit,
 9927        cx: &mut ViewContext<Self>,
 9928    ) -> Task<Result<Navigated>> {
 9929        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9930    }
 9931
 9932    fn go_to_definition_of_kind(
 9933        &mut self,
 9934        kind: GotoDefinitionKind,
 9935        split: bool,
 9936        cx: &mut ViewContext<Self>,
 9937    ) -> Task<Result<Navigated>> {
 9938        let Some(provider) = self.semantics_provider.clone() else {
 9939            return Task::ready(Ok(Navigated::No));
 9940        };
 9941        let head = self.selections.newest::<usize>(cx).head();
 9942        let buffer = self.buffer.read(cx);
 9943        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9944            text_anchor
 9945        } else {
 9946            return Task::ready(Ok(Navigated::No));
 9947        };
 9948
 9949        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9950            return Task::ready(Ok(Navigated::No));
 9951        };
 9952
 9953        cx.spawn(|editor, mut cx| async move {
 9954            let definitions = definitions.await?;
 9955            let navigated = editor
 9956                .update(&mut cx, |editor, cx| {
 9957                    editor.navigate_to_hover_links(
 9958                        Some(kind),
 9959                        definitions
 9960                            .into_iter()
 9961                            .filter(|location| {
 9962                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9963                            })
 9964                            .map(HoverLink::Text)
 9965                            .collect::<Vec<_>>(),
 9966                        split,
 9967                        cx,
 9968                    )
 9969                })?
 9970                .await?;
 9971            anyhow::Ok(navigated)
 9972        })
 9973    }
 9974
 9975    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9976        let position = self.selections.newest_anchor().head();
 9977        let Some((buffer, buffer_position)) =
 9978            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9979        else {
 9980            return;
 9981        };
 9982
 9983        cx.spawn(|editor, mut cx| async move {
 9984            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9985                editor.update(&mut cx, |_, cx| {
 9986                    cx.open_url(&url);
 9987                })
 9988            } else {
 9989                Ok(())
 9990            }
 9991        })
 9992        .detach();
 9993    }
 9994
 9995    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9996        let Some(workspace) = self.workspace() else {
 9997            return;
 9998        };
 9999
10000        let position = self.selections.newest_anchor().head();
10001
10002        let Some((buffer, buffer_position)) =
10003            self.buffer.read(cx).text_anchor_for_position(position, cx)
10004        else {
10005            return;
10006        };
10007
10008        let project = self.project.clone();
10009
10010        cx.spawn(|_, mut cx| async move {
10011            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10012
10013            if let Some((_, path)) = result {
10014                workspace
10015                    .update(&mut cx, |workspace, cx| {
10016                        workspace.open_resolved_path(path, cx)
10017                    })?
10018                    .await?;
10019            }
10020            anyhow::Ok(())
10021        })
10022        .detach();
10023    }
10024
10025    pub(crate) fn navigate_to_hover_links(
10026        &mut self,
10027        kind: Option<GotoDefinitionKind>,
10028        mut definitions: Vec<HoverLink>,
10029        split: bool,
10030        cx: &mut ViewContext<Editor>,
10031    ) -> Task<Result<Navigated>> {
10032        // If there is one definition, just open it directly
10033        if definitions.len() == 1 {
10034            let definition = definitions.pop().unwrap();
10035
10036            enum TargetTaskResult {
10037                Location(Option<Location>),
10038                AlreadyNavigated,
10039            }
10040
10041            let target_task = match definition {
10042                HoverLink::Text(link) => {
10043                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10044                }
10045                HoverLink::InlayHint(lsp_location, server_id) => {
10046                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10047                    cx.background_executor().spawn(async move {
10048                        let location = computation.await?;
10049                        Ok(TargetTaskResult::Location(location))
10050                    })
10051                }
10052                HoverLink::Url(url) => {
10053                    cx.open_url(&url);
10054                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10055                }
10056                HoverLink::File(path) => {
10057                    if let Some(workspace) = self.workspace() {
10058                        cx.spawn(|_, mut cx| async move {
10059                            workspace
10060                                .update(&mut cx, |workspace, cx| {
10061                                    workspace.open_resolved_path(path, cx)
10062                                })?
10063                                .await
10064                                .map(|_| TargetTaskResult::AlreadyNavigated)
10065                        })
10066                    } else {
10067                        Task::ready(Ok(TargetTaskResult::Location(None)))
10068                    }
10069                }
10070            };
10071            cx.spawn(|editor, mut cx| async move {
10072                let target = match target_task.await.context("target resolution task")? {
10073                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10074                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10075                    TargetTaskResult::Location(Some(target)) => target,
10076                };
10077
10078                editor.update(&mut cx, |editor, cx| {
10079                    let Some(workspace) = editor.workspace() else {
10080                        return Navigated::No;
10081                    };
10082                    let pane = workspace.read(cx).active_pane().clone();
10083
10084                    let range = target.range.to_offset(target.buffer.read(cx));
10085                    let range = editor.range_for_match(&range);
10086
10087                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10088                        let buffer = target.buffer.read(cx);
10089                        let range = check_multiline_range(buffer, range);
10090                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10091                            s.select_ranges([range]);
10092                        });
10093                    } else {
10094                        cx.window_context().defer(move |cx| {
10095                            let target_editor: View<Self> =
10096                                workspace.update(cx, |workspace, cx| {
10097                                    let pane = if split {
10098                                        workspace.adjacent_pane(cx)
10099                                    } else {
10100                                        workspace.active_pane().clone()
10101                                    };
10102
10103                                    workspace.open_project_item(
10104                                        pane,
10105                                        target.buffer.clone(),
10106                                        true,
10107                                        true,
10108                                        cx,
10109                                    )
10110                                });
10111                            target_editor.update(cx, |target_editor, cx| {
10112                                // When selecting a definition in a different buffer, disable the nav history
10113                                // to avoid creating a history entry at the previous cursor location.
10114                                pane.update(cx, |pane, _| pane.disable_history());
10115                                let buffer = target.buffer.read(cx);
10116                                let range = check_multiline_range(buffer, range);
10117                                target_editor.change_selections(
10118                                    Some(Autoscroll::focused()),
10119                                    cx,
10120                                    |s| {
10121                                        s.select_ranges([range]);
10122                                    },
10123                                );
10124                                pane.update(cx, |pane, _| pane.enable_history());
10125                            });
10126                        });
10127                    }
10128                    Navigated::Yes
10129                })
10130            })
10131        } else if !definitions.is_empty() {
10132            cx.spawn(|editor, mut cx| async move {
10133                let (title, location_tasks, workspace) = editor
10134                    .update(&mut cx, |editor, cx| {
10135                        let tab_kind = match kind {
10136                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10137                            _ => "Definitions",
10138                        };
10139                        let title = definitions
10140                            .iter()
10141                            .find_map(|definition| match definition {
10142                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10143                                    let buffer = origin.buffer.read(cx);
10144                                    format!(
10145                                        "{} for {}",
10146                                        tab_kind,
10147                                        buffer
10148                                            .text_for_range(origin.range.clone())
10149                                            .collect::<String>()
10150                                    )
10151                                }),
10152                                HoverLink::InlayHint(_, _) => None,
10153                                HoverLink::Url(_) => None,
10154                                HoverLink::File(_) => None,
10155                            })
10156                            .unwrap_or(tab_kind.to_string());
10157                        let location_tasks = definitions
10158                            .into_iter()
10159                            .map(|definition| match definition {
10160                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10161                                HoverLink::InlayHint(lsp_location, server_id) => {
10162                                    editor.compute_target_location(lsp_location, server_id, cx)
10163                                }
10164                                HoverLink::Url(_) => Task::ready(Ok(None)),
10165                                HoverLink::File(_) => Task::ready(Ok(None)),
10166                            })
10167                            .collect::<Vec<_>>();
10168                        (title, location_tasks, editor.workspace().clone())
10169                    })
10170                    .context("location tasks preparation")?;
10171
10172                let locations = future::join_all(location_tasks)
10173                    .await
10174                    .into_iter()
10175                    .filter_map(|location| location.transpose())
10176                    .collect::<Result<_>>()
10177                    .context("location tasks")?;
10178
10179                let Some(workspace) = workspace else {
10180                    return Ok(Navigated::No);
10181                };
10182                let opened = workspace
10183                    .update(&mut cx, |workspace, cx| {
10184                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10185                    })
10186                    .ok();
10187
10188                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10189            })
10190        } else {
10191            Task::ready(Ok(Navigated::No))
10192        }
10193    }
10194
10195    fn compute_target_location(
10196        &self,
10197        lsp_location: lsp::Location,
10198        server_id: LanguageServerId,
10199        cx: &mut ViewContext<Self>,
10200    ) -> Task<anyhow::Result<Option<Location>>> {
10201        let Some(project) = self.project.clone() else {
10202            return Task::Ready(Some(Ok(None)));
10203        };
10204
10205        cx.spawn(move |editor, mut cx| async move {
10206            let location_task = editor.update(&mut cx, |_, cx| {
10207                project.update(cx, |project, cx| {
10208                    let language_server_name = project
10209                        .language_server_statuses(cx)
10210                        .find(|(id, _)| server_id == *id)
10211                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10212                    language_server_name.map(|language_server_name| {
10213                        project.open_local_buffer_via_lsp(
10214                            lsp_location.uri.clone(),
10215                            server_id,
10216                            language_server_name,
10217                            cx,
10218                        )
10219                    })
10220                })
10221            })?;
10222            let location = match location_task {
10223                Some(task) => Some({
10224                    let target_buffer_handle = task.await.context("open local buffer")?;
10225                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10226                        let target_start = target_buffer
10227                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10228                        let target_end = target_buffer
10229                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10230                        target_buffer.anchor_after(target_start)
10231                            ..target_buffer.anchor_before(target_end)
10232                    })?;
10233                    Location {
10234                        buffer: target_buffer_handle,
10235                        range,
10236                    }
10237                }),
10238                None => None,
10239            };
10240            Ok(location)
10241        })
10242    }
10243
10244    pub fn find_all_references(
10245        &mut self,
10246        _: &FindAllReferences,
10247        cx: &mut ViewContext<Self>,
10248    ) -> Option<Task<Result<Navigated>>> {
10249        let selection = self.selections.newest::<usize>(cx);
10250        let multi_buffer = self.buffer.read(cx);
10251        let head = selection.head();
10252
10253        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10254        let head_anchor = multi_buffer_snapshot.anchor_at(
10255            head,
10256            if head < selection.tail() {
10257                Bias::Right
10258            } else {
10259                Bias::Left
10260            },
10261        );
10262
10263        match self
10264            .find_all_references_task_sources
10265            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10266        {
10267            Ok(_) => {
10268                log::info!(
10269                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10270                );
10271                return None;
10272            }
10273            Err(i) => {
10274                self.find_all_references_task_sources.insert(i, head_anchor);
10275            }
10276        }
10277
10278        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10279        let workspace = self.workspace()?;
10280        let project = workspace.read(cx).project().clone();
10281        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10282        Some(cx.spawn(|editor, mut cx| async move {
10283            let _cleanup = defer({
10284                let mut cx = cx.clone();
10285                move || {
10286                    let _ = editor.update(&mut cx, |editor, _| {
10287                        if let Ok(i) =
10288                            editor
10289                                .find_all_references_task_sources
10290                                .binary_search_by(|anchor| {
10291                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10292                                })
10293                        {
10294                            editor.find_all_references_task_sources.remove(i);
10295                        }
10296                    });
10297                }
10298            });
10299
10300            let locations = references.await?;
10301            if locations.is_empty() {
10302                return anyhow::Ok(Navigated::No);
10303            }
10304
10305            workspace.update(&mut cx, |workspace, cx| {
10306                let title = locations
10307                    .first()
10308                    .as_ref()
10309                    .map(|location| {
10310                        let buffer = location.buffer.read(cx);
10311                        format!(
10312                            "References to `{}`",
10313                            buffer
10314                                .text_for_range(location.range.clone())
10315                                .collect::<String>()
10316                        )
10317                    })
10318                    .unwrap();
10319                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10320                Navigated::Yes
10321            })
10322        }))
10323    }
10324
10325    /// Opens a multibuffer with the given project locations in it
10326    pub fn open_locations_in_multibuffer(
10327        workspace: &mut Workspace,
10328        mut locations: Vec<Location>,
10329        title: String,
10330        split: bool,
10331        cx: &mut ViewContext<Workspace>,
10332    ) {
10333        // If there are multiple definitions, open them in a multibuffer
10334        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10335        let mut locations = locations.into_iter().peekable();
10336        let mut ranges_to_highlight = Vec::new();
10337        let capability = workspace.project().read(cx).capability();
10338
10339        let excerpt_buffer = cx.new_model(|cx| {
10340            let mut multibuffer = MultiBuffer::new(capability);
10341            while let Some(location) = locations.next() {
10342                let buffer = location.buffer.read(cx);
10343                let mut ranges_for_buffer = Vec::new();
10344                let range = location.range.to_offset(buffer);
10345                ranges_for_buffer.push(range.clone());
10346
10347                while let Some(next_location) = locations.peek() {
10348                    if next_location.buffer == location.buffer {
10349                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10350                        locations.next();
10351                    } else {
10352                        break;
10353                    }
10354                }
10355
10356                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10357                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10358                    location.buffer.clone(),
10359                    ranges_for_buffer,
10360                    DEFAULT_MULTIBUFFER_CONTEXT,
10361                    cx,
10362                ))
10363            }
10364
10365            multibuffer.with_title(title)
10366        });
10367
10368        let editor = cx.new_view(|cx| {
10369            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10370        });
10371        editor.update(cx, |editor, cx| {
10372            if let Some(first_range) = ranges_to_highlight.first() {
10373                editor.change_selections(None, cx, |selections| {
10374                    selections.clear_disjoint();
10375                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10376                });
10377            }
10378            editor.highlight_background::<Self>(
10379                &ranges_to_highlight,
10380                |theme| theme.editor_highlighted_line_background,
10381                cx,
10382            );
10383        });
10384
10385        let item = Box::new(editor);
10386        let item_id = item.item_id();
10387
10388        if split {
10389            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10390        } else {
10391            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10392                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10393                    pane.close_current_preview_item(cx)
10394                } else {
10395                    None
10396                }
10397            });
10398            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10399        }
10400        workspace.active_pane().update(cx, |pane, cx| {
10401            pane.set_preview_item_id(Some(item_id), cx);
10402        });
10403    }
10404
10405    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10406        use language::ToOffset as _;
10407
10408        let provider = self.semantics_provider.clone()?;
10409        let selection = self.selections.newest_anchor().clone();
10410        let (cursor_buffer, cursor_buffer_position) = self
10411            .buffer
10412            .read(cx)
10413            .text_anchor_for_position(selection.head(), cx)?;
10414        let (tail_buffer, cursor_buffer_position_end) = self
10415            .buffer
10416            .read(cx)
10417            .text_anchor_for_position(selection.tail(), cx)?;
10418        if tail_buffer != cursor_buffer {
10419            return None;
10420        }
10421
10422        let snapshot = cursor_buffer.read(cx).snapshot();
10423        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10424        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10425        let prepare_rename = provider
10426            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10427            .unwrap_or_else(|| Task::ready(Ok(None)));
10428        drop(snapshot);
10429
10430        Some(cx.spawn(|this, mut cx| async move {
10431            let rename_range = if let Some(range) = prepare_rename.await? {
10432                Some(range)
10433            } else {
10434                this.update(&mut cx, |this, cx| {
10435                    let buffer = this.buffer.read(cx).snapshot(cx);
10436                    let mut buffer_highlights = this
10437                        .document_highlights_for_position(selection.head(), &buffer)
10438                        .filter(|highlight| {
10439                            highlight.start.excerpt_id == selection.head().excerpt_id
10440                                && highlight.end.excerpt_id == selection.head().excerpt_id
10441                        });
10442                    buffer_highlights
10443                        .next()
10444                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10445                })?
10446            };
10447            if let Some(rename_range) = rename_range {
10448                this.update(&mut cx, |this, cx| {
10449                    let snapshot = cursor_buffer.read(cx).snapshot();
10450                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10451                    let cursor_offset_in_rename_range =
10452                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10453                    let cursor_offset_in_rename_range_end =
10454                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10455
10456                    this.take_rename(false, cx);
10457                    let buffer = this.buffer.read(cx).read(cx);
10458                    let cursor_offset = selection.head().to_offset(&buffer);
10459                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10460                    let rename_end = rename_start + rename_buffer_range.len();
10461                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10462                    let mut old_highlight_id = None;
10463                    let old_name: Arc<str> = buffer
10464                        .chunks(rename_start..rename_end, true)
10465                        .map(|chunk| {
10466                            if old_highlight_id.is_none() {
10467                                old_highlight_id = chunk.syntax_highlight_id;
10468                            }
10469                            chunk.text
10470                        })
10471                        .collect::<String>()
10472                        .into();
10473
10474                    drop(buffer);
10475
10476                    // Position the selection in the rename editor so that it matches the current selection.
10477                    this.show_local_selections = false;
10478                    let rename_editor = cx.new_view(|cx| {
10479                        let mut editor = Editor::single_line(cx);
10480                        editor.buffer.update(cx, |buffer, cx| {
10481                            buffer.edit([(0..0, old_name.clone())], None, cx)
10482                        });
10483                        let rename_selection_range = match cursor_offset_in_rename_range
10484                            .cmp(&cursor_offset_in_rename_range_end)
10485                        {
10486                            Ordering::Equal => {
10487                                editor.select_all(&SelectAll, cx);
10488                                return editor;
10489                            }
10490                            Ordering::Less => {
10491                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10492                            }
10493                            Ordering::Greater => {
10494                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10495                            }
10496                        };
10497                        if rename_selection_range.end > old_name.len() {
10498                            editor.select_all(&SelectAll, cx);
10499                        } else {
10500                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10501                                s.select_ranges([rename_selection_range]);
10502                            });
10503                        }
10504                        editor
10505                    });
10506                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10507                        if e == &EditorEvent::Focused {
10508                            cx.emit(EditorEvent::FocusedIn)
10509                        }
10510                    })
10511                    .detach();
10512
10513                    let write_highlights =
10514                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10515                    let read_highlights =
10516                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10517                    let ranges = write_highlights
10518                        .iter()
10519                        .flat_map(|(_, ranges)| ranges.iter())
10520                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10521                        .cloned()
10522                        .collect();
10523
10524                    this.highlight_text::<Rename>(
10525                        ranges,
10526                        HighlightStyle {
10527                            fade_out: Some(0.6),
10528                            ..Default::default()
10529                        },
10530                        cx,
10531                    );
10532                    let rename_focus_handle = rename_editor.focus_handle(cx);
10533                    cx.focus(&rename_focus_handle);
10534                    let block_id = this.insert_blocks(
10535                        [BlockProperties {
10536                            style: BlockStyle::Flex,
10537                            placement: BlockPlacement::Below(range.start),
10538                            height: 1,
10539                            render: Arc::new({
10540                                let rename_editor = rename_editor.clone();
10541                                move |cx: &mut BlockContext| {
10542                                    let mut text_style = cx.editor_style.text.clone();
10543                                    if let Some(highlight_style) = old_highlight_id
10544                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10545                                    {
10546                                        text_style = text_style.highlight(highlight_style);
10547                                    }
10548                                    div()
10549                                        .block_mouse_down()
10550                                        .pl(cx.anchor_x)
10551                                        .child(EditorElement::new(
10552                                            &rename_editor,
10553                                            EditorStyle {
10554                                                background: cx.theme().system().transparent,
10555                                                local_player: cx.editor_style.local_player,
10556                                                text: text_style,
10557                                                scrollbar_width: cx.editor_style.scrollbar_width,
10558                                                syntax: cx.editor_style.syntax.clone(),
10559                                                status: cx.editor_style.status.clone(),
10560                                                inlay_hints_style: HighlightStyle {
10561                                                    font_weight: Some(FontWeight::BOLD),
10562                                                    ..make_inlay_hints_style(cx)
10563                                                },
10564                                                suggestions_style: HighlightStyle {
10565                                                    color: Some(cx.theme().status().predictive),
10566                                                    ..HighlightStyle::default()
10567                                                },
10568                                                ..EditorStyle::default()
10569                                            },
10570                                        ))
10571                                        .into_any_element()
10572                                }
10573                            }),
10574                            priority: 0,
10575                        }],
10576                        Some(Autoscroll::fit()),
10577                        cx,
10578                    )[0];
10579                    this.pending_rename = Some(RenameState {
10580                        range,
10581                        old_name,
10582                        editor: rename_editor,
10583                        block_id,
10584                    });
10585                })?;
10586            }
10587
10588            Ok(())
10589        }))
10590    }
10591
10592    pub fn confirm_rename(
10593        &mut self,
10594        _: &ConfirmRename,
10595        cx: &mut ViewContext<Self>,
10596    ) -> Option<Task<Result<()>>> {
10597        let rename = self.take_rename(false, cx)?;
10598        let workspace = self.workspace()?.downgrade();
10599        let (buffer, start) = self
10600            .buffer
10601            .read(cx)
10602            .text_anchor_for_position(rename.range.start, cx)?;
10603        let (end_buffer, _) = self
10604            .buffer
10605            .read(cx)
10606            .text_anchor_for_position(rename.range.end, cx)?;
10607        if buffer != end_buffer {
10608            return None;
10609        }
10610
10611        let old_name = rename.old_name;
10612        let new_name = rename.editor.read(cx).text(cx);
10613
10614        let rename = self.semantics_provider.as_ref()?.perform_rename(
10615            &buffer,
10616            start,
10617            new_name.clone(),
10618            cx,
10619        )?;
10620
10621        Some(cx.spawn(|editor, mut cx| async move {
10622            let project_transaction = rename.await?;
10623            Self::open_project_transaction(
10624                &editor,
10625                workspace,
10626                project_transaction,
10627                format!("Rename: {}{}", old_name, new_name),
10628                cx.clone(),
10629            )
10630            .await?;
10631
10632            editor.update(&mut cx, |editor, cx| {
10633                editor.refresh_document_highlights(cx);
10634            })?;
10635            Ok(())
10636        }))
10637    }
10638
10639    fn take_rename(
10640        &mut self,
10641        moving_cursor: bool,
10642        cx: &mut ViewContext<Self>,
10643    ) -> Option<RenameState> {
10644        let rename = self.pending_rename.take()?;
10645        if rename.editor.focus_handle(cx).is_focused(cx) {
10646            cx.focus(&self.focus_handle);
10647        }
10648
10649        self.remove_blocks(
10650            [rename.block_id].into_iter().collect(),
10651            Some(Autoscroll::fit()),
10652            cx,
10653        );
10654        self.clear_highlights::<Rename>(cx);
10655        self.show_local_selections = true;
10656
10657        if moving_cursor {
10658            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10659                editor.selections.newest::<usize>(cx).head()
10660            });
10661
10662            // Update the selection to match the position of the selection inside
10663            // the rename editor.
10664            let snapshot = self.buffer.read(cx).read(cx);
10665            let rename_range = rename.range.to_offset(&snapshot);
10666            let cursor_in_editor = snapshot
10667                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10668                .min(rename_range.end);
10669            drop(snapshot);
10670
10671            self.change_selections(None, cx, |s| {
10672                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10673            });
10674        } else {
10675            self.refresh_document_highlights(cx);
10676        }
10677
10678        Some(rename)
10679    }
10680
10681    pub fn pending_rename(&self) -> Option<&RenameState> {
10682        self.pending_rename.as_ref()
10683    }
10684
10685    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10686        let project = match &self.project {
10687            Some(project) => project.clone(),
10688            None => return None,
10689        };
10690
10691        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10692    }
10693
10694    fn format_selections(
10695        &mut self,
10696        _: &FormatSelections,
10697        cx: &mut ViewContext<Self>,
10698    ) -> Option<Task<Result<()>>> {
10699        let project = match &self.project {
10700            Some(project) => project.clone(),
10701            None => return None,
10702        };
10703
10704        let selections = self
10705            .selections
10706            .all_adjusted(cx)
10707            .into_iter()
10708            .filter(|s| !s.is_empty())
10709            .collect_vec();
10710
10711        Some(self.perform_format(
10712            project,
10713            FormatTrigger::Manual,
10714            FormatTarget::Ranges(selections),
10715            cx,
10716        ))
10717    }
10718
10719    fn perform_format(
10720        &mut self,
10721        project: Model<Project>,
10722        trigger: FormatTrigger,
10723        target: FormatTarget,
10724        cx: &mut ViewContext<Self>,
10725    ) -> Task<Result<()>> {
10726        let buffer = self.buffer().clone();
10727        let mut buffers = buffer.read(cx).all_buffers();
10728        if trigger == FormatTrigger::Save {
10729            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10730        }
10731
10732        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10733        let format = project.update(cx, |project, cx| {
10734            project.format(buffers, true, trigger, target, cx)
10735        });
10736
10737        cx.spawn(|_, mut cx| async move {
10738            let transaction = futures::select_biased! {
10739                () = timeout => {
10740                    log::warn!("timed out waiting for formatting");
10741                    None
10742                }
10743                transaction = format.log_err().fuse() => transaction,
10744            };
10745
10746            buffer
10747                .update(&mut cx, |buffer, cx| {
10748                    if let Some(transaction) = transaction {
10749                        if !buffer.is_singleton() {
10750                            buffer.push_transaction(&transaction.0, cx);
10751                        }
10752                    }
10753
10754                    cx.notify();
10755                })
10756                .ok();
10757
10758            Ok(())
10759        })
10760    }
10761
10762    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10763        if let Some(project) = self.project.clone() {
10764            self.buffer.update(cx, |multi_buffer, cx| {
10765                project.update(cx, |project, cx| {
10766                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10767                });
10768            })
10769        }
10770    }
10771
10772    fn cancel_language_server_work(
10773        &mut self,
10774        _: &actions::CancelLanguageServerWork,
10775        cx: &mut ViewContext<Self>,
10776    ) {
10777        if let Some(project) = self.project.clone() {
10778            self.buffer.update(cx, |multi_buffer, cx| {
10779                project.update(cx, |project, cx| {
10780                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10781                });
10782            })
10783        }
10784    }
10785
10786    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10787        cx.show_character_palette();
10788    }
10789
10790    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10791        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10792            let buffer = self.buffer.read(cx).snapshot(cx);
10793            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10794            let is_valid = buffer
10795                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10796                .any(|entry| {
10797                    entry.diagnostic.is_primary
10798                        && !entry.range.is_empty()
10799                        && entry.range.start == primary_range_start
10800                        && entry.diagnostic.message == active_diagnostics.primary_message
10801                });
10802
10803            if is_valid != active_diagnostics.is_valid {
10804                active_diagnostics.is_valid = is_valid;
10805                let mut new_styles = HashMap::default();
10806                for (block_id, diagnostic) in &active_diagnostics.blocks {
10807                    new_styles.insert(
10808                        *block_id,
10809                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10810                    );
10811                }
10812                self.display_map.update(cx, |display_map, _cx| {
10813                    display_map.replace_blocks(new_styles)
10814                });
10815            }
10816        }
10817    }
10818
10819    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10820        self.dismiss_diagnostics(cx);
10821        let snapshot = self.snapshot(cx);
10822        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10823            let buffer = self.buffer.read(cx).snapshot(cx);
10824
10825            let mut primary_range = None;
10826            let mut primary_message = None;
10827            let mut group_end = Point::zero();
10828            let diagnostic_group = buffer
10829                .diagnostic_group::<MultiBufferPoint>(group_id)
10830                .filter_map(|entry| {
10831                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10832                        && (entry.range.start.row == entry.range.end.row
10833                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10834                    {
10835                        return None;
10836                    }
10837                    if entry.range.end > group_end {
10838                        group_end = entry.range.end;
10839                    }
10840                    if entry.diagnostic.is_primary {
10841                        primary_range = Some(entry.range.clone());
10842                        primary_message = Some(entry.diagnostic.message.clone());
10843                    }
10844                    Some(entry)
10845                })
10846                .collect::<Vec<_>>();
10847            let primary_range = primary_range?;
10848            let primary_message = primary_message?;
10849            let primary_range =
10850                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10851
10852            let blocks = display_map
10853                .insert_blocks(
10854                    diagnostic_group.iter().map(|entry| {
10855                        let diagnostic = entry.diagnostic.clone();
10856                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10857                        BlockProperties {
10858                            style: BlockStyle::Fixed,
10859                            placement: BlockPlacement::Below(
10860                                buffer.anchor_after(entry.range.start),
10861                            ),
10862                            height: message_height,
10863                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10864                            priority: 0,
10865                        }
10866                    }),
10867                    cx,
10868                )
10869                .into_iter()
10870                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10871                .collect();
10872
10873            Some(ActiveDiagnosticGroup {
10874                primary_range,
10875                primary_message,
10876                group_id,
10877                blocks,
10878                is_valid: true,
10879            })
10880        });
10881        self.active_diagnostics.is_some()
10882    }
10883
10884    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10885        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10886            self.display_map.update(cx, |display_map, cx| {
10887                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10888            });
10889            cx.notify();
10890        }
10891    }
10892
10893    pub fn set_selections_from_remote(
10894        &mut self,
10895        selections: Vec<Selection<Anchor>>,
10896        pending_selection: Option<Selection<Anchor>>,
10897        cx: &mut ViewContext<Self>,
10898    ) {
10899        let old_cursor_position = self.selections.newest_anchor().head();
10900        self.selections.change_with(cx, |s| {
10901            s.select_anchors(selections);
10902            if let Some(pending_selection) = pending_selection {
10903                s.set_pending(pending_selection, SelectMode::Character);
10904            } else {
10905                s.clear_pending();
10906            }
10907        });
10908        self.selections_did_change(false, &old_cursor_position, true, cx);
10909    }
10910
10911    fn push_to_selection_history(&mut self) {
10912        self.selection_history.push(SelectionHistoryEntry {
10913            selections: self.selections.disjoint_anchors(),
10914            select_next_state: self.select_next_state.clone(),
10915            select_prev_state: self.select_prev_state.clone(),
10916            add_selections_state: self.add_selections_state.clone(),
10917        });
10918    }
10919
10920    pub fn transact(
10921        &mut self,
10922        cx: &mut ViewContext<Self>,
10923        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10924    ) -> Option<TransactionId> {
10925        self.start_transaction_at(Instant::now(), cx);
10926        update(self, cx);
10927        self.end_transaction_at(Instant::now(), cx)
10928    }
10929
10930    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10931        self.end_selection(cx);
10932        if let Some(tx_id) = self
10933            .buffer
10934            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10935        {
10936            self.selection_history
10937                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10938            cx.emit(EditorEvent::TransactionBegun {
10939                transaction_id: tx_id,
10940            })
10941        }
10942    }
10943
10944    fn end_transaction_at(
10945        &mut self,
10946        now: Instant,
10947        cx: &mut ViewContext<Self>,
10948    ) -> Option<TransactionId> {
10949        if let Some(transaction_id) = self
10950            .buffer
10951            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10952        {
10953            if let Some((_, end_selections)) =
10954                self.selection_history.transaction_mut(transaction_id)
10955            {
10956                *end_selections = Some(self.selections.disjoint_anchors());
10957            } else {
10958                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10959            }
10960
10961            cx.emit(EditorEvent::Edited { transaction_id });
10962            Some(transaction_id)
10963        } else {
10964            None
10965        }
10966    }
10967
10968    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10969        let selection = self.selections.newest::<Point>(cx);
10970
10971        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10972        let range = if selection.is_empty() {
10973            let point = selection.head().to_display_point(&display_map);
10974            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10975            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10976                .to_point(&display_map);
10977            start..end
10978        } else {
10979            selection.range()
10980        };
10981        if display_map.folds_in_range(range).next().is_some() {
10982            self.unfold_lines(&Default::default(), cx)
10983        } else {
10984            self.fold(&Default::default(), cx)
10985        }
10986    }
10987
10988    pub fn toggle_fold_recursive(
10989        &mut self,
10990        _: &actions::ToggleFoldRecursive,
10991        cx: &mut ViewContext<Self>,
10992    ) {
10993        let selection = self.selections.newest::<Point>(cx);
10994
10995        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10996        let range = if selection.is_empty() {
10997            let point = selection.head().to_display_point(&display_map);
10998            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10999            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11000                .to_point(&display_map);
11001            start..end
11002        } else {
11003            selection.range()
11004        };
11005        if display_map.folds_in_range(range).next().is_some() {
11006            self.unfold_recursive(&Default::default(), cx)
11007        } else {
11008            self.fold_recursive(&Default::default(), cx)
11009        }
11010    }
11011
11012    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11013        let mut to_fold = Vec::new();
11014        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11015        let selections = self.selections.all_adjusted(cx);
11016
11017        for selection in selections {
11018            let range = selection.range().sorted();
11019            let buffer_start_row = range.start.row;
11020
11021            if range.start.row != range.end.row {
11022                let mut found = false;
11023                let mut row = range.start.row;
11024                while row <= range.end.row {
11025                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11026                        found = true;
11027                        row = crease.range().end.row + 1;
11028                        to_fold.push(crease);
11029                    } else {
11030                        row += 1
11031                    }
11032                }
11033                if found {
11034                    continue;
11035                }
11036            }
11037
11038            for row in (0..=range.start.row).rev() {
11039                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11040                    if crease.range().end.row >= buffer_start_row {
11041                        to_fold.push(crease);
11042                        if row <= range.start.row {
11043                            break;
11044                        }
11045                    }
11046                }
11047            }
11048        }
11049
11050        self.fold_creases(to_fold, true, cx);
11051    }
11052
11053    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11054        if !self.buffer.read(cx).is_singleton() {
11055            return;
11056        }
11057
11058        let fold_at_level = fold_at.level;
11059        let snapshot = self.buffer.read(cx).snapshot(cx);
11060        let mut to_fold = Vec::new();
11061        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11062
11063        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11064            while start_row < end_row {
11065                match self
11066                    .snapshot(cx)
11067                    .crease_for_buffer_row(MultiBufferRow(start_row))
11068                {
11069                    Some(crease) => {
11070                        let nested_start_row = crease.range().start.row + 1;
11071                        let nested_end_row = crease.range().end.row;
11072
11073                        if current_level < fold_at_level {
11074                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11075                        } else if current_level == fold_at_level {
11076                            to_fold.push(crease);
11077                        }
11078
11079                        start_row = nested_end_row + 1;
11080                    }
11081                    None => start_row += 1,
11082                }
11083            }
11084        }
11085
11086        self.fold_creases(to_fold, true, cx);
11087    }
11088
11089    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11090        if !self.buffer.read(cx).is_singleton() {
11091            return;
11092        }
11093
11094        let mut fold_ranges = Vec::new();
11095        let snapshot = self.buffer.read(cx).snapshot(cx);
11096
11097        for row in 0..snapshot.max_row().0 {
11098            if let Some(foldable_range) =
11099                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11100            {
11101                fold_ranges.push(foldable_range);
11102            }
11103        }
11104
11105        self.fold_creases(fold_ranges, true, cx);
11106    }
11107
11108    pub fn fold_function_bodies(
11109        &mut self,
11110        _: &actions::FoldFunctionBodies,
11111        cx: &mut ViewContext<Self>,
11112    ) {
11113        let snapshot = self.buffer.read(cx).snapshot(cx);
11114        let Some((_, _, buffer)) = snapshot.as_singleton() else {
11115            return;
11116        };
11117        let creases = buffer
11118            .function_body_fold_ranges(0..buffer.len())
11119            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11120            .collect();
11121
11122        self.fold_creases(creases, true, cx);
11123    }
11124
11125    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11126        let mut to_fold = Vec::new();
11127        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11128        let selections = self.selections.all_adjusted(cx);
11129
11130        for selection in selections {
11131            let range = selection.range().sorted();
11132            let buffer_start_row = range.start.row;
11133
11134            if range.start.row != range.end.row {
11135                let mut found = false;
11136                for row in range.start.row..=range.end.row {
11137                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11138                        found = true;
11139                        to_fold.push(crease);
11140                    }
11141                }
11142                if found {
11143                    continue;
11144                }
11145            }
11146
11147            for row in (0..=range.start.row).rev() {
11148                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11149                    if crease.range().end.row >= buffer_start_row {
11150                        to_fold.push(crease);
11151                    } else {
11152                        break;
11153                    }
11154                }
11155            }
11156        }
11157
11158        self.fold_creases(to_fold, true, cx);
11159    }
11160
11161    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11162        let buffer_row = fold_at.buffer_row;
11163        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11164
11165        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11166            let autoscroll = self
11167                .selections
11168                .all::<Point>(cx)
11169                .iter()
11170                .any(|selection| crease.range().overlaps(&selection.range()));
11171
11172            self.fold_creases(vec![crease], autoscroll, cx);
11173        }
11174    }
11175
11176    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11177        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11178        let buffer = &display_map.buffer_snapshot;
11179        let selections = self.selections.all::<Point>(cx);
11180        let ranges = selections
11181            .iter()
11182            .map(|s| {
11183                let range = s.display_range(&display_map).sorted();
11184                let mut start = range.start.to_point(&display_map);
11185                let mut end = range.end.to_point(&display_map);
11186                start.column = 0;
11187                end.column = buffer.line_len(MultiBufferRow(end.row));
11188                start..end
11189            })
11190            .collect::<Vec<_>>();
11191
11192        self.unfold_ranges(&ranges, true, true, cx);
11193    }
11194
11195    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11196        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11197        let selections = self.selections.all::<Point>(cx);
11198        let ranges = selections
11199            .iter()
11200            .map(|s| {
11201                let mut range = s.display_range(&display_map).sorted();
11202                *range.start.column_mut() = 0;
11203                *range.end.column_mut() = display_map.line_len(range.end.row());
11204                let start = range.start.to_point(&display_map);
11205                let end = range.end.to_point(&display_map);
11206                start..end
11207            })
11208            .collect::<Vec<_>>();
11209
11210        self.unfold_ranges(&ranges, true, true, cx);
11211    }
11212
11213    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11214        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11215
11216        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11217            ..Point::new(
11218                unfold_at.buffer_row.0,
11219                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11220            );
11221
11222        let autoscroll = self
11223            .selections
11224            .all::<Point>(cx)
11225            .iter()
11226            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11227
11228        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11229    }
11230
11231    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11232        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11233        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11234    }
11235
11236    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11237        let selections = self.selections.all::<Point>(cx);
11238        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11239        let line_mode = self.selections.line_mode;
11240        let ranges = selections
11241            .into_iter()
11242            .map(|s| {
11243                if line_mode {
11244                    let start = Point::new(s.start.row, 0);
11245                    let end = Point::new(
11246                        s.end.row,
11247                        display_map
11248                            .buffer_snapshot
11249                            .line_len(MultiBufferRow(s.end.row)),
11250                    );
11251                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11252                } else {
11253                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11254                }
11255            })
11256            .collect::<Vec<_>>();
11257        self.fold_creases(ranges, true, cx);
11258    }
11259
11260    pub fn fold_creases<T: ToOffset + Clone>(
11261        &mut self,
11262        creases: Vec<Crease<T>>,
11263        auto_scroll: bool,
11264        cx: &mut ViewContext<Self>,
11265    ) {
11266        if creases.is_empty() {
11267            return;
11268        }
11269
11270        let mut buffers_affected = HashMap::default();
11271        let multi_buffer = self.buffer().read(cx);
11272        for crease in &creases {
11273            if let Some((_, buffer, _)) =
11274                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11275            {
11276                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11277            };
11278        }
11279
11280        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11281
11282        if auto_scroll {
11283            self.request_autoscroll(Autoscroll::fit(), cx);
11284        }
11285
11286        for buffer in buffers_affected.into_values() {
11287            self.sync_expanded_diff_hunks(buffer, cx);
11288        }
11289
11290        cx.notify();
11291
11292        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11293            // Clear diagnostics block when folding a range that contains it.
11294            let snapshot = self.snapshot(cx);
11295            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11296                drop(snapshot);
11297                self.active_diagnostics = Some(active_diagnostics);
11298                self.dismiss_diagnostics(cx);
11299            } else {
11300                self.active_diagnostics = Some(active_diagnostics);
11301            }
11302        }
11303
11304        self.scrollbar_marker_state.dirty = true;
11305    }
11306
11307    /// Removes any folds whose ranges intersect any of the given ranges.
11308    pub fn unfold_ranges<T: ToOffset + Clone>(
11309        &mut self,
11310        ranges: &[Range<T>],
11311        inclusive: bool,
11312        auto_scroll: bool,
11313        cx: &mut ViewContext<Self>,
11314    ) {
11315        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11316            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11317        });
11318    }
11319
11320    /// Removes any folds with the given ranges.
11321    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11322        &mut self,
11323        ranges: &[Range<T>],
11324        type_id: TypeId,
11325        auto_scroll: bool,
11326        cx: &mut ViewContext<Self>,
11327    ) {
11328        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11329            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11330        });
11331    }
11332
11333    fn remove_folds_with<T: ToOffset + Clone>(
11334        &mut self,
11335        ranges: &[Range<T>],
11336        auto_scroll: bool,
11337        cx: &mut ViewContext<Self>,
11338        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11339    ) {
11340        if ranges.is_empty() {
11341            return;
11342        }
11343
11344        let mut buffers_affected = HashMap::default();
11345        let multi_buffer = self.buffer().read(cx);
11346        for range in ranges {
11347            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11348                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11349            };
11350        }
11351
11352        self.display_map.update(cx, update);
11353
11354        if auto_scroll {
11355            self.request_autoscroll(Autoscroll::fit(), cx);
11356        }
11357
11358        for buffer in buffers_affected.into_values() {
11359            self.sync_expanded_diff_hunks(buffer, cx);
11360        }
11361
11362        cx.notify();
11363        self.scrollbar_marker_state.dirty = true;
11364        self.active_indent_guides_state.dirty = true;
11365    }
11366
11367    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11368        self.display_map.read(cx).fold_placeholder.clone()
11369    }
11370
11371    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11372        if hovered != self.gutter_hovered {
11373            self.gutter_hovered = hovered;
11374            cx.notify();
11375        }
11376    }
11377
11378    pub fn insert_blocks(
11379        &mut self,
11380        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11381        autoscroll: Option<Autoscroll>,
11382        cx: &mut ViewContext<Self>,
11383    ) -> Vec<CustomBlockId> {
11384        let blocks = self
11385            .display_map
11386            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11387        if let Some(autoscroll) = autoscroll {
11388            self.request_autoscroll(autoscroll, cx);
11389        }
11390        cx.notify();
11391        blocks
11392    }
11393
11394    pub fn resize_blocks(
11395        &mut self,
11396        heights: HashMap<CustomBlockId, u32>,
11397        autoscroll: Option<Autoscroll>,
11398        cx: &mut ViewContext<Self>,
11399    ) {
11400        self.display_map
11401            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11402        if let Some(autoscroll) = autoscroll {
11403            self.request_autoscroll(autoscroll, cx);
11404        }
11405        cx.notify();
11406    }
11407
11408    pub fn replace_blocks(
11409        &mut self,
11410        renderers: HashMap<CustomBlockId, RenderBlock>,
11411        autoscroll: Option<Autoscroll>,
11412        cx: &mut ViewContext<Self>,
11413    ) {
11414        self.display_map
11415            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11416        if let Some(autoscroll) = autoscroll {
11417            self.request_autoscroll(autoscroll, cx);
11418        }
11419        cx.notify();
11420    }
11421
11422    pub fn remove_blocks(
11423        &mut self,
11424        block_ids: HashSet<CustomBlockId>,
11425        autoscroll: Option<Autoscroll>,
11426        cx: &mut ViewContext<Self>,
11427    ) {
11428        self.display_map.update(cx, |display_map, cx| {
11429            display_map.remove_blocks(block_ids, cx)
11430        });
11431        if let Some(autoscroll) = autoscroll {
11432            self.request_autoscroll(autoscroll, cx);
11433        }
11434        cx.notify();
11435    }
11436
11437    pub fn row_for_block(
11438        &self,
11439        block_id: CustomBlockId,
11440        cx: &mut ViewContext<Self>,
11441    ) -> Option<DisplayRow> {
11442        self.display_map
11443            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11444    }
11445
11446    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11447        self.focused_block = Some(focused_block);
11448    }
11449
11450    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11451        self.focused_block.take()
11452    }
11453
11454    pub fn insert_creases(
11455        &mut self,
11456        creases: impl IntoIterator<Item = Crease<Anchor>>,
11457        cx: &mut ViewContext<Self>,
11458    ) -> Vec<CreaseId> {
11459        self.display_map
11460            .update(cx, |map, cx| map.insert_creases(creases, cx))
11461    }
11462
11463    pub fn remove_creases(
11464        &mut self,
11465        ids: impl IntoIterator<Item = CreaseId>,
11466        cx: &mut ViewContext<Self>,
11467    ) {
11468        self.display_map
11469            .update(cx, |map, cx| map.remove_creases(ids, cx));
11470    }
11471
11472    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11473        self.display_map
11474            .update(cx, |map, cx| map.snapshot(cx))
11475            .longest_row()
11476    }
11477
11478    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11479        self.display_map
11480            .update(cx, |map, cx| map.snapshot(cx))
11481            .max_point()
11482    }
11483
11484    pub fn text(&self, cx: &AppContext) -> String {
11485        self.buffer.read(cx).read(cx).text()
11486    }
11487
11488    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11489        let text = self.text(cx);
11490        let text = text.trim();
11491
11492        if text.is_empty() {
11493            return None;
11494        }
11495
11496        Some(text.to_string())
11497    }
11498
11499    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11500        self.transact(cx, |this, cx| {
11501            this.buffer
11502                .read(cx)
11503                .as_singleton()
11504                .expect("you can only call set_text on editors for singleton buffers")
11505                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11506        });
11507    }
11508
11509    pub fn display_text(&self, cx: &mut AppContext) -> String {
11510        self.display_map
11511            .update(cx, |map, cx| map.snapshot(cx))
11512            .text()
11513    }
11514
11515    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11516        let mut wrap_guides = smallvec::smallvec![];
11517
11518        if self.show_wrap_guides == Some(false) {
11519            return wrap_guides;
11520        }
11521
11522        let settings = self.buffer.read(cx).settings_at(0, cx);
11523        if settings.show_wrap_guides {
11524            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11525                wrap_guides.push((soft_wrap as usize, true));
11526            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11527                wrap_guides.push((soft_wrap as usize, true));
11528            }
11529            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11530        }
11531
11532        wrap_guides
11533    }
11534
11535    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11536        let settings = self.buffer.read(cx).settings_at(0, cx);
11537        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11538        match mode {
11539            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11540                SoftWrap::None
11541            }
11542            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11543            language_settings::SoftWrap::PreferredLineLength => {
11544                SoftWrap::Column(settings.preferred_line_length)
11545            }
11546            language_settings::SoftWrap::Bounded => {
11547                SoftWrap::Bounded(settings.preferred_line_length)
11548            }
11549        }
11550    }
11551
11552    pub fn set_soft_wrap_mode(
11553        &mut self,
11554        mode: language_settings::SoftWrap,
11555        cx: &mut ViewContext<Self>,
11556    ) {
11557        self.soft_wrap_mode_override = Some(mode);
11558        cx.notify();
11559    }
11560
11561    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11562        self.text_style_refinement = Some(style);
11563    }
11564
11565    /// called by the Element so we know what style we were most recently rendered with.
11566    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11567        let rem_size = cx.rem_size();
11568        self.display_map.update(cx, |map, cx| {
11569            map.set_font(
11570                style.text.font(),
11571                style.text.font_size.to_pixels(rem_size),
11572                cx,
11573            )
11574        });
11575        self.style = Some(style);
11576    }
11577
11578    pub fn style(&self) -> Option<&EditorStyle> {
11579        self.style.as_ref()
11580    }
11581
11582    // Called by the element. This method is not designed to be called outside of the editor
11583    // element's layout code because it does not notify when rewrapping is computed synchronously.
11584    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11585        self.display_map
11586            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11587    }
11588
11589    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11590        if self.soft_wrap_mode_override.is_some() {
11591            self.soft_wrap_mode_override.take();
11592        } else {
11593            let soft_wrap = match self.soft_wrap_mode(cx) {
11594                SoftWrap::GitDiff => return,
11595                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11596                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11597                    language_settings::SoftWrap::None
11598                }
11599            };
11600            self.soft_wrap_mode_override = Some(soft_wrap);
11601        }
11602        cx.notify();
11603    }
11604
11605    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11606        let Some(workspace) = self.workspace() else {
11607            return;
11608        };
11609        let fs = workspace.read(cx).app_state().fs.clone();
11610        let current_show = TabBarSettings::get_global(cx).show;
11611        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11612            setting.show = Some(!current_show);
11613        });
11614    }
11615
11616    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11617        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11618            self.buffer
11619                .read(cx)
11620                .settings_at(0, cx)
11621                .indent_guides
11622                .enabled
11623        });
11624        self.show_indent_guides = Some(!currently_enabled);
11625        cx.notify();
11626    }
11627
11628    fn should_show_indent_guides(&self) -> Option<bool> {
11629        self.show_indent_guides
11630    }
11631
11632    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11633        let mut editor_settings = EditorSettings::get_global(cx).clone();
11634        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11635        EditorSettings::override_global(editor_settings, cx);
11636    }
11637
11638    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11639        self.use_relative_line_numbers
11640            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11641    }
11642
11643    pub fn toggle_relative_line_numbers(
11644        &mut self,
11645        _: &ToggleRelativeLineNumbers,
11646        cx: &mut ViewContext<Self>,
11647    ) {
11648        let is_relative = self.should_use_relative_line_numbers(cx);
11649        self.set_relative_line_number(Some(!is_relative), cx)
11650    }
11651
11652    pub fn set_relative_line_number(
11653        &mut self,
11654        is_relative: Option<bool>,
11655        cx: &mut ViewContext<Self>,
11656    ) {
11657        self.use_relative_line_numbers = is_relative;
11658        cx.notify();
11659    }
11660
11661    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11662        self.show_gutter = show_gutter;
11663        cx.notify();
11664    }
11665
11666    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11667        self.show_line_numbers = Some(show_line_numbers);
11668        cx.notify();
11669    }
11670
11671    pub fn set_show_git_diff_gutter(
11672        &mut self,
11673        show_git_diff_gutter: bool,
11674        cx: &mut ViewContext<Self>,
11675    ) {
11676        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11677        cx.notify();
11678    }
11679
11680    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11681        self.show_code_actions = Some(show_code_actions);
11682        cx.notify();
11683    }
11684
11685    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11686        self.show_runnables = Some(show_runnables);
11687        cx.notify();
11688    }
11689
11690    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11691        if self.display_map.read(cx).masked != masked {
11692            self.display_map.update(cx, |map, _| map.masked = masked);
11693        }
11694        cx.notify()
11695    }
11696
11697    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11698        self.show_wrap_guides = Some(show_wrap_guides);
11699        cx.notify();
11700    }
11701
11702    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11703        self.show_indent_guides = Some(show_indent_guides);
11704        cx.notify();
11705    }
11706
11707    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11708        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11709            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11710                if let Some(dir) = file.abs_path(cx).parent() {
11711                    return Some(dir.to_owned());
11712                }
11713            }
11714
11715            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11716                return Some(project_path.path.to_path_buf());
11717            }
11718        }
11719
11720        None
11721    }
11722
11723    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11724        self.active_excerpt(cx)?
11725            .1
11726            .read(cx)
11727            .file()
11728            .and_then(|f| f.as_local())
11729    }
11730
11731    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11732        if let Some(target) = self.target_file(cx) {
11733            cx.reveal_path(&target.abs_path(cx));
11734        }
11735    }
11736
11737    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11738        if let Some(file) = self.target_file(cx) {
11739            if let Some(path) = file.abs_path(cx).to_str() {
11740                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11741            }
11742        }
11743    }
11744
11745    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11746        if let Some(file) = self.target_file(cx) {
11747            if let Some(path) = file.path().to_str() {
11748                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11749            }
11750        }
11751    }
11752
11753    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11754        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11755
11756        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11757            self.start_git_blame(true, cx);
11758        }
11759
11760        cx.notify();
11761    }
11762
11763    pub fn toggle_git_blame_inline(
11764        &mut self,
11765        _: &ToggleGitBlameInline,
11766        cx: &mut ViewContext<Self>,
11767    ) {
11768        self.toggle_git_blame_inline_internal(true, cx);
11769        cx.notify();
11770    }
11771
11772    pub fn git_blame_inline_enabled(&self) -> bool {
11773        self.git_blame_inline_enabled
11774    }
11775
11776    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11777        self.show_selection_menu = self
11778            .show_selection_menu
11779            .map(|show_selections_menu| !show_selections_menu)
11780            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11781
11782        cx.notify();
11783    }
11784
11785    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11786        self.show_selection_menu
11787            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11788    }
11789
11790    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11791        if let Some(project) = self.project.as_ref() {
11792            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11793                return;
11794            };
11795
11796            if buffer.read(cx).file().is_none() {
11797                return;
11798            }
11799
11800            let focused = self.focus_handle(cx).contains_focused(cx);
11801
11802            let project = project.clone();
11803            let blame =
11804                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11805            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11806            self.blame = Some(blame);
11807        }
11808    }
11809
11810    fn toggle_git_blame_inline_internal(
11811        &mut self,
11812        user_triggered: bool,
11813        cx: &mut ViewContext<Self>,
11814    ) {
11815        if self.git_blame_inline_enabled {
11816            self.git_blame_inline_enabled = false;
11817            self.show_git_blame_inline = false;
11818            self.show_git_blame_inline_delay_task.take();
11819        } else {
11820            self.git_blame_inline_enabled = true;
11821            self.start_git_blame_inline(user_triggered, cx);
11822        }
11823
11824        cx.notify();
11825    }
11826
11827    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11828        self.start_git_blame(user_triggered, cx);
11829
11830        if ProjectSettings::get_global(cx)
11831            .git
11832            .inline_blame_delay()
11833            .is_some()
11834        {
11835            self.start_inline_blame_timer(cx);
11836        } else {
11837            self.show_git_blame_inline = true
11838        }
11839    }
11840
11841    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11842        self.blame.as_ref()
11843    }
11844
11845    pub fn show_git_blame_gutter(&self) -> bool {
11846        self.show_git_blame_gutter
11847    }
11848
11849    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11850        self.show_git_blame_gutter && self.has_blame_entries(cx)
11851    }
11852
11853    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11854        self.show_git_blame_inline
11855            && self.focus_handle.is_focused(cx)
11856            && !self.newest_selection_head_on_empty_line(cx)
11857            && self.has_blame_entries(cx)
11858    }
11859
11860    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11861        self.blame()
11862            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11863    }
11864
11865    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11866        let cursor_anchor = self.selections.newest_anchor().head();
11867
11868        let snapshot = self.buffer.read(cx).snapshot(cx);
11869        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11870
11871        snapshot.line_len(buffer_row) == 0
11872    }
11873
11874    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11875        let buffer_and_selection = maybe!({
11876            let selection = self.selections.newest::<Point>(cx);
11877            let selection_range = selection.range();
11878
11879            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11880                (buffer, selection_range.start.row..selection_range.end.row)
11881            } else {
11882                let buffer_ranges = self
11883                    .buffer()
11884                    .read(cx)
11885                    .range_to_buffer_ranges(selection_range, cx);
11886
11887                let (buffer, range, _) = if selection.reversed {
11888                    buffer_ranges.first()
11889                } else {
11890                    buffer_ranges.last()
11891                }?;
11892
11893                let snapshot = buffer.read(cx).snapshot();
11894                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11895                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11896                (buffer.clone(), selection)
11897            };
11898
11899            Some((buffer, selection))
11900        });
11901
11902        let Some((buffer, selection)) = buffer_and_selection else {
11903            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11904        };
11905
11906        let Some(project) = self.project.as_ref() else {
11907            return Task::ready(Err(anyhow!("editor does not have project")));
11908        };
11909
11910        project.update(cx, |project, cx| {
11911            project.get_permalink_to_line(&buffer, selection, cx)
11912        })
11913    }
11914
11915    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11916        let permalink_task = self.get_permalink_to_line(cx);
11917        let workspace = self.workspace();
11918
11919        cx.spawn(|_, mut cx| async move {
11920            match permalink_task.await {
11921                Ok(permalink) => {
11922                    cx.update(|cx| {
11923                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11924                    })
11925                    .ok();
11926                }
11927                Err(err) => {
11928                    let message = format!("Failed to copy permalink: {err}");
11929
11930                    Err::<(), anyhow::Error>(err).log_err();
11931
11932                    if let Some(workspace) = workspace {
11933                        workspace
11934                            .update(&mut cx, |workspace, cx| {
11935                                struct CopyPermalinkToLine;
11936
11937                                workspace.show_toast(
11938                                    Toast::new(
11939                                        NotificationId::unique::<CopyPermalinkToLine>(),
11940                                        message,
11941                                    ),
11942                                    cx,
11943                                )
11944                            })
11945                            .ok();
11946                    }
11947                }
11948            }
11949        })
11950        .detach();
11951    }
11952
11953    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11954        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11955        if let Some(file) = self.target_file(cx) {
11956            if let Some(path) = file.path().to_str() {
11957                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11958            }
11959        }
11960    }
11961
11962    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11963        let permalink_task = self.get_permalink_to_line(cx);
11964        let workspace = self.workspace();
11965
11966        cx.spawn(|_, mut cx| async move {
11967            match permalink_task.await {
11968                Ok(permalink) => {
11969                    cx.update(|cx| {
11970                        cx.open_url(permalink.as_ref());
11971                    })
11972                    .ok();
11973                }
11974                Err(err) => {
11975                    let message = format!("Failed to open permalink: {err}");
11976
11977                    Err::<(), anyhow::Error>(err).log_err();
11978
11979                    if let Some(workspace) = workspace {
11980                        workspace
11981                            .update(&mut cx, |workspace, cx| {
11982                                struct OpenPermalinkToLine;
11983
11984                                workspace.show_toast(
11985                                    Toast::new(
11986                                        NotificationId::unique::<OpenPermalinkToLine>(),
11987                                        message,
11988                                    ),
11989                                    cx,
11990                                )
11991                            })
11992                            .ok();
11993                    }
11994                }
11995            }
11996        })
11997        .detach();
11998    }
11999
12000    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12001    /// last highlight added will be used.
12002    ///
12003    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12004    pub fn highlight_rows<T: 'static>(
12005        &mut self,
12006        range: Range<Anchor>,
12007        color: Hsla,
12008        should_autoscroll: bool,
12009        cx: &mut ViewContext<Self>,
12010    ) {
12011        let snapshot = self.buffer().read(cx).snapshot(cx);
12012        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12013        let ix = row_highlights.binary_search_by(|highlight| {
12014            Ordering::Equal
12015                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12016                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12017        });
12018
12019        if let Err(mut ix) = ix {
12020            let index = post_inc(&mut self.highlight_order);
12021
12022            // If this range intersects with the preceding highlight, then merge it with
12023            // the preceding highlight. Otherwise insert a new highlight.
12024            let mut merged = false;
12025            if ix > 0 {
12026                let prev_highlight = &mut row_highlights[ix - 1];
12027                if prev_highlight
12028                    .range
12029                    .end
12030                    .cmp(&range.start, &snapshot)
12031                    .is_ge()
12032                {
12033                    ix -= 1;
12034                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12035                        prev_highlight.range.end = range.end;
12036                    }
12037                    merged = true;
12038                    prev_highlight.index = index;
12039                    prev_highlight.color = color;
12040                    prev_highlight.should_autoscroll = should_autoscroll;
12041                }
12042            }
12043
12044            if !merged {
12045                row_highlights.insert(
12046                    ix,
12047                    RowHighlight {
12048                        range: range.clone(),
12049                        index,
12050                        color,
12051                        should_autoscroll,
12052                    },
12053                );
12054            }
12055
12056            // If any of the following highlights intersect with this one, merge them.
12057            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12058                let highlight = &row_highlights[ix];
12059                if next_highlight
12060                    .range
12061                    .start
12062                    .cmp(&highlight.range.end, &snapshot)
12063                    .is_le()
12064                {
12065                    if next_highlight
12066                        .range
12067                        .end
12068                        .cmp(&highlight.range.end, &snapshot)
12069                        .is_gt()
12070                    {
12071                        row_highlights[ix].range.end = next_highlight.range.end;
12072                    }
12073                    row_highlights.remove(ix + 1);
12074                } else {
12075                    break;
12076                }
12077            }
12078        }
12079    }
12080
12081    /// Remove any highlighted row ranges of the given type that intersect the
12082    /// given ranges.
12083    pub fn remove_highlighted_rows<T: 'static>(
12084        &mut self,
12085        ranges_to_remove: Vec<Range<Anchor>>,
12086        cx: &mut ViewContext<Self>,
12087    ) {
12088        let snapshot = self.buffer().read(cx).snapshot(cx);
12089        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12090        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12091        row_highlights.retain(|highlight| {
12092            while let Some(range_to_remove) = ranges_to_remove.peek() {
12093                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12094                    Ordering::Less | Ordering::Equal => {
12095                        ranges_to_remove.next();
12096                    }
12097                    Ordering::Greater => {
12098                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12099                            Ordering::Less | Ordering::Equal => {
12100                                return false;
12101                            }
12102                            Ordering::Greater => break,
12103                        }
12104                    }
12105                }
12106            }
12107
12108            true
12109        })
12110    }
12111
12112    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12113    pub fn clear_row_highlights<T: 'static>(&mut self) {
12114        self.highlighted_rows.remove(&TypeId::of::<T>());
12115    }
12116
12117    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12118    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12119        self.highlighted_rows
12120            .get(&TypeId::of::<T>())
12121            .map_or(&[] as &[_], |vec| vec.as_slice())
12122            .iter()
12123            .map(|highlight| (highlight.range.clone(), highlight.color))
12124    }
12125
12126    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12127    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12128    /// Allows to ignore certain kinds of highlights.
12129    pub fn highlighted_display_rows(
12130        &mut self,
12131        cx: &mut WindowContext,
12132    ) -> BTreeMap<DisplayRow, Hsla> {
12133        let snapshot = self.snapshot(cx);
12134        let mut used_highlight_orders = HashMap::default();
12135        self.highlighted_rows
12136            .iter()
12137            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12138            .fold(
12139                BTreeMap::<DisplayRow, Hsla>::new(),
12140                |mut unique_rows, highlight| {
12141                    let start = highlight.range.start.to_display_point(&snapshot);
12142                    let end = highlight.range.end.to_display_point(&snapshot);
12143                    let start_row = start.row().0;
12144                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12145                        && end.column() == 0
12146                    {
12147                        end.row().0.saturating_sub(1)
12148                    } else {
12149                        end.row().0
12150                    };
12151                    for row in start_row..=end_row {
12152                        let used_index =
12153                            used_highlight_orders.entry(row).or_insert(highlight.index);
12154                        if highlight.index >= *used_index {
12155                            *used_index = highlight.index;
12156                            unique_rows.insert(DisplayRow(row), highlight.color);
12157                        }
12158                    }
12159                    unique_rows
12160                },
12161            )
12162    }
12163
12164    pub fn highlighted_display_row_for_autoscroll(
12165        &self,
12166        snapshot: &DisplaySnapshot,
12167    ) -> Option<DisplayRow> {
12168        self.highlighted_rows
12169            .values()
12170            .flat_map(|highlighted_rows| highlighted_rows.iter())
12171            .filter_map(|highlight| {
12172                if highlight.should_autoscroll {
12173                    Some(highlight.range.start.to_display_point(snapshot).row())
12174                } else {
12175                    None
12176                }
12177            })
12178            .min()
12179    }
12180
12181    pub fn set_search_within_ranges(
12182        &mut self,
12183        ranges: &[Range<Anchor>],
12184        cx: &mut ViewContext<Self>,
12185    ) {
12186        self.highlight_background::<SearchWithinRange>(
12187            ranges,
12188            |colors| colors.editor_document_highlight_read_background,
12189            cx,
12190        )
12191    }
12192
12193    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12194        self.breadcrumb_header = Some(new_header);
12195    }
12196
12197    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12198        self.clear_background_highlights::<SearchWithinRange>(cx);
12199    }
12200
12201    pub fn highlight_background<T: 'static>(
12202        &mut self,
12203        ranges: &[Range<Anchor>],
12204        color_fetcher: fn(&ThemeColors) -> Hsla,
12205        cx: &mut ViewContext<Self>,
12206    ) {
12207        self.background_highlights
12208            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12209        self.scrollbar_marker_state.dirty = true;
12210        cx.notify();
12211    }
12212
12213    pub fn clear_background_highlights<T: 'static>(
12214        &mut self,
12215        cx: &mut ViewContext<Self>,
12216    ) -> Option<BackgroundHighlight> {
12217        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12218        if !text_highlights.1.is_empty() {
12219            self.scrollbar_marker_state.dirty = true;
12220            cx.notify();
12221        }
12222        Some(text_highlights)
12223    }
12224
12225    pub fn highlight_gutter<T: 'static>(
12226        &mut self,
12227        ranges: &[Range<Anchor>],
12228        color_fetcher: fn(&AppContext) -> Hsla,
12229        cx: &mut ViewContext<Self>,
12230    ) {
12231        self.gutter_highlights
12232            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12233        cx.notify();
12234    }
12235
12236    pub fn clear_gutter_highlights<T: 'static>(
12237        &mut self,
12238        cx: &mut ViewContext<Self>,
12239    ) -> Option<GutterHighlight> {
12240        cx.notify();
12241        self.gutter_highlights.remove(&TypeId::of::<T>())
12242    }
12243
12244    #[cfg(feature = "test-support")]
12245    pub fn all_text_background_highlights(
12246        &mut self,
12247        cx: &mut ViewContext<Self>,
12248    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12249        let snapshot = self.snapshot(cx);
12250        let buffer = &snapshot.buffer_snapshot;
12251        let start = buffer.anchor_before(0);
12252        let end = buffer.anchor_after(buffer.len());
12253        let theme = cx.theme().colors();
12254        self.background_highlights_in_range(start..end, &snapshot, theme)
12255    }
12256
12257    #[cfg(feature = "test-support")]
12258    pub fn search_background_highlights(
12259        &mut self,
12260        cx: &mut ViewContext<Self>,
12261    ) -> Vec<Range<Point>> {
12262        let snapshot = self.buffer().read(cx).snapshot(cx);
12263
12264        let highlights = self
12265            .background_highlights
12266            .get(&TypeId::of::<items::BufferSearchHighlights>());
12267
12268        if let Some((_color, ranges)) = highlights {
12269            ranges
12270                .iter()
12271                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12272                .collect_vec()
12273        } else {
12274            vec![]
12275        }
12276    }
12277
12278    fn document_highlights_for_position<'a>(
12279        &'a self,
12280        position: Anchor,
12281        buffer: &'a MultiBufferSnapshot,
12282    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12283        let read_highlights = self
12284            .background_highlights
12285            .get(&TypeId::of::<DocumentHighlightRead>())
12286            .map(|h| &h.1);
12287        let write_highlights = self
12288            .background_highlights
12289            .get(&TypeId::of::<DocumentHighlightWrite>())
12290            .map(|h| &h.1);
12291        let left_position = position.bias_left(buffer);
12292        let right_position = position.bias_right(buffer);
12293        read_highlights
12294            .into_iter()
12295            .chain(write_highlights)
12296            .flat_map(move |ranges| {
12297                let start_ix = match ranges.binary_search_by(|probe| {
12298                    let cmp = probe.end.cmp(&left_position, buffer);
12299                    if cmp.is_ge() {
12300                        Ordering::Greater
12301                    } else {
12302                        Ordering::Less
12303                    }
12304                }) {
12305                    Ok(i) | Err(i) => i,
12306                };
12307
12308                ranges[start_ix..]
12309                    .iter()
12310                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12311            })
12312    }
12313
12314    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12315        self.background_highlights
12316            .get(&TypeId::of::<T>())
12317            .map_or(false, |(_, highlights)| !highlights.is_empty())
12318    }
12319
12320    pub fn background_highlights_in_range(
12321        &self,
12322        search_range: Range<Anchor>,
12323        display_snapshot: &DisplaySnapshot,
12324        theme: &ThemeColors,
12325    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12326        let mut results = Vec::new();
12327        for (color_fetcher, ranges) in self.background_highlights.values() {
12328            let color = color_fetcher(theme);
12329            let start_ix = match ranges.binary_search_by(|probe| {
12330                let cmp = probe
12331                    .end
12332                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12333                if cmp.is_gt() {
12334                    Ordering::Greater
12335                } else {
12336                    Ordering::Less
12337                }
12338            }) {
12339                Ok(i) | Err(i) => i,
12340            };
12341            for range in &ranges[start_ix..] {
12342                if range
12343                    .start
12344                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12345                    .is_ge()
12346                {
12347                    break;
12348                }
12349
12350                let start = range.start.to_display_point(display_snapshot);
12351                let end = range.end.to_display_point(display_snapshot);
12352                results.push((start..end, color))
12353            }
12354        }
12355        results
12356    }
12357
12358    pub fn background_highlight_row_ranges<T: 'static>(
12359        &self,
12360        search_range: Range<Anchor>,
12361        display_snapshot: &DisplaySnapshot,
12362        count: usize,
12363    ) -> Vec<RangeInclusive<DisplayPoint>> {
12364        let mut results = Vec::new();
12365        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12366            return vec![];
12367        };
12368
12369        let start_ix = match ranges.binary_search_by(|probe| {
12370            let cmp = probe
12371                .end
12372                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12373            if cmp.is_gt() {
12374                Ordering::Greater
12375            } else {
12376                Ordering::Less
12377            }
12378        }) {
12379            Ok(i) | Err(i) => i,
12380        };
12381        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12382            if let (Some(start_display), Some(end_display)) = (start, end) {
12383                results.push(
12384                    start_display.to_display_point(display_snapshot)
12385                        ..=end_display.to_display_point(display_snapshot),
12386                );
12387            }
12388        };
12389        let mut start_row: Option<Point> = None;
12390        let mut end_row: Option<Point> = None;
12391        if ranges.len() > count {
12392            return Vec::new();
12393        }
12394        for range in &ranges[start_ix..] {
12395            if range
12396                .start
12397                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12398                .is_ge()
12399            {
12400                break;
12401            }
12402            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12403            if let Some(current_row) = &end_row {
12404                if end.row == current_row.row {
12405                    continue;
12406                }
12407            }
12408            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12409            if start_row.is_none() {
12410                assert_eq!(end_row, None);
12411                start_row = Some(start);
12412                end_row = Some(end);
12413                continue;
12414            }
12415            if let Some(current_end) = end_row.as_mut() {
12416                if start.row > current_end.row + 1 {
12417                    push_region(start_row, end_row);
12418                    start_row = Some(start);
12419                    end_row = Some(end);
12420                } else {
12421                    // Merge two hunks.
12422                    *current_end = end;
12423                }
12424            } else {
12425                unreachable!();
12426            }
12427        }
12428        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12429        push_region(start_row, end_row);
12430        results
12431    }
12432
12433    pub fn gutter_highlights_in_range(
12434        &self,
12435        search_range: Range<Anchor>,
12436        display_snapshot: &DisplaySnapshot,
12437        cx: &AppContext,
12438    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12439        let mut results = Vec::new();
12440        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12441            let color = color_fetcher(cx);
12442            let start_ix = match ranges.binary_search_by(|probe| {
12443                let cmp = probe
12444                    .end
12445                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12446                if cmp.is_gt() {
12447                    Ordering::Greater
12448                } else {
12449                    Ordering::Less
12450                }
12451            }) {
12452                Ok(i) | Err(i) => i,
12453            };
12454            for range in &ranges[start_ix..] {
12455                if range
12456                    .start
12457                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12458                    .is_ge()
12459                {
12460                    break;
12461                }
12462
12463                let start = range.start.to_display_point(display_snapshot);
12464                let end = range.end.to_display_point(display_snapshot);
12465                results.push((start..end, color))
12466            }
12467        }
12468        results
12469    }
12470
12471    /// Get the text ranges corresponding to the redaction query
12472    pub fn redacted_ranges(
12473        &self,
12474        search_range: Range<Anchor>,
12475        display_snapshot: &DisplaySnapshot,
12476        cx: &WindowContext,
12477    ) -> Vec<Range<DisplayPoint>> {
12478        display_snapshot
12479            .buffer_snapshot
12480            .redacted_ranges(search_range, |file| {
12481                if let Some(file) = file {
12482                    file.is_private()
12483                        && EditorSettings::get(
12484                            Some(SettingsLocation {
12485                                worktree_id: file.worktree_id(cx),
12486                                path: file.path().as_ref(),
12487                            }),
12488                            cx,
12489                        )
12490                        .redact_private_values
12491                } else {
12492                    false
12493                }
12494            })
12495            .map(|range| {
12496                range.start.to_display_point(display_snapshot)
12497                    ..range.end.to_display_point(display_snapshot)
12498            })
12499            .collect()
12500    }
12501
12502    pub fn highlight_text<T: 'static>(
12503        &mut self,
12504        ranges: Vec<Range<Anchor>>,
12505        style: HighlightStyle,
12506        cx: &mut ViewContext<Self>,
12507    ) {
12508        self.display_map.update(cx, |map, _| {
12509            map.highlight_text(TypeId::of::<T>(), ranges, style)
12510        });
12511        cx.notify();
12512    }
12513
12514    pub(crate) fn highlight_inlays<T: 'static>(
12515        &mut self,
12516        highlights: Vec<InlayHighlight>,
12517        style: HighlightStyle,
12518        cx: &mut ViewContext<Self>,
12519    ) {
12520        self.display_map.update(cx, |map, _| {
12521            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12522        });
12523        cx.notify();
12524    }
12525
12526    pub fn text_highlights<'a, T: 'static>(
12527        &'a self,
12528        cx: &'a AppContext,
12529    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12530        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12531    }
12532
12533    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12534        let cleared = self
12535            .display_map
12536            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12537        if cleared {
12538            cx.notify();
12539        }
12540    }
12541
12542    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12543        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12544            && self.focus_handle.is_focused(cx)
12545    }
12546
12547    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12548        self.show_cursor_when_unfocused = is_enabled;
12549        cx.notify();
12550    }
12551
12552    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12553        cx.notify();
12554    }
12555
12556    fn on_buffer_event(
12557        &mut self,
12558        multibuffer: Model<MultiBuffer>,
12559        event: &multi_buffer::Event,
12560        cx: &mut ViewContext<Self>,
12561    ) {
12562        match event {
12563            multi_buffer::Event::Edited {
12564                singleton_buffer_edited,
12565            } => {
12566                self.scrollbar_marker_state.dirty = true;
12567                self.active_indent_guides_state.dirty = true;
12568                self.refresh_active_diagnostics(cx);
12569                self.refresh_code_actions(cx);
12570                if self.has_active_inline_completion(cx) {
12571                    self.update_visible_inline_completion(cx);
12572                }
12573                cx.emit(EditorEvent::BufferEdited);
12574                cx.emit(SearchEvent::MatchesInvalidated);
12575                if *singleton_buffer_edited {
12576                    if let Some(project) = &self.project {
12577                        let project = project.read(cx);
12578                        #[allow(clippy::mutable_key_type)]
12579                        let languages_affected = multibuffer
12580                            .read(cx)
12581                            .all_buffers()
12582                            .into_iter()
12583                            .filter_map(|buffer| {
12584                                let buffer = buffer.read(cx);
12585                                let language = buffer.language()?;
12586                                if project.is_local()
12587                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12588                                {
12589                                    None
12590                                } else {
12591                                    Some(language)
12592                                }
12593                            })
12594                            .cloned()
12595                            .collect::<HashSet<_>>();
12596                        if !languages_affected.is_empty() {
12597                            self.refresh_inlay_hints(
12598                                InlayHintRefreshReason::BufferEdited(languages_affected),
12599                                cx,
12600                            );
12601                        }
12602                    }
12603                }
12604
12605                let Some(project) = &self.project else { return };
12606                let (telemetry, is_via_ssh) = {
12607                    let project = project.read(cx);
12608                    let telemetry = project.client().telemetry().clone();
12609                    let is_via_ssh = project.is_via_ssh();
12610                    (telemetry, is_via_ssh)
12611                };
12612                refresh_linked_ranges(self, cx);
12613                telemetry.log_edit_event("editor", is_via_ssh);
12614            }
12615            multi_buffer::Event::ExcerptsAdded {
12616                buffer,
12617                predecessor,
12618                excerpts,
12619            } => {
12620                self.tasks_update_task = Some(self.refresh_runnables(cx));
12621                cx.emit(EditorEvent::ExcerptsAdded {
12622                    buffer: buffer.clone(),
12623                    predecessor: *predecessor,
12624                    excerpts: excerpts.clone(),
12625                });
12626                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12627            }
12628            multi_buffer::Event::ExcerptsRemoved { ids } => {
12629                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12630                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12631            }
12632            multi_buffer::Event::ExcerptsEdited { ids } => {
12633                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12634            }
12635            multi_buffer::Event::ExcerptsExpanded { ids } => {
12636                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12637            }
12638            multi_buffer::Event::Reparsed(buffer_id) => {
12639                self.tasks_update_task = Some(self.refresh_runnables(cx));
12640
12641                cx.emit(EditorEvent::Reparsed(*buffer_id));
12642            }
12643            multi_buffer::Event::LanguageChanged(buffer_id) => {
12644                linked_editing_ranges::refresh_linked_ranges(self, cx);
12645                cx.emit(EditorEvent::Reparsed(*buffer_id));
12646                cx.notify();
12647            }
12648            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12649            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12650            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12651                cx.emit(EditorEvent::TitleChanged)
12652            }
12653            multi_buffer::Event::DiffBaseChanged => {
12654                self.scrollbar_marker_state.dirty = true;
12655                cx.emit(EditorEvent::DiffBaseChanged);
12656                cx.notify();
12657            }
12658            multi_buffer::Event::DiffUpdated { buffer } => {
12659                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12660                cx.notify();
12661            }
12662            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12663            multi_buffer::Event::DiagnosticsUpdated => {
12664                self.refresh_active_diagnostics(cx);
12665                self.scrollbar_marker_state.dirty = true;
12666                cx.notify();
12667            }
12668            _ => {}
12669        };
12670    }
12671
12672    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12673        cx.notify();
12674    }
12675
12676    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12677        self.tasks_update_task = Some(self.refresh_runnables(cx));
12678        self.refresh_inline_completion(true, false, cx);
12679        self.refresh_inlay_hints(
12680            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12681                self.selections.newest_anchor().head(),
12682                &self.buffer.read(cx).snapshot(cx),
12683                cx,
12684            )),
12685            cx,
12686        );
12687
12688        let old_cursor_shape = self.cursor_shape;
12689
12690        {
12691            let editor_settings = EditorSettings::get_global(cx);
12692            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12693            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12694            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12695        }
12696
12697        if old_cursor_shape != self.cursor_shape {
12698            cx.emit(EditorEvent::CursorShapeChanged);
12699        }
12700
12701        let project_settings = ProjectSettings::get_global(cx);
12702        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12703
12704        if self.mode == EditorMode::Full {
12705            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12706            if self.git_blame_inline_enabled != inline_blame_enabled {
12707                self.toggle_git_blame_inline_internal(false, cx);
12708            }
12709        }
12710
12711        cx.notify();
12712    }
12713
12714    pub fn set_searchable(&mut self, searchable: bool) {
12715        self.searchable = searchable;
12716    }
12717
12718    pub fn searchable(&self) -> bool {
12719        self.searchable
12720    }
12721
12722    fn open_proposed_changes_editor(
12723        &mut self,
12724        _: &OpenProposedChangesEditor,
12725        cx: &mut ViewContext<Self>,
12726    ) {
12727        let Some(workspace) = self.workspace() else {
12728            cx.propagate();
12729            return;
12730        };
12731
12732        let selections = self.selections.all::<usize>(cx);
12733        let buffer = self.buffer.read(cx);
12734        let mut new_selections_by_buffer = HashMap::default();
12735        for selection in selections {
12736            for (buffer, range, _) in
12737                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12738            {
12739                let mut range = range.to_point(buffer.read(cx));
12740                range.start.column = 0;
12741                range.end.column = buffer.read(cx).line_len(range.end.row);
12742                new_selections_by_buffer
12743                    .entry(buffer)
12744                    .or_insert(Vec::new())
12745                    .push(range)
12746            }
12747        }
12748
12749        let proposed_changes_buffers = new_selections_by_buffer
12750            .into_iter()
12751            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12752            .collect::<Vec<_>>();
12753        let proposed_changes_editor = cx.new_view(|cx| {
12754            ProposedChangesEditor::new(
12755                "Proposed changes",
12756                proposed_changes_buffers,
12757                self.project.clone(),
12758                cx,
12759            )
12760        });
12761
12762        cx.window_context().defer(move |cx| {
12763            workspace.update(cx, |workspace, cx| {
12764                workspace.active_pane().update(cx, |pane, cx| {
12765                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12766                });
12767            });
12768        });
12769    }
12770
12771    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12772        self.open_excerpts_common(None, true, cx)
12773    }
12774
12775    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12776        self.open_excerpts_common(None, false, cx)
12777    }
12778
12779    fn open_excerpts_common(
12780        &mut self,
12781        jump_data: Option<JumpData>,
12782        split: bool,
12783        cx: &mut ViewContext<Self>,
12784    ) {
12785        let Some(workspace) = self.workspace() else {
12786            cx.propagate();
12787            return;
12788        };
12789
12790        if self.buffer.read(cx).is_singleton() {
12791            cx.propagate();
12792            return;
12793        }
12794
12795        let mut new_selections_by_buffer = HashMap::default();
12796        match &jump_data {
12797            Some(jump_data) => {
12798                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12799                if let Some(buffer) = multi_buffer_snapshot
12800                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12801                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12802                {
12803                    let buffer_snapshot = buffer.read(cx).snapshot();
12804                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12805                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12806                    } else {
12807                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12808                    };
12809                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12810                    new_selections_by_buffer.insert(
12811                        buffer,
12812                        (
12813                            vec![jump_to_offset..jump_to_offset],
12814                            Some(jump_data.line_offset_from_top),
12815                        ),
12816                    );
12817                }
12818            }
12819            None => {
12820                let selections = self.selections.all::<usize>(cx);
12821                let buffer = self.buffer.read(cx);
12822                for selection in selections {
12823                    for (mut buffer_handle, mut range, _) in
12824                        buffer.range_to_buffer_ranges(selection.range(), cx)
12825                    {
12826                        // When editing branch buffers, jump to the corresponding location
12827                        // in their base buffer.
12828                        let buffer = buffer_handle.read(cx);
12829                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12830                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12831                            buffer_handle = base_buffer;
12832                        }
12833
12834                        if selection.reversed {
12835                            mem::swap(&mut range.start, &mut range.end);
12836                        }
12837                        new_selections_by_buffer
12838                            .entry(buffer_handle)
12839                            .or_insert((Vec::new(), None))
12840                            .0
12841                            .push(range)
12842                    }
12843                }
12844            }
12845        }
12846
12847        if new_selections_by_buffer.is_empty() {
12848            return;
12849        }
12850
12851        // We defer the pane interaction because we ourselves are a workspace item
12852        // and activating a new item causes the pane to call a method on us reentrantly,
12853        // which panics if we're on the stack.
12854        cx.window_context().defer(move |cx| {
12855            workspace.update(cx, |workspace, cx| {
12856                let pane = if split {
12857                    workspace.adjacent_pane(cx)
12858                } else {
12859                    workspace.active_pane().clone()
12860                };
12861
12862                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12863                    let editor = buffer
12864                        .read(cx)
12865                        .file()
12866                        .is_none()
12867                        .then(|| {
12868                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12869                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12870                            // Instead, we try to activate the existing editor in the pane first.
12871                            let (editor, pane_item_index) =
12872                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12873                                    let editor = item.downcast::<Editor>()?;
12874                                    let singleton_buffer =
12875                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12876                                    if singleton_buffer == buffer {
12877                                        Some((editor, i))
12878                                    } else {
12879                                        None
12880                                    }
12881                                })?;
12882                            pane.update(cx, |pane, cx| {
12883                                pane.activate_item(pane_item_index, true, true, cx)
12884                            });
12885                            Some(editor)
12886                        })
12887                        .flatten()
12888                        .unwrap_or_else(|| {
12889                            workspace.open_project_item::<Self>(
12890                                pane.clone(),
12891                                buffer,
12892                                true,
12893                                true,
12894                                cx,
12895                            )
12896                        });
12897
12898                    editor.update(cx, |editor, cx| {
12899                        let autoscroll = match scroll_offset {
12900                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12901                            None => Autoscroll::newest(),
12902                        };
12903                        let nav_history = editor.nav_history.take();
12904                        editor.change_selections(Some(autoscroll), cx, |s| {
12905                            s.select_ranges(ranges);
12906                        });
12907                        editor.nav_history = nav_history;
12908                    });
12909                }
12910            })
12911        });
12912    }
12913
12914    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12915        let snapshot = self.buffer.read(cx).read(cx);
12916        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12917        Some(
12918            ranges
12919                .iter()
12920                .map(move |range| {
12921                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12922                })
12923                .collect(),
12924        )
12925    }
12926
12927    fn selection_replacement_ranges(
12928        &self,
12929        range: Range<OffsetUtf16>,
12930        cx: &mut AppContext,
12931    ) -> Vec<Range<OffsetUtf16>> {
12932        let selections = self.selections.all::<OffsetUtf16>(cx);
12933        let newest_selection = selections
12934            .iter()
12935            .max_by_key(|selection| selection.id)
12936            .unwrap();
12937        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12938        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12939        let snapshot = self.buffer.read(cx).read(cx);
12940        selections
12941            .into_iter()
12942            .map(|mut selection| {
12943                selection.start.0 =
12944                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12945                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12946                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12947                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12948            })
12949            .collect()
12950    }
12951
12952    fn report_editor_event(
12953        &self,
12954        operation: &'static str,
12955        file_extension: Option<String>,
12956        cx: &AppContext,
12957    ) {
12958        if cfg!(any(test, feature = "test-support")) {
12959            return;
12960        }
12961
12962        let Some(project) = &self.project else { return };
12963
12964        // If None, we are in a file without an extension
12965        let file = self
12966            .buffer
12967            .read(cx)
12968            .as_singleton()
12969            .and_then(|b| b.read(cx).file());
12970        let file_extension = file_extension.or(file
12971            .as_ref()
12972            .and_then(|file| Path::new(file.file_name(cx)).extension())
12973            .and_then(|e| e.to_str())
12974            .map(|a| a.to_string()));
12975
12976        let vim_mode = cx
12977            .global::<SettingsStore>()
12978            .raw_user_settings()
12979            .get("vim_mode")
12980            == Some(&serde_json::Value::Bool(true));
12981
12982        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12983            == language::language_settings::InlineCompletionProvider::Copilot;
12984        let copilot_enabled_for_language = self
12985            .buffer
12986            .read(cx)
12987            .settings_at(0, cx)
12988            .show_inline_completions;
12989
12990        let project = project.read(cx);
12991        let telemetry = project.client().telemetry().clone();
12992        telemetry.report_editor_event(
12993            file_extension,
12994            vim_mode,
12995            operation,
12996            copilot_enabled,
12997            copilot_enabled_for_language,
12998            project.is_via_ssh(),
12999        )
13000    }
13001
13002    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13003    /// with each line being an array of {text, highlight} objects.
13004    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13005        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13006            return;
13007        };
13008
13009        #[derive(Serialize)]
13010        struct Chunk<'a> {
13011            text: String,
13012            highlight: Option<&'a str>,
13013        }
13014
13015        let snapshot = buffer.read(cx).snapshot();
13016        let range = self
13017            .selected_text_range(false, cx)
13018            .and_then(|selection| {
13019                if selection.range.is_empty() {
13020                    None
13021                } else {
13022                    Some(selection.range)
13023                }
13024            })
13025            .unwrap_or_else(|| 0..snapshot.len());
13026
13027        let chunks = snapshot.chunks(range, true);
13028        let mut lines = Vec::new();
13029        let mut line: VecDeque<Chunk> = VecDeque::new();
13030
13031        let Some(style) = self.style.as_ref() else {
13032            return;
13033        };
13034
13035        for chunk in chunks {
13036            let highlight = chunk
13037                .syntax_highlight_id
13038                .and_then(|id| id.name(&style.syntax));
13039            let mut chunk_lines = chunk.text.split('\n').peekable();
13040            while let Some(text) = chunk_lines.next() {
13041                let mut merged_with_last_token = false;
13042                if let Some(last_token) = line.back_mut() {
13043                    if last_token.highlight == highlight {
13044                        last_token.text.push_str(text);
13045                        merged_with_last_token = true;
13046                    }
13047                }
13048
13049                if !merged_with_last_token {
13050                    line.push_back(Chunk {
13051                        text: text.into(),
13052                        highlight,
13053                    });
13054                }
13055
13056                if chunk_lines.peek().is_some() {
13057                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13058                        line.pop_front();
13059                    }
13060                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13061                        line.pop_back();
13062                    }
13063
13064                    lines.push(mem::take(&mut line));
13065                }
13066            }
13067        }
13068
13069        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13070            return;
13071        };
13072        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13073    }
13074
13075    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13076        &self.inlay_hint_cache
13077    }
13078
13079    pub fn replay_insert_event(
13080        &mut self,
13081        text: &str,
13082        relative_utf16_range: Option<Range<isize>>,
13083        cx: &mut ViewContext<Self>,
13084    ) {
13085        if !self.input_enabled {
13086            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13087            return;
13088        }
13089        if let Some(relative_utf16_range) = relative_utf16_range {
13090            let selections = self.selections.all::<OffsetUtf16>(cx);
13091            self.change_selections(None, cx, |s| {
13092                let new_ranges = selections.into_iter().map(|range| {
13093                    let start = OffsetUtf16(
13094                        range
13095                            .head()
13096                            .0
13097                            .saturating_add_signed(relative_utf16_range.start),
13098                    );
13099                    let end = OffsetUtf16(
13100                        range
13101                            .head()
13102                            .0
13103                            .saturating_add_signed(relative_utf16_range.end),
13104                    );
13105                    start..end
13106                });
13107                s.select_ranges(new_ranges);
13108            });
13109        }
13110
13111        self.handle_input(text, cx);
13112    }
13113
13114    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13115        let Some(provider) = self.semantics_provider.as_ref() else {
13116            return false;
13117        };
13118
13119        let mut supports = false;
13120        self.buffer().read(cx).for_each_buffer(|buffer| {
13121            supports |= provider.supports_inlay_hints(buffer, cx);
13122        });
13123        supports
13124    }
13125
13126    pub fn focus(&self, cx: &mut WindowContext) {
13127        cx.focus(&self.focus_handle)
13128    }
13129
13130    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13131        self.focus_handle.is_focused(cx)
13132    }
13133
13134    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13135        cx.emit(EditorEvent::Focused);
13136
13137        if let Some(descendant) = self
13138            .last_focused_descendant
13139            .take()
13140            .and_then(|descendant| descendant.upgrade())
13141        {
13142            cx.focus(&descendant);
13143        } else {
13144            if let Some(blame) = self.blame.as_ref() {
13145                blame.update(cx, GitBlame::focus)
13146            }
13147
13148            self.blink_manager.update(cx, BlinkManager::enable);
13149            self.show_cursor_names(cx);
13150            self.buffer.update(cx, |buffer, cx| {
13151                buffer.finalize_last_transaction(cx);
13152                if self.leader_peer_id.is_none() {
13153                    buffer.set_active_selections(
13154                        &self.selections.disjoint_anchors(),
13155                        self.selections.line_mode,
13156                        self.cursor_shape,
13157                        cx,
13158                    );
13159                }
13160            });
13161        }
13162    }
13163
13164    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13165        cx.emit(EditorEvent::FocusedIn)
13166    }
13167
13168    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13169        if event.blurred != self.focus_handle {
13170            self.last_focused_descendant = Some(event.blurred);
13171        }
13172    }
13173
13174    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13175        self.blink_manager.update(cx, BlinkManager::disable);
13176        self.buffer
13177            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13178
13179        if let Some(blame) = self.blame.as_ref() {
13180            blame.update(cx, GitBlame::blur)
13181        }
13182        if !self.hover_state.focused(cx) {
13183            hide_hover(self, cx);
13184        }
13185
13186        self.hide_context_menu(cx);
13187        cx.emit(EditorEvent::Blurred);
13188        cx.notify();
13189    }
13190
13191    pub fn register_action<A: Action>(
13192        &mut self,
13193        listener: impl Fn(&A, &mut WindowContext) + 'static,
13194    ) -> Subscription {
13195        let id = self.next_editor_action_id.post_inc();
13196        let listener = Arc::new(listener);
13197        self.editor_actions.borrow_mut().insert(
13198            id,
13199            Box::new(move |cx| {
13200                let cx = cx.window_context();
13201                let listener = listener.clone();
13202                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13203                    let action = action.downcast_ref().unwrap();
13204                    if phase == DispatchPhase::Bubble {
13205                        listener(action, cx)
13206                    }
13207                })
13208            }),
13209        );
13210
13211        let editor_actions = self.editor_actions.clone();
13212        Subscription::new(move || {
13213            editor_actions.borrow_mut().remove(&id);
13214        })
13215    }
13216
13217    pub fn file_header_size(&self) -> u32 {
13218        FILE_HEADER_HEIGHT
13219    }
13220
13221    pub fn revert(
13222        &mut self,
13223        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13224        cx: &mut ViewContext<Self>,
13225    ) {
13226        self.buffer().update(cx, |multi_buffer, cx| {
13227            for (buffer_id, changes) in revert_changes {
13228                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13229                    buffer.update(cx, |buffer, cx| {
13230                        buffer.edit(
13231                            changes.into_iter().map(|(range, text)| {
13232                                (range, text.to_string().map(Arc::<str>::from))
13233                            }),
13234                            None,
13235                            cx,
13236                        );
13237                    });
13238                }
13239            }
13240        });
13241        self.change_selections(None, cx, |selections| selections.refresh());
13242    }
13243
13244    pub fn to_pixel_point(
13245        &mut self,
13246        source: multi_buffer::Anchor,
13247        editor_snapshot: &EditorSnapshot,
13248        cx: &mut ViewContext<Self>,
13249    ) -> Option<gpui::Point<Pixels>> {
13250        let source_point = source.to_display_point(editor_snapshot);
13251        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13252    }
13253
13254    pub fn display_to_pixel_point(
13255        &mut self,
13256        source: DisplayPoint,
13257        editor_snapshot: &EditorSnapshot,
13258        cx: &mut ViewContext<Self>,
13259    ) -> Option<gpui::Point<Pixels>> {
13260        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13261        let text_layout_details = self.text_layout_details(cx);
13262        let scroll_top = text_layout_details
13263            .scroll_anchor
13264            .scroll_position(editor_snapshot)
13265            .y;
13266
13267        if source.row().as_f32() < scroll_top.floor() {
13268            return None;
13269        }
13270        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13271        let source_y = line_height * (source.row().as_f32() - scroll_top);
13272        Some(gpui::Point::new(source_x, source_y))
13273    }
13274
13275    pub fn has_active_completions_menu(&self) -> bool {
13276        self.context_menu.read().as_ref().map_or(false, |menu| {
13277            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13278        })
13279    }
13280
13281    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13282        self.addons
13283            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13284    }
13285
13286    pub fn unregister_addon<T: Addon>(&mut self) {
13287        self.addons.remove(&std::any::TypeId::of::<T>());
13288    }
13289
13290    pub fn addon<T: Addon>(&self) -> Option<&T> {
13291        let type_id = std::any::TypeId::of::<T>();
13292        self.addons
13293            .get(&type_id)
13294            .and_then(|item| item.to_any().downcast_ref::<T>())
13295    }
13296}
13297
13298fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13299    let tab_size = tab_size.get() as usize;
13300    let mut width = offset;
13301
13302    for ch in text.chars() {
13303        width += if ch == '\t' {
13304            tab_size - (width % tab_size)
13305        } else {
13306            1
13307        };
13308    }
13309
13310    width - offset
13311}
13312
13313#[cfg(test)]
13314mod tests {
13315    use super::*;
13316
13317    #[test]
13318    fn test_string_size_with_expanded_tabs() {
13319        let nz = |val| NonZeroU32::new(val).unwrap();
13320        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13321        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13322        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13323        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13324        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13325        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13326        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13327        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13328    }
13329}
13330
13331/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13332struct WordBreakingTokenizer<'a> {
13333    input: &'a str,
13334}
13335
13336impl<'a> WordBreakingTokenizer<'a> {
13337    fn new(input: &'a str) -> Self {
13338        Self { input }
13339    }
13340}
13341
13342fn is_char_ideographic(ch: char) -> bool {
13343    use unicode_script::Script::*;
13344    use unicode_script::UnicodeScript;
13345    matches!(ch.script(), Han | Tangut | Yi)
13346}
13347
13348fn is_grapheme_ideographic(text: &str) -> bool {
13349    text.chars().any(is_char_ideographic)
13350}
13351
13352fn is_grapheme_whitespace(text: &str) -> bool {
13353    text.chars().any(|x| x.is_whitespace())
13354}
13355
13356fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13357    text.chars().next().map_or(false, |ch| {
13358        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13359    })
13360}
13361
13362#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13363struct WordBreakToken<'a> {
13364    token: &'a str,
13365    grapheme_len: usize,
13366    is_whitespace: bool,
13367}
13368
13369impl<'a> Iterator for WordBreakingTokenizer<'a> {
13370    /// Yields a span, the count of graphemes in the token, and whether it was
13371    /// whitespace. Note that it also breaks at word boundaries.
13372    type Item = WordBreakToken<'a>;
13373
13374    fn next(&mut self) -> Option<Self::Item> {
13375        use unicode_segmentation::UnicodeSegmentation;
13376        if self.input.is_empty() {
13377            return None;
13378        }
13379
13380        let mut iter = self.input.graphemes(true).peekable();
13381        let mut offset = 0;
13382        let mut graphemes = 0;
13383        if let Some(first_grapheme) = iter.next() {
13384            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13385            offset += first_grapheme.len();
13386            graphemes += 1;
13387            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13388                if let Some(grapheme) = iter.peek().copied() {
13389                    if should_stay_with_preceding_ideograph(grapheme) {
13390                        offset += grapheme.len();
13391                        graphemes += 1;
13392                    }
13393                }
13394            } else {
13395                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13396                let mut next_word_bound = words.peek().copied();
13397                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13398                    next_word_bound = words.next();
13399                }
13400                while let Some(grapheme) = iter.peek().copied() {
13401                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13402                        break;
13403                    };
13404                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13405                        break;
13406                    };
13407                    offset += grapheme.len();
13408                    graphemes += 1;
13409                    iter.next();
13410                }
13411            }
13412            let token = &self.input[..offset];
13413            self.input = &self.input[offset..];
13414            if is_whitespace {
13415                Some(WordBreakToken {
13416                    token: " ",
13417                    grapheme_len: 1,
13418                    is_whitespace: true,
13419                })
13420            } else {
13421                Some(WordBreakToken {
13422                    token,
13423                    grapheme_len: graphemes,
13424                    is_whitespace: false,
13425                })
13426            }
13427        } else {
13428            None
13429        }
13430    }
13431}
13432
13433#[test]
13434fn test_word_breaking_tokenizer() {
13435    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13436        ("", &[]),
13437        ("  ", &[(" ", 1, true)]),
13438        ("Ʒ", &[("Ʒ", 1, false)]),
13439        ("Ǽ", &[("Ǽ", 1, false)]),
13440        ("", &[("", 1, false)]),
13441        ("⋑⋑", &[("⋑⋑", 2, false)]),
13442        (
13443            "原理,进而",
13444            &[
13445                ("", 1, false),
13446                ("理,", 2, false),
13447                ("", 1, false),
13448                ("", 1, false),
13449            ],
13450        ),
13451        (
13452            "hello world",
13453            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13454        ),
13455        (
13456            "hello, world",
13457            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13458        ),
13459        (
13460            "  hello world",
13461            &[
13462                (" ", 1, true),
13463                ("hello", 5, false),
13464                (" ", 1, true),
13465                ("world", 5, false),
13466            ],
13467        ),
13468        (
13469            "这是什么 \n 钢笔",
13470            &[
13471                ("", 1, false),
13472                ("", 1, false),
13473                ("", 1, false),
13474                ("", 1, false),
13475                (" ", 1, true),
13476                ("", 1, false),
13477                ("", 1, false),
13478            ],
13479        ),
13480        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13481    ];
13482
13483    for (input, result) in tests {
13484        assert_eq!(
13485            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13486            result
13487                .iter()
13488                .copied()
13489                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13490                    token,
13491                    grapheme_len,
13492                    is_whitespace,
13493                })
13494                .collect::<Vec<_>>()
13495        );
13496    }
13497}
13498
13499fn wrap_with_prefix(
13500    line_prefix: String,
13501    unwrapped_text: String,
13502    wrap_column: usize,
13503    tab_size: NonZeroU32,
13504) -> String {
13505    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13506    let mut wrapped_text = String::new();
13507    let mut current_line = line_prefix.clone();
13508
13509    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13510    let mut current_line_len = line_prefix_len;
13511    for WordBreakToken {
13512        token,
13513        grapheme_len,
13514        is_whitespace,
13515    } in tokenizer
13516    {
13517        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13518            wrapped_text.push_str(current_line.trim_end());
13519            wrapped_text.push('\n');
13520            current_line.truncate(line_prefix.len());
13521            current_line_len = line_prefix_len;
13522            if !is_whitespace {
13523                current_line.push_str(token);
13524                current_line_len += grapheme_len;
13525            }
13526        } else if !is_whitespace {
13527            current_line.push_str(token);
13528            current_line_len += grapheme_len;
13529        } else if current_line_len != line_prefix_len {
13530            current_line.push(' ');
13531            current_line_len += 1;
13532        }
13533    }
13534
13535    if !current_line.is_empty() {
13536        wrapped_text.push_str(&current_line);
13537    }
13538    wrapped_text
13539}
13540
13541#[test]
13542fn test_wrap_with_prefix() {
13543    assert_eq!(
13544        wrap_with_prefix(
13545            "# ".to_string(),
13546            "abcdefg".to_string(),
13547            4,
13548            NonZeroU32::new(4).unwrap()
13549        ),
13550        "# abcdefg"
13551    );
13552    assert_eq!(
13553        wrap_with_prefix(
13554            "".to_string(),
13555            "\thello world".to_string(),
13556            8,
13557            NonZeroU32::new(4).unwrap()
13558        ),
13559        "hello\nworld"
13560    );
13561    assert_eq!(
13562        wrap_with_prefix(
13563            "// ".to_string(),
13564            "xx \nyy zz aa bb cc".to_string(),
13565            12,
13566            NonZeroU32::new(4).unwrap()
13567        ),
13568        "// xx yy zz\n// aa bb cc"
13569    );
13570    assert_eq!(
13571        wrap_with_prefix(
13572            String::new(),
13573            "这是什么 \n 钢笔".to_string(),
13574            3,
13575            NonZeroU32::new(4).unwrap()
13576        ),
13577        "这是什\n么 钢\n"
13578    );
13579}
13580
13581fn hunks_for_selections(
13582    multi_buffer_snapshot: &MultiBufferSnapshot,
13583    selections: &[Selection<Anchor>],
13584) -> Vec<MultiBufferDiffHunk> {
13585    let buffer_rows_for_selections = selections.iter().map(|selection| {
13586        let head = selection.head();
13587        let tail = selection.tail();
13588        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13589        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13590        if start > end {
13591            end..start
13592        } else {
13593            start..end
13594        }
13595    });
13596
13597    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13598}
13599
13600pub fn hunks_for_rows(
13601    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13602    multi_buffer_snapshot: &MultiBufferSnapshot,
13603) -> Vec<MultiBufferDiffHunk> {
13604    let mut hunks = Vec::new();
13605    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13606        HashMap::default();
13607    for selected_multi_buffer_rows in rows {
13608        let query_rows =
13609            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13610        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13611            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13612            // when the caret is just above or just below the deleted hunk.
13613            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13614            let related_to_selection = if allow_adjacent {
13615                hunk.row_range.overlaps(&query_rows)
13616                    || hunk.row_range.start == query_rows.end
13617                    || hunk.row_range.end == query_rows.start
13618            } else {
13619                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13620                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13621                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13622                    || selected_multi_buffer_rows.end == hunk.row_range.start
13623            };
13624            if related_to_selection {
13625                if !processed_buffer_rows
13626                    .entry(hunk.buffer_id)
13627                    .or_default()
13628                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13629                {
13630                    continue;
13631                }
13632                hunks.push(hunk);
13633            }
13634        }
13635    }
13636
13637    hunks
13638}
13639
13640pub trait CollaborationHub {
13641    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13642    fn user_participant_indices<'a>(
13643        &self,
13644        cx: &'a AppContext,
13645    ) -> &'a HashMap<u64, ParticipantIndex>;
13646    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13647}
13648
13649impl CollaborationHub for Model<Project> {
13650    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13651        self.read(cx).collaborators()
13652    }
13653
13654    fn user_participant_indices<'a>(
13655        &self,
13656        cx: &'a AppContext,
13657    ) -> &'a HashMap<u64, ParticipantIndex> {
13658        self.read(cx).user_store().read(cx).participant_indices()
13659    }
13660
13661    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13662        let this = self.read(cx);
13663        let user_ids = this.collaborators().values().map(|c| c.user_id);
13664        this.user_store().read_with(cx, |user_store, cx| {
13665            user_store.participant_names(user_ids, cx)
13666        })
13667    }
13668}
13669
13670pub trait SemanticsProvider {
13671    fn hover(
13672        &self,
13673        buffer: &Model<Buffer>,
13674        position: text::Anchor,
13675        cx: &mut AppContext,
13676    ) -> Option<Task<Vec<project::Hover>>>;
13677
13678    fn inlay_hints(
13679        &self,
13680        buffer_handle: Model<Buffer>,
13681        range: Range<text::Anchor>,
13682        cx: &mut AppContext,
13683    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13684
13685    fn resolve_inlay_hint(
13686        &self,
13687        hint: InlayHint,
13688        buffer_handle: Model<Buffer>,
13689        server_id: LanguageServerId,
13690        cx: &mut AppContext,
13691    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13692
13693    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13694
13695    fn document_highlights(
13696        &self,
13697        buffer: &Model<Buffer>,
13698        position: text::Anchor,
13699        cx: &mut AppContext,
13700    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13701
13702    fn definitions(
13703        &self,
13704        buffer: &Model<Buffer>,
13705        position: text::Anchor,
13706        kind: GotoDefinitionKind,
13707        cx: &mut AppContext,
13708    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13709
13710    fn range_for_rename(
13711        &self,
13712        buffer: &Model<Buffer>,
13713        position: text::Anchor,
13714        cx: &mut AppContext,
13715    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13716
13717    fn perform_rename(
13718        &self,
13719        buffer: &Model<Buffer>,
13720        position: text::Anchor,
13721        new_name: String,
13722        cx: &mut AppContext,
13723    ) -> Option<Task<Result<ProjectTransaction>>>;
13724}
13725
13726pub trait CompletionProvider {
13727    fn completions(
13728        &self,
13729        buffer: &Model<Buffer>,
13730        buffer_position: text::Anchor,
13731        trigger: CompletionContext,
13732        cx: &mut ViewContext<Editor>,
13733    ) -> Task<Result<Vec<Completion>>>;
13734
13735    fn resolve_completions(
13736        &self,
13737        buffer: Model<Buffer>,
13738        completion_indices: Vec<usize>,
13739        completions: Arc<RwLock<Box<[Completion]>>>,
13740        cx: &mut ViewContext<Editor>,
13741    ) -> Task<Result<bool>>;
13742
13743    fn apply_additional_edits_for_completion(
13744        &self,
13745        buffer: Model<Buffer>,
13746        completion: Completion,
13747        push_to_history: bool,
13748        cx: &mut ViewContext<Editor>,
13749    ) -> Task<Result<Option<language::Transaction>>>;
13750
13751    fn is_completion_trigger(
13752        &self,
13753        buffer: &Model<Buffer>,
13754        position: language::Anchor,
13755        text: &str,
13756        trigger_in_words: bool,
13757        cx: &mut ViewContext<Editor>,
13758    ) -> bool;
13759
13760    fn sort_completions(&self) -> bool {
13761        true
13762    }
13763}
13764
13765pub trait CodeActionProvider {
13766    fn code_actions(
13767        &self,
13768        buffer: &Model<Buffer>,
13769        range: Range<text::Anchor>,
13770        cx: &mut WindowContext,
13771    ) -> Task<Result<Vec<CodeAction>>>;
13772
13773    fn apply_code_action(
13774        &self,
13775        buffer_handle: Model<Buffer>,
13776        action: CodeAction,
13777        excerpt_id: ExcerptId,
13778        push_to_history: bool,
13779        cx: &mut WindowContext,
13780    ) -> Task<Result<ProjectTransaction>>;
13781}
13782
13783impl CodeActionProvider for Model<Project> {
13784    fn code_actions(
13785        &self,
13786        buffer: &Model<Buffer>,
13787        range: Range<text::Anchor>,
13788        cx: &mut WindowContext,
13789    ) -> Task<Result<Vec<CodeAction>>> {
13790        self.update(cx, |project, cx| {
13791            project.code_actions(buffer, range, None, cx)
13792        })
13793    }
13794
13795    fn apply_code_action(
13796        &self,
13797        buffer_handle: Model<Buffer>,
13798        action: CodeAction,
13799        _excerpt_id: ExcerptId,
13800        push_to_history: bool,
13801        cx: &mut WindowContext,
13802    ) -> Task<Result<ProjectTransaction>> {
13803        self.update(cx, |project, cx| {
13804            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13805        })
13806    }
13807}
13808
13809fn snippet_completions(
13810    project: &Project,
13811    buffer: &Model<Buffer>,
13812    buffer_position: text::Anchor,
13813    cx: &mut AppContext,
13814) -> Task<Result<Vec<Completion>>> {
13815    let language = buffer.read(cx).language_at(buffer_position);
13816    let language_name = language.as_ref().map(|language| language.lsp_id());
13817    let snippet_store = project.snippets().read(cx);
13818    let snippets = snippet_store.snippets_for(language_name, cx);
13819
13820    if snippets.is_empty() {
13821        return Task::ready(Ok(vec![]));
13822    }
13823    let snapshot = buffer.read(cx).text_snapshot();
13824    let chars: String = snapshot
13825        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13826        .collect();
13827
13828    let scope = language.map(|language| language.default_scope());
13829    let executor = cx.background_executor().clone();
13830
13831    cx.background_executor().spawn(async move {
13832        let classifier = CharClassifier::new(scope).for_completion(true);
13833        let mut last_word = chars
13834            .chars()
13835            .take_while(|c| classifier.is_word(*c))
13836            .collect::<String>();
13837        last_word = last_word.chars().rev().collect();
13838
13839        if last_word.is_empty() {
13840            return Ok(vec![]);
13841        }
13842
13843        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13844        let to_lsp = |point: &text::Anchor| {
13845            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13846            point_to_lsp(end)
13847        };
13848        let lsp_end = to_lsp(&buffer_position);
13849
13850        let candidates = snippets
13851            .iter()
13852            .enumerate()
13853            .flat_map(|(ix, snippet)| {
13854                snippet
13855                    .prefix
13856                    .iter()
13857                    .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
13858            })
13859            .collect::<Vec<StringMatchCandidate>>();
13860
13861        let mut matches = fuzzy::match_strings(
13862            &candidates,
13863            &last_word,
13864            last_word.chars().any(|c| c.is_uppercase()),
13865            100,
13866            &Default::default(),
13867            executor,
13868        )
13869        .await;
13870
13871        // Remove all candidates where the query's start does not match the start of any word in the candidate
13872        if let Some(query_start) = last_word.chars().next() {
13873            matches.retain(|string_match| {
13874                split_words(&string_match.string).any(|word| {
13875                    // Check that the first codepoint of the word as lowercase matches the first
13876                    // codepoint of the query as lowercase
13877                    word.chars()
13878                        .flat_map(|codepoint| codepoint.to_lowercase())
13879                        .zip(query_start.to_lowercase())
13880                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13881                })
13882            });
13883        }
13884
13885        let matched_strings = matches
13886            .into_iter()
13887            .map(|m| m.string)
13888            .collect::<HashSet<_>>();
13889
13890        let result: Vec<Completion> = snippets
13891            .into_iter()
13892            .filter_map(|snippet| {
13893                let matching_prefix = snippet
13894                    .prefix
13895                    .iter()
13896                    .find(|prefix| matched_strings.contains(*prefix))?;
13897                let start = as_offset - last_word.len();
13898                let start = snapshot.anchor_before(start);
13899                let range = start..buffer_position;
13900                let lsp_start = to_lsp(&start);
13901                let lsp_range = lsp::Range {
13902                    start: lsp_start,
13903                    end: lsp_end,
13904                };
13905                Some(Completion {
13906                    old_range: range,
13907                    new_text: snippet.body.clone(),
13908                    label: CodeLabel {
13909                        text: matching_prefix.clone(),
13910                        runs: vec![],
13911                        filter_range: 0..matching_prefix.len(),
13912                    },
13913                    server_id: LanguageServerId(usize::MAX),
13914                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13915                    lsp_completion: lsp::CompletionItem {
13916                        label: snippet.prefix.first().unwrap().clone(),
13917                        kind: Some(CompletionItemKind::SNIPPET),
13918                        label_details: snippet.description.as_ref().map(|description| {
13919                            lsp::CompletionItemLabelDetails {
13920                                detail: Some(description.clone()),
13921                                description: None,
13922                            }
13923                        }),
13924                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13925                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13926                            lsp::InsertReplaceEdit {
13927                                new_text: snippet.body.clone(),
13928                                insert: lsp_range,
13929                                replace: lsp_range,
13930                            },
13931                        )),
13932                        filter_text: Some(snippet.body.clone()),
13933                        sort_text: Some(char::MAX.to_string()),
13934                        ..Default::default()
13935                    },
13936                    confirm: None,
13937                })
13938            })
13939            .collect();
13940
13941        Ok(result)
13942    })
13943}
13944
13945impl CompletionProvider for Model<Project> {
13946    fn completions(
13947        &self,
13948        buffer: &Model<Buffer>,
13949        buffer_position: text::Anchor,
13950        options: CompletionContext,
13951        cx: &mut ViewContext<Editor>,
13952    ) -> Task<Result<Vec<Completion>>> {
13953        self.update(cx, |project, cx| {
13954            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13955            let project_completions = project.completions(buffer, buffer_position, options, cx);
13956            cx.background_executor().spawn(async move {
13957                let mut completions = project_completions.await?;
13958                let snippets_completions = snippets.await?;
13959                completions.extend(snippets_completions);
13960                Ok(completions)
13961            })
13962        })
13963    }
13964
13965    fn resolve_completions(
13966        &self,
13967        buffer: Model<Buffer>,
13968        completion_indices: Vec<usize>,
13969        completions: Arc<RwLock<Box<[Completion]>>>,
13970        cx: &mut ViewContext<Editor>,
13971    ) -> Task<Result<bool>> {
13972        self.update(cx, |project, cx| {
13973            project.resolve_completions(buffer, completion_indices, completions, cx)
13974        })
13975    }
13976
13977    fn apply_additional_edits_for_completion(
13978        &self,
13979        buffer: Model<Buffer>,
13980        completion: Completion,
13981        push_to_history: bool,
13982        cx: &mut ViewContext<Editor>,
13983    ) -> Task<Result<Option<language::Transaction>>> {
13984        self.update(cx, |project, cx| {
13985            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13986        })
13987    }
13988
13989    fn is_completion_trigger(
13990        &self,
13991        buffer: &Model<Buffer>,
13992        position: language::Anchor,
13993        text: &str,
13994        trigger_in_words: bool,
13995        cx: &mut ViewContext<Editor>,
13996    ) -> bool {
13997        if !EditorSettings::get_global(cx).show_completions_on_input {
13998            return false;
13999        }
14000
14001        let mut chars = text.chars();
14002        let char = if let Some(char) = chars.next() {
14003            char
14004        } else {
14005            return false;
14006        };
14007        if chars.next().is_some() {
14008            return false;
14009        }
14010
14011        let buffer = buffer.read(cx);
14012        let classifier = buffer
14013            .snapshot()
14014            .char_classifier_at(position)
14015            .for_completion(true);
14016        if trigger_in_words && classifier.is_word(char) {
14017            return true;
14018        }
14019
14020        buffer.completion_triggers().contains(text)
14021    }
14022}
14023
14024impl SemanticsProvider for Model<Project> {
14025    fn hover(
14026        &self,
14027        buffer: &Model<Buffer>,
14028        position: text::Anchor,
14029        cx: &mut AppContext,
14030    ) -> Option<Task<Vec<project::Hover>>> {
14031        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14032    }
14033
14034    fn document_highlights(
14035        &self,
14036        buffer: &Model<Buffer>,
14037        position: text::Anchor,
14038        cx: &mut AppContext,
14039    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14040        Some(self.update(cx, |project, cx| {
14041            project.document_highlights(buffer, position, cx)
14042        }))
14043    }
14044
14045    fn definitions(
14046        &self,
14047        buffer: &Model<Buffer>,
14048        position: text::Anchor,
14049        kind: GotoDefinitionKind,
14050        cx: &mut AppContext,
14051    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14052        Some(self.update(cx, |project, cx| match kind {
14053            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14054            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14055            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14056            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14057        }))
14058    }
14059
14060    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14061        // TODO: make this work for remote projects
14062        self.read(cx)
14063            .language_servers_for_buffer(buffer.read(cx), cx)
14064            .any(
14065                |(_, server)| match server.capabilities().inlay_hint_provider {
14066                    Some(lsp::OneOf::Left(enabled)) => enabled,
14067                    Some(lsp::OneOf::Right(_)) => true,
14068                    None => false,
14069                },
14070            )
14071    }
14072
14073    fn inlay_hints(
14074        &self,
14075        buffer_handle: Model<Buffer>,
14076        range: Range<text::Anchor>,
14077        cx: &mut AppContext,
14078    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14079        Some(self.update(cx, |project, cx| {
14080            project.inlay_hints(buffer_handle, range, cx)
14081        }))
14082    }
14083
14084    fn resolve_inlay_hint(
14085        &self,
14086        hint: InlayHint,
14087        buffer_handle: Model<Buffer>,
14088        server_id: LanguageServerId,
14089        cx: &mut AppContext,
14090    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14091        Some(self.update(cx, |project, cx| {
14092            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14093        }))
14094    }
14095
14096    fn range_for_rename(
14097        &self,
14098        buffer: &Model<Buffer>,
14099        position: text::Anchor,
14100        cx: &mut AppContext,
14101    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14102        Some(self.update(cx, |project, cx| {
14103            project.prepare_rename(buffer.clone(), position, cx)
14104        }))
14105    }
14106
14107    fn perform_rename(
14108        &self,
14109        buffer: &Model<Buffer>,
14110        position: text::Anchor,
14111        new_name: String,
14112        cx: &mut AppContext,
14113    ) -> Option<Task<Result<ProjectTransaction>>> {
14114        Some(self.update(cx, |project, cx| {
14115            project.perform_rename(buffer.clone(), position, new_name, cx)
14116        }))
14117    }
14118}
14119
14120fn inlay_hint_settings(
14121    location: Anchor,
14122    snapshot: &MultiBufferSnapshot,
14123    cx: &mut ViewContext<'_, Editor>,
14124) -> InlayHintSettings {
14125    let file = snapshot.file_at(location);
14126    let language = snapshot.language_at(location).map(|l| l.name());
14127    language_settings(language, file, cx).inlay_hints
14128}
14129
14130fn consume_contiguous_rows(
14131    contiguous_row_selections: &mut Vec<Selection<Point>>,
14132    selection: &Selection<Point>,
14133    display_map: &DisplaySnapshot,
14134    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14135) -> (MultiBufferRow, MultiBufferRow) {
14136    contiguous_row_selections.push(selection.clone());
14137    let start_row = MultiBufferRow(selection.start.row);
14138    let mut end_row = ending_row(selection, display_map);
14139
14140    while let Some(next_selection) = selections.peek() {
14141        if next_selection.start.row <= end_row.0 {
14142            end_row = ending_row(next_selection, display_map);
14143            contiguous_row_selections.push(selections.next().unwrap().clone());
14144        } else {
14145            break;
14146        }
14147    }
14148    (start_row, end_row)
14149}
14150
14151fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14152    if next_selection.end.column > 0 || next_selection.is_empty() {
14153        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14154    } else {
14155        MultiBufferRow(next_selection.end.row)
14156    }
14157}
14158
14159impl EditorSnapshot {
14160    pub fn remote_selections_in_range<'a>(
14161        &'a self,
14162        range: &'a Range<Anchor>,
14163        collaboration_hub: &dyn CollaborationHub,
14164        cx: &'a AppContext,
14165    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14166        let participant_names = collaboration_hub.user_names(cx);
14167        let participant_indices = collaboration_hub.user_participant_indices(cx);
14168        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14169        let collaborators_by_replica_id = collaborators_by_peer_id
14170            .iter()
14171            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14172            .collect::<HashMap<_, _>>();
14173        self.buffer_snapshot
14174            .selections_in_range(range, false)
14175            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14176                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14177                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14178                let user_name = participant_names.get(&collaborator.user_id).cloned();
14179                Some(RemoteSelection {
14180                    replica_id,
14181                    selection,
14182                    cursor_shape,
14183                    line_mode,
14184                    participant_index,
14185                    peer_id: collaborator.peer_id,
14186                    user_name,
14187                })
14188            })
14189    }
14190
14191    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14192        self.display_snapshot.buffer_snapshot.language_at(position)
14193    }
14194
14195    pub fn is_focused(&self) -> bool {
14196        self.is_focused
14197    }
14198
14199    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14200        self.placeholder_text.as_ref()
14201    }
14202
14203    pub fn scroll_position(&self) -> gpui::Point<f32> {
14204        self.scroll_anchor.scroll_position(&self.display_snapshot)
14205    }
14206
14207    fn gutter_dimensions(
14208        &self,
14209        font_id: FontId,
14210        font_size: Pixels,
14211        em_width: Pixels,
14212        em_advance: Pixels,
14213        max_line_number_width: Pixels,
14214        cx: &AppContext,
14215    ) -> GutterDimensions {
14216        if !self.show_gutter {
14217            return GutterDimensions::default();
14218        }
14219        let descent = cx.text_system().descent(font_id, font_size);
14220
14221        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14222            matches!(
14223                ProjectSettings::get_global(cx).git.git_gutter,
14224                Some(GitGutterSetting::TrackedFiles)
14225            )
14226        });
14227        let gutter_settings = EditorSettings::get_global(cx).gutter;
14228        let show_line_numbers = self
14229            .show_line_numbers
14230            .unwrap_or(gutter_settings.line_numbers);
14231        let line_gutter_width = if show_line_numbers {
14232            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14233            let min_width_for_number_on_gutter = em_advance * 4.0;
14234            max_line_number_width.max(min_width_for_number_on_gutter)
14235        } else {
14236            0.0.into()
14237        };
14238
14239        let show_code_actions = self
14240            .show_code_actions
14241            .unwrap_or(gutter_settings.code_actions);
14242
14243        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14244
14245        let git_blame_entries_width =
14246            self.git_blame_gutter_max_author_length
14247                .map(|max_author_length| {
14248                    // Length of the author name, but also space for the commit hash,
14249                    // the spacing and the timestamp.
14250                    let max_char_count = max_author_length
14251                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14252                        + 7 // length of commit sha
14253                        + 14 // length of max relative timestamp ("60 minutes ago")
14254                        + 4; // gaps and margins
14255
14256                    em_advance * max_char_count
14257                });
14258
14259        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14260        left_padding += if show_code_actions || show_runnables {
14261            em_width * 3.0
14262        } else if show_git_gutter && show_line_numbers {
14263            em_width * 2.0
14264        } else if show_git_gutter || show_line_numbers {
14265            em_width
14266        } else {
14267            px(0.)
14268        };
14269
14270        let right_padding = if gutter_settings.folds && show_line_numbers {
14271            em_width * 4.0
14272        } else if gutter_settings.folds {
14273            em_width * 3.0
14274        } else if show_line_numbers {
14275            em_width
14276        } else {
14277            px(0.)
14278        };
14279
14280        GutterDimensions {
14281            left_padding,
14282            right_padding,
14283            width: line_gutter_width + left_padding + right_padding,
14284            margin: -descent,
14285            git_blame_entries_width,
14286        }
14287    }
14288
14289    pub fn render_crease_toggle(
14290        &self,
14291        buffer_row: MultiBufferRow,
14292        row_contains_cursor: bool,
14293        editor: View<Editor>,
14294        cx: &mut WindowContext,
14295    ) -> Option<AnyElement> {
14296        let folded = self.is_line_folded(buffer_row);
14297        let mut is_foldable = false;
14298
14299        if let Some(crease) = self
14300            .crease_snapshot
14301            .query_row(buffer_row, &self.buffer_snapshot)
14302        {
14303            is_foldable = true;
14304            match crease {
14305                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14306                    if let Some(render_toggle) = render_toggle {
14307                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14308                            if folded {
14309                                editor.update(cx, |editor, cx| {
14310                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14311                                });
14312                            } else {
14313                                editor.update(cx, |editor, cx| {
14314                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14315                                });
14316                            }
14317                        });
14318                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14319                    }
14320                }
14321            }
14322        }
14323
14324        is_foldable |= self.starts_indent(buffer_row);
14325
14326        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14327            Some(
14328                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14329                    .selected(folded)
14330                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14331                        if folded {
14332                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14333                        } else {
14334                            this.fold_at(&FoldAt { buffer_row }, cx);
14335                        }
14336                    }))
14337                    .into_any_element(),
14338            )
14339        } else {
14340            None
14341        }
14342    }
14343
14344    pub fn render_crease_trailer(
14345        &self,
14346        buffer_row: MultiBufferRow,
14347        cx: &mut WindowContext,
14348    ) -> Option<AnyElement> {
14349        let folded = self.is_line_folded(buffer_row);
14350        if let Crease::Inline { render_trailer, .. } = self
14351            .crease_snapshot
14352            .query_row(buffer_row, &self.buffer_snapshot)?
14353        {
14354            let render_trailer = render_trailer.as_ref()?;
14355            Some(render_trailer(buffer_row, folded, cx))
14356        } else {
14357            None
14358        }
14359    }
14360}
14361
14362impl Deref for EditorSnapshot {
14363    type Target = DisplaySnapshot;
14364
14365    fn deref(&self) -> &Self::Target {
14366        &self.display_snapshot
14367    }
14368}
14369
14370#[derive(Clone, Debug, PartialEq, Eq)]
14371pub enum EditorEvent {
14372    InputIgnored {
14373        text: Arc<str>,
14374    },
14375    InputHandled {
14376        utf16_range_to_replace: Option<Range<isize>>,
14377        text: Arc<str>,
14378    },
14379    ExcerptsAdded {
14380        buffer: Model<Buffer>,
14381        predecessor: ExcerptId,
14382        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14383    },
14384    ExcerptsRemoved {
14385        ids: Vec<ExcerptId>,
14386    },
14387    ExcerptsEdited {
14388        ids: Vec<ExcerptId>,
14389    },
14390    ExcerptsExpanded {
14391        ids: Vec<ExcerptId>,
14392    },
14393    BufferEdited,
14394    Edited {
14395        transaction_id: clock::Lamport,
14396    },
14397    Reparsed(BufferId),
14398    Focused,
14399    FocusedIn,
14400    Blurred,
14401    DirtyChanged,
14402    Saved,
14403    TitleChanged,
14404    DiffBaseChanged,
14405    SelectionsChanged {
14406        local: bool,
14407    },
14408    ScrollPositionChanged {
14409        local: bool,
14410        autoscroll: bool,
14411    },
14412    Closed,
14413    TransactionUndone {
14414        transaction_id: clock::Lamport,
14415    },
14416    TransactionBegun {
14417        transaction_id: clock::Lamport,
14418    },
14419    Reloaded,
14420    CursorShapeChanged,
14421}
14422
14423impl EventEmitter<EditorEvent> for Editor {}
14424
14425impl FocusableView for Editor {
14426    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14427        self.focus_handle.clone()
14428    }
14429}
14430
14431impl Render for Editor {
14432    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14433        let settings = ThemeSettings::get_global(cx);
14434
14435        let mut text_style = match self.mode {
14436            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14437                color: cx.theme().colors().editor_foreground,
14438                font_family: settings.ui_font.family.clone(),
14439                font_features: settings.ui_font.features.clone(),
14440                font_fallbacks: settings.ui_font.fallbacks.clone(),
14441                font_size: rems(0.875).into(),
14442                font_weight: settings.ui_font.weight,
14443                line_height: relative(settings.buffer_line_height.value()),
14444                ..Default::default()
14445            },
14446            EditorMode::Full => TextStyle {
14447                color: cx.theme().colors().editor_foreground,
14448                font_family: settings.buffer_font.family.clone(),
14449                font_features: settings.buffer_font.features.clone(),
14450                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14451                font_size: settings.buffer_font_size(cx).into(),
14452                font_weight: settings.buffer_font.weight,
14453                line_height: relative(settings.buffer_line_height.value()),
14454                ..Default::default()
14455            },
14456        };
14457        if let Some(text_style_refinement) = &self.text_style_refinement {
14458            text_style.refine(text_style_refinement)
14459        }
14460
14461        let background = match self.mode {
14462            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14463            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14464            EditorMode::Full => cx.theme().colors().editor_background,
14465        };
14466
14467        EditorElement::new(
14468            cx.view(),
14469            EditorStyle {
14470                background,
14471                local_player: cx.theme().players().local(),
14472                text: text_style,
14473                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14474                syntax: cx.theme().syntax().clone(),
14475                status: cx.theme().status().clone(),
14476                inlay_hints_style: make_inlay_hints_style(cx),
14477                suggestions_style: HighlightStyle {
14478                    color: Some(cx.theme().status().predictive),
14479                    ..HighlightStyle::default()
14480                },
14481                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14482            },
14483        )
14484    }
14485}
14486
14487impl ViewInputHandler for Editor {
14488    fn text_for_range(
14489        &mut self,
14490        range_utf16: Range<usize>,
14491        adjusted_range: &mut Option<Range<usize>>,
14492        cx: &mut ViewContext<Self>,
14493    ) -> Option<String> {
14494        let snapshot = self.buffer.read(cx).read(cx);
14495        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14496        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14497        if (start.0..end.0) != range_utf16 {
14498            adjusted_range.replace(start.0..end.0);
14499        }
14500        Some(snapshot.text_for_range(start..end).collect())
14501    }
14502
14503    fn selected_text_range(
14504        &mut self,
14505        ignore_disabled_input: bool,
14506        cx: &mut ViewContext<Self>,
14507    ) -> Option<UTF16Selection> {
14508        // Prevent the IME menu from appearing when holding down an alphabetic key
14509        // while input is disabled.
14510        if !ignore_disabled_input && !self.input_enabled {
14511            return None;
14512        }
14513
14514        let selection = self.selections.newest::<OffsetUtf16>(cx);
14515        let range = selection.range();
14516
14517        Some(UTF16Selection {
14518            range: range.start.0..range.end.0,
14519            reversed: selection.reversed,
14520        })
14521    }
14522
14523    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14524        let snapshot = self.buffer.read(cx).read(cx);
14525        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14526        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14527    }
14528
14529    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14530        self.clear_highlights::<InputComposition>(cx);
14531        self.ime_transaction.take();
14532    }
14533
14534    fn replace_text_in_range(
14535        &mut self,
14536        range_utf16: Option<Range<usize>>,
14537        text: &str,
14538        cx: &mut ViewContext<Self>,
14539    ) {
14540        if !self.input_enabled {
14541            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14542            return;
14543        }
14544
14545        self.transact(cx, |this, cx| {
14546            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14547                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14548                Some(this.selection_replacement_ranges(range_utf16, cx))
14549            } else {
14550                this.marked_text_ranges(cx)
14551            };
14552
14553            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14554                let newest_selection_id = this.selections.newest_anchor().id;
14555                this.selections
14556                    .all::<OffsetUtf16>(cx)
14557                    .iter()
14558                    .zip(ranges_to_replace.iter())
14559                    .find_map(|(selection, range)| {
14560                        if selection.id == newest_selection_id {
14561                            Some(
14562                                (range.start.0 as isize - selection.head().0 as isize)
14563                                    ..(range.end.0 as isize - selection.head().0 as isize),
14564                            )
14565                        } else {
14566                            None
14567                        }
14568                    })
14569            });
14570
14571            cx.emit(EditorEvent::InputHandled {
14572                utf16_range_to_replace: range_to_replace,
14573                text: text.into(),
14574            });
14575
14576            if let Some(new_selected_ranges) = new_selected_ranges {
14577                this.change_selections(None, cx, |selections| {
14578                    selections.select_ranges(new_selected_ranges)
14579                });
14580                this.backspace(&Default::default(), cx);
14581            }
14582
14583            this.handle_input(text, cx);
14584        });
14585
14586        if let Some(transaction) = self.ime_transaction {
14587            self.buffer.update(cx, |buffer, cx| {
14588                buffer.group_until_transaction(transaction, cx);
14589            });
14590        }
14591
14592        self.unmark_text(cx);
14593    }
14594
14595    fn replace_and_mark_text_in_range(
14596        &mut self,
14597        range_utf16: Option<Range<usize>>,
14598        text: &str,
14599        new_selected_range_utf16: Option<Range<usize>>,
14600        cx: &mut ViewContext<Self>,
14601    ) {
14602        if !self.input_enabled {
14603            return;
14604        }
14605
14606        let transaction = self.transact(cx, |this, cx| {
14607            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14608                let snapshot = this.buffer.read(cx).read(cx);
14609                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14610                    for marked_range in &mut marked_ranges {
14611                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14612                        marked_range.start.0 += relative_range_utf16.start;
14613                        marked_range.start =
14614                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14615                        marked_range.end =
14616                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14617                    }
14618                }
14619                Some(marked_ranges)
14620            } else if let Some(range_utf16) = range_utf16 {
14621                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14622                Some(this.selection_replacement_ranges(range_utf16, cx))
14623            } else {
14624                None
14625            };
14626
14627            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14628                let newest_selection_id = this.selections.newest_anchor().id;
14629                this.selections
14630                    .all::<OffsetUtf16>(cx)
14631                    .iter()
14632                    .zip(ranges_to_replace.iter())
14633                    .find_map(|(selection, range)| {
14634                        if selection.id == newest_selection_id {
14635                            Some(
14636                                (range.start.0 as isize - selection.head().0 as isize)
14637                                    ..(range.end.0 as isize - selection.head().0 as isize),
14638                            )
14639                        } else {
14640                            None
14641                        }
14642                    })
14643            });
14644
14645            cx.emit(EditorEvent::InputHandled {
14646                utf16_range_to_replace: range_to_replace,
14647                text: text.into(),
14648            });
14649
14650            if let Some(ranges) = ranges_to_replace {
14651                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14652            }
14653
14654            let marked_ranges = {
14655                let snapshot = this.buffer.read(cx).read(cx);
14656                this.selections
14657                    .disjoint_anchors()
14658                    .iter()
14659                    .map(|selection| {
14660                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14661                    })
14662                    .collect::<Vec<_>>()
14663            };
14664
14665            if text.is_empty() {
14666                this.unmark_text(cx);
14667            } else {
14668                this.highlight_text::<InputComposition>(
14669                    marked_ranges.clone(),
14670                    HighlightStyle {
14671                        underline: Some(UnderlineStyle {
14672                            thickness: px(1.),
14673                            color: None,
14674                            wavy: false,
14675                        }),
14676                        ..Default::default()
14677                    },
14678                    cx,
14679                );
14680            }
14681
14682            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14683            let use_autoclose = this.use_autoclose;
14684            let use_auto_surround = this.use_auto_surround;
14685            this.set_use_autoclose(false);
14686            this.set_use_auto_surround(false);
14687            this.handle_input(text, cx);
14688            this.set_use_autoclose(use_autoclose);
14689            this.set_use_auto_surround(use_auto_surround);
14690
14691            if let Some(new_selected_range) = new_selected_range_utf16 {
14692                let snapshot = this.buffer.read(cx).read(cx);
14693                let new_selected_ranges = marked_ranges
14694                    .into_iter()
14695                    .map(|marked_range| {
14696                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14697                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14698                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14699                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14700                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14701                    })
14702                    .collect::<Vec<_>>();
14703
14704                drop(snapshot);
14705                this.change_selections(None, cx, |selections| {
14706                    selections.select_ranges(new_selected_ranges)
14707                });
14708            }
14709        });
14710
14711        self.ime_transaction = self.ime_transaction.or(transaction);
14712        if let Some(transaction) = self.ime_transaction {
14713            self.buffer.update(cx, |buffer, cx| {
14714                buffer.group_until_transaction(transaction, cx);
14715            });
14716        }
14717
14718        if self.text_highlights::<InputComposition>(cx).is_none() {
14719            self.ime_transaction.take();
14720        }
14721    }
14722
14723    fn bounds_for_range(
14724        &mut self,
14725        range_utf16: Range<usize>,
14726        element_bounds: gpui::Bounds<Pixels>,
14727        cx: &mut ViewContext<Self>,
14728    ) -> Option<gpui::Bounds<Pixels>> {
14729        let text_layout_details = self.text_layout_details(cx);
14730        let style = &text_layout_details.editor_style;
14731        let font_id = cx.text_system().resolve_font(&style.text.font());
14732        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14733        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14734
14735        let em_width = cx
14736            .text_system()
14737            .typographic_bounds(font_id, font_size, 'm')
14738            .unwrap()
14739            .size
14740            .width;
14741
14742        let snapshot = self.snapshot(cx);
14743        let scroll_position = snapshot.scroll_position();
14744        let scroll_left = scroll_position.x * em_width;
14745
14746        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14747        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14748            + self.gutter_dimensions.width
14749            + self.gutter_dimensions.margin;
14750        let y = line_height * (start.row().as_f32() - scroll_position.y);
14751
14752        Some(Bounds {
14753            origin: element_bounds.origin + point(x, y),
14754            size: size(em_width, line_height),
14755        })
14756    }
14757}
14758
14759trait SelectionExt {
14760    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14761    fn spanned_rows(
14762        &self,
14763        include_end_if_at_line_start: bool,
14764        map: &DisplaySnapshot,
14765    ) -> Range<MultiBufferRow>;
14766}
14767
14768impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14769    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14770        let start = self
14771            .start
14772            .to_point(&map.buffer_snapshot)
14773            .to_display_point(map);
14774        let end = self
14775            .end
14776            .to_point(&map.buffer_snapshot)
14777            .to_display_point(map);
14778        if self.reversed {
14779            end..start
14780        } else {
14781            start..end
14782        }
14783    }
14784
14785    fn spanned_rows(
14786        &self,
14787        include_end_if_at_line_start: bool,
14788        map: &DisplaySnapshot,
14789    ) -> Range<MultiBufferRow> {
14790        let start = self.start.to_point(&map.buffer_snapshot);
14791        let mut end = self.end.to_point(&map.buffer_snapshot);
14792        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14793            end.row -= 1;
14794        }
14795
14796        let buffer_start = map.prev_line_boundary(start).0;
14797        let buffer_end = map.next_line_boundary(end).0;
14798        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14799    }
14800}
14801
14802impl<T: InvalidationRegion> InvalidationStack<T> {
14803    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14804    where
14805        S: Clone + ToOffset,
14806    {
14807        while let Some(region) = self.last() {
14808            let all_selections_inside_invalidation_ranges =
14809                if selections.len() == region.ranges().len() {
14810                    selections
14811                        .iter()
14812                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14813                        .all(|(selection, invalidation_range)| {
14814                            let head = selection.head().to_offset(buffer);
14815                            invalidation_range.start <= head && invalidation_range.end >= head
14816                        })
14817                } else {
14818                    false
14819                };
14820
14821            if all_selections_inside_invalidation_ranges {
14822                break;
14823            } else {
14824                self.pop();
14825            }
14826        }
14827    }
14828}
14829
14830impl<T> Default for InvalidationStack<T> {
14831    fn default() -> Self {
14832        Self(Default::default())
14833    }
14834}
14835
14836impl<T> Deref for InvalidationStack<T> {
14837    type Target = Vec<T>;
14838
14839    fn deref(&self) -> &Self::Target {
14840        &self.0
14841    }
14842}
14843
14844impl<T> DerefMut for InvalidationStack<T> {
14845    fn deref_mut(&mut self) -> &mut Self::Target {
14846        &mut self.0
14847    }
14848}
14849
14850impl InvalidationRegion for SnippetState {
14851    fn ranges(&self) -> &[Range<Anchor>] {
14852        &self.ranges[self.active_index]
14853    }
14854}
14855
14856pub fn diagnostic_block_renderer(
14857    diagnostic: Diagnostic,
14858    max_message_rows: Option<u8>,
14859    allow_closing: bool,
14860    _is_valid: bool,
14861) -> RenderBlock {
14862    let (text_without_backticks, code_ranges) =
14863        highlight_diagnostic_message(&diagnostic, max_message_rows);
14864
14865    Arc::new(move |cx: &mut BlockContext| {
14866        let group_id: SharedString = cx.block_id.to_string().into();
14867
14868        let mut text_style = cx.text_style().clone();
14869        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14870        let theme_settings = ThemeSettings::get_global(cx);
14871        text_style.font_family = theme_settings.buffer_font.family.clone();
14872        text_style.font_style = theme_settings.buffer_font.style;
14873        text_style.font_features = theme_settings.buffer_font.features.clone();
14874        text_style.font_weight = theme_settings.buffer_font.weight;
14875
14876        let multi_line_diagnostic = diagnostic.message.contains('\n');
14877
14878        let buttons = |diagnostic: &Diagnostic| {
14879            if multi_line_diagnostic {
14880                v_flex()
14881            } else {
14882                h_flex()
14883            }
14884            .when(allow_closing, |div| {
14885                div.children(diagnostic.is_primary.then(|| {
14886                    IconButton::new("close-block", IconName::XCircle)
14887                        .icon_color(Color::Muted)
14888                        .size(ButtonSize::Compact)
14889                        .style(ButtonStyle::Transparent)
14890                        .visible_on_hover(group_id.clone())
14891                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14892                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14893                }))
14894            })
14895            .child(
14896                IconButton::new("copy-block", IconName::Copy)
14897                    .icon_color(Color::Muted)
14898                    .size(ButtonSize::Compact)
14899                    .style(ButtonStyle::Transparent)
14900                    .visible_on_hover(group_id.clone())
14901                    .on_click({
14902                        let message = diagnostic.message.clone();
14903                        move |_click, cx| {
14904                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14905                        }
14906                    })
14907                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14908            )
14909        };
14910
14911        let icon_size = buttons(&diagnostic)
14912            .into_any_element()
14913            .layout_as_root(AvailableSpace::min_size(), cx);
14914
14915        h_flex()
14916            .id(cx.block_id)
14917            .group(group_id.clone())
14918            .relative()
14919            .size_full()
14920            .block_mouse_down()
14921            .pl(cx.gutter_dimensions.width)
14922            .w(cx.max_width - cx.gutter_dimensions.full_width())
14923            .child(
14924                div()
14925                    .flex()
14926                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14927                    .flex_shrink(),
14928            )
14929            .child(buttons(&diagnostic))
14930            .child(div().flex().flex_shrink_0().child(
14931                StyledText::new(text_without_backticks.clone()).with_highlights(
14932                    &text_style,
14933                    code_ranges.iter().map(|range| {
14934                        (
14935                            range.clone(),
14936                            HighlightStyle {
14937                                font_weight: Some(FontWeight::BOLD),
14938                                ..Default::default()
14939                            },
14940                        )
14941                    }),
14942                ),
14943            ))
14944            .into_any_element()
14945    })
14946}
14947
14948pub fn highlight_diagnostic_message(
14949    diagnostic: &Diagnostic,
14950    mut max_message_rows: Option<u8>,
14951) -> (SharedString, Vec<Range<usize>>) {
14952    let mut text_without_backticks = String::new();
14953    let mut code_ranges = Vec::new();
14954
14955    if let Some(source) = &diagnostic.source {
14956        text_without_backticks.push_str(source);
14957        code_ranges.push(0..source.len());
14958        text_without_backticks.push_str(": ");
14959    }
14960
14961    let mut prev_offset = 0;
14962    let mut in_code_block = false;
14963    let has_row_limit = max_message_rows.is_some();
14964    let mut newline_indices = diagnostic
14965        .message
14966        .match_indices('\n')
14967        .filter(|_| has_row_limit)
14968        .map(|(ix, _)| ix)
14969        .fuse()
14970        .peekable();
14971
14972    for (quote_ix, _) in diagnostic
14973        .message
14974        .match_indices('`')
14975        .chain([(diagnostic.message.len(), "")])
14976    {
14977        let mut first_newline_ix = None;
14978        let mut last_newline_ix = None;
14979        while let Some(newline_ix) = newline_indices.peek() {
14980            if *newline_ix < quote_ix {
14981                if first_newline_ix.is_none() {
14982                    first_newline_ix = Some(*newline_ix);
14983                }
14984                last_newline_ix = Some(*newline_ix);
14985
14986                if let Some(rows_left) = &mut max_message_rows {
14987                    if *rows_left == 0 {
14988                        break;
14989                    } else {
14990                        *rows_left -= 1;
14991                    }
14992                }
14993                let _ = newline_indices.next();
14994            } else {
14995                break;
14996            }
14997        }
14998        let prev_len = text_without_backticks.len();
14999        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15000        text_without_backticks.push_str(new_text);
15001        if in_code_block {
15002            code_ranges.push(prev_len..text_without_backticks.len());
15003        }
15004        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15005        in_code_block = !in_code_block;
15006        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15007            text_without_backticks.push_str("...");
15008            break;
15009        }
15010    }
15011
15012    (text_without_backticks.into(), code_ranges)
15013}
15014
15015fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15016    match severity {
15017        DiagnosticSeverity::ERROR => colors.error,
15018        DiagnosticSeverity::WARNING => colors.warning,
15019        DiagnosticSeverity::INFORMATION => colors.info,
15020        DiagnosticSeverity::HINT => colors.info,
15021        _ => colors.ignored,
15022    }
15023}
15024
15025pub fn styled_runs_for_code_label<'a>(
15026    label: &'a CodeLabel,
15027    syntax_theme: &'a theme::SyntaxTheme,
15028) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15029    let fade_out = HighlightStyle {
15030        fade_out: Some(0.35),
15031        ..Default::default()
15032    };
15033
15034    let mut prev_end = label.filter_range.end;
15035    label
15036        .runs
15037        .iter()
15038        .enumerate()
15039        .flat_map(move |(ix, (range, highlight_id))| {
15040            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15041                style
15042            } else {
15043                return Default::default();
15044            };
15045            let mut muted_style = style;
15046            muted_style.highlight(fade_out);
15047
15048            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15049            if range.start >= label.filter_range.end {
15050                if range.start > prev_end {
15051                    runs.push((prev_end..range.start, fade_out));
15052                }
15053                runs.push((range.clone(), muted_style));
15054            } else if range.end <= label.filter_range.end {
15055                runs.push((range.clone(), style));
15056            } else {
15057                runs.push((range.start..label.filter_range.end, style));
15058                runs.push((label.filter_range.end..range.end, muted_style));
15059            }
15060            prev_end = cmp::max(prev_end, range.end);
15061
15062            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15063                runs.push((prev_end..label.text.len(), fade_out));
15064            }
15065
15066            runs
15067        })
15068}
15069
15070pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15071    let mut prev_index = 0;
15072    let mut prev_codepoint: Option<char> = None;
15073    text.char_indices()
15074        .chain([(text.len(), '\0')])
15075        .filter_map(move |(index, codepoint)| {
15076            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15077            let is_boundary = index == text.len()
15078                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15079                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15080            if is_boundary {
15081                let chunk = &text[prev_index..index];
15082                prev_index = index;
15083                Some(chunk)
15084            } else {
15085                None
15086            }
15087        })
15088}
15089
15090pub trait RangeToAnchorExt: Sized {
15091    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15092
15093    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15094        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15095        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15096    }
15097}
15098
15099impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15100    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15101        let start_offset = self.start.to_offset(snapshot);
15102        let end_offset = self.end.to_offset(snapshot);
15103        if start_offset == end_offset {
15104            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15105        } else {
15106            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15107        }
15108    }
15109}
15110
15111pub trait RowExt {
15112    fn as_f32(&self) -> f32;
15113
15114    fn next_row(&self) -> Self;
15115
15116    fn previous_row(&self) -> Self;
15117
15118    fn minus(&self, other: Self) -> u32;
15119}
15120
15121impl RowExt for DisplayRow {
15122    fn as_f32(&self) -> f32 {
15123        self.0 as f32
15124    }
15125
15126    fn next_row(&self) -> Self {
15127        Self(self.0 + 1)
15128    }
15129
15130    fn previous_row(&self) -> Self {
15131        Self(self.0.saturating_sub(1))
15132    }
15133
15134    fn minus(&self, other: Self) -> u32 {
15135        self.0 - other.0
15136    }
15137}
15138
15139impl RowExt for MultiBufferRow {
15140    fn as_f32(&self) -> f32 {
15141        self.0 as f32
15142    }
15143
15144    fn next_row(&self) -> Self {
15145        Self(self.0 + 1)
15146    }
15147
15148    fn previous_row(&self) -> Self {
15149        Self(self.0.saturating_sub(1))
15150    }
15151
15152    fn minus(&self, other: Self) -> u32 {
15153        self.0 - other.0
15154    }
15155}
15156
15157trait RowRangeExt {
15158    type Row;
15159
15160    fn len(&self) -> usize;
15161
15162    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15163}
15164
15165impl RowRangeExt for Range<MultiBufferRow> {
15166    type Row = MultiBufferRow;
15167
15168    fn len(&self) -> usize {
15169        (self.end.0 - self.start.0) as usize
15170    }
15171
15172    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15173        (self.start.0..self.end.0).map(MultiBufferRow)
15174    }
15175}
15176
15177impl RowRangeExt for Range<DisplayRow> {
15178    type Row = DisplayRow;
15179
15180    fn len(&self) -> usize {
15181        (self.end.0 - self.start.0) as usize
15182    }
15183
15184    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15185        (self.start.0..self.end.0).map(DisplayRow)
15186    }
15187}
15188
15189fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15190    if hunk.diff_base_byte_range.is_empty() {
15191        DiffHunkStatus::Added
15192    } else if hunk.row_range.is_empty() {
15193        DiffHunkStatus::Removed
15194    } else {
15195        DiffHunkStatus::Modified
15196    }
15197}
15198
15199/// If select range has more than one line, we
15200/// just point the cursor to range.start.
15201fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15202    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15203        range
15204    } else {
15205        range.start..range.start
15206    }
15207}
15208
15209pub struct KillRing(ClipboardItem);
15210impl Global for KillRing {}
15211
15212const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);