editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod debounced_delay;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45mod signature_help;
   46#[cfg(any(test, feature = "test-support"))]
   47pub mod test;
   48
   49use ::git::diff::DiffHunkStatus;
   50pub(crate) use actions::*;
   51pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use debounced_delay::DebouncedDelay;
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use gpui::{
   74    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   75    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   76    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   77    FocusableView, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
   78    ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   79    ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
   80    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   81    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   82};
   83use highlight_matching_bracket::refresh_matching_bracket_highlights;
   84use hover_popover::{hide_hover, HoverState};
   85pub(crate) use hunk_diff::HoveredHunk;
   86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   87use indent_guides::ActiveIndentGuidesState;
   88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   89pub use inline_completion::Direction;
   90use inline_completion::{InlayProposal, InlineCompletionProvider, InlineCompletionProviderHandle};
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  100use linked_editing_ranges::refresh_linked_ranges;
  101pub use proposed_changes_editor::{
  102    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  103};
  104use similar::{ChangeTag, TextDiff};
  105use std::iter::Peekable;
  106use task::{ResolvedTask, TaskTemplate, TaskVariables};
  107
  108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  109pub use lsp::CompletionContext;
  110use lsp::{
  111    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  112    LanguageServerId, LanguageServerName,
  113};
  114use mouse_context_menu::MouseContextMenu;
  115use movement::TextLayoutDetails;
  116pub use multi_buffer::{
  117    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  118    ToPoint,
  119};
  120use multi_buffer::{
  121    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  122};
  123use ordered_float::OrderedFloat;
  124use parking_lot::{Mutex, RwLock};
  125use project::{
  126    lsp_store::{FormatTarget, FormatTrigger},
  127    project_settings::{GitGutterSetting, ProjectSettings},
  128    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  129    LocationLink, Project, ProjectTransaction, TaskSourceKind,
  130};
  131use rand::prelude::*;
  132use rpc::{proto::*, ErrorExt};
  133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  134use selections_collection::{
  135    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  136};
  137use serde::{Deserialize, Serialize};
  138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  139use smallvec::SmallVec;
  140use snippet::Snippet;
  141use std::{
  142    any::TypeId,
  143    borrow::Cow,
  144    cell::RefCell,
  145    cmp::{self, Ordering, Reverse},
  146    mem,
  147    num::NonZeroU32,
  148    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  149    path::{Path, PathBuf},
  150    rc::Rc,
  151    sync::Arc,
  152    time::{Duration, Instant},
  153};
  154pub use sum_tree::Bias;
  155use sum_tree::TreeMap;
  156use text::{BufferId, OffsetUtf16, Rope};
  157use theme::{
  158    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  159    ThemeColors, ThemeSettings,
  160};
  161use ui::{
  162    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  163    ListItem, Popover, PopoverMenuHandle, Tooltip,
  164};
  165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  166use workspace::item::{ItemHandle, PreviewTabsSettings};
  167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  168use workspace::{
  169    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  170};
  171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  172
  173use crate::hover_links::find_url;
  174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  175
  176pub const FILE_HEADER_HEIGHT: u32 = 2;
  177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  181const MAX_LINE_LEN: usize = 1024;
  182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  185#[doc(hidden)]
  186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  187#[doc(hidden)]
  188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub fn render_parsed_markdown(
  194    element_id: impl Into<ElementId>,
  195    parsed: &language::ParsedMarkdown,
  196    editor_style: &EditorStyle,
  197    workspace: Option<WeakView<Workspace>>,
  198    cx: &mut WindowContext,
  199) -> InteractiveText {
  200    let code_span_background_color = cx
  201        .theme()
  202        .colors()
  203        .editor_document_highlight_read_background;
  204
  205    let highlights = gpui::combine_highlights(
  206        parsed.highlights.iter().filter_map(|(range, highlight)| {
  207            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  208            Some((range.clone(), highlight))
  209        }),
  210        parsed
  211            .regions
  212            .iter()
  213            .zip(&parsed.region_ranges)
  214            .filter_map(|(region, range)| {
  215                if region.code {
  216                    Some((
  217                        range.clone(),
  218                        HighlightStyle {
  219                            background_color: Some(code_span_background_color),
  220                            ..Default::default()
  221                        },
  222                    ))
  223                } else {
  224                    None
  225                }
  226            }),
  227    );
  228
  229    let mut links = Vec::new();
  230    let mut link_ranges = Vec::new();
  231    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  232        if let Some(link) = region.link.clone() {
  233            links.push(link);
  234            link_ranges.push(range.clone());
  235        }
  236    }
  237
  238    InteractiveText::new(
  239        element_id,
  240        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  241    )
  242    .on_click(link_ranges, move |clicked_range_ix, cx| {
  243        match &links[clicked_range_ix] {
  244            markdown::Link::Web { url } => cx.open_url(url),
  245            markdown::Link::Path { path } => {
  246                if let Some(workspace) = &workspace {
  247                    _ = workspace.update(cx, |workspace, cx| {
  248                        workspace.open_abs_path(path.clone(), false, cx).detach();
  249                    });
  250                }
  251            }
  252        }
  253    })
  254}
  255
  256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  257pub(crate) enum InlayId {
  258    Suggestion(usize),
  259    Hint(usize),
  260}
  261
  262impl InlayId {
  263    fn id(&self) -> usize {
  264        match self {
  265            Self::Suggestion(id) => *id,
  266            Self::Hint(id) => *id,
  267        }
  268    }
  269}
  270
  271enum DiffRowHighlight {}
  272enum DocumentHighlightRead {}
  273enum DocumentHighlightWrite {}
  274enum InputComposition {}
  275
  276#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  277pub enum Navigated {
  278    Yes,
  279    No,
  280}
  281
  282impl Navigated {
  283    pub fn from_bool(yes: bool) -> Navigated {
  284        if yes {
  285            Navigated::Yes
  286        } else {
  287            Navigated::No
  288        }
  289    }
  290}
  291
  292pub fn init_settings(cx: &mut AppContext) {
  293    EditorSettings::register(cx);
  294}
  295
  296pub fn init(cx: &mut AppContext) {
  297    init_settings(cx);
  298
  299    workspace::register_project_item::<Editor>(cx);
  300    workspace::FollowableViewRegistry::register::<Editor>(cx);
  301    workspace::register_serializable_item::<Editor>(cx);
  302
  303    cx.observe_new_views(
  304        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  305            workspace.register_action(Editor::new_file);
  306            workspace.register_action(Editor::new_file_vertical);
  307            workspace.register_action(Editor::new_file_horizontal);
  308        },
  309    )
  310    .detach();
  311
  312    cx.on_action(move |_: &workspace::NewFile, cx| {
  313        let app_state = workspace::AppState::global(cx);
  314        if let Some(app_state) = app_state.upgrade() {
  315            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  316                Editor::new_file(workspace, &Default::default(), cx)
  317            })
  318            .detach();
  319        }
  320    });
  321    cx.on_action(move |_: &workspace::NewWindow, cx| {
  322        let app_state = workspace::AppState::global(cx);
  323        if let Some(app_state) = app_state.upgrade() {
  324            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  325                Editor::new_file(workspace, &Default::default(), cx)
  326            })
  327            .detach();
  328        }
  329    });
  330}
  331
  332pub struct SearchWithinRange;
  333
  334trait InvalidationRegion {
  335    fn ranges(&self) -> &[Range<Anchor>];
  336}
  337
  338#[derive(Clone, Debug, PartialEq)]
  339pub enum SelectPhase {
  340    Begin {
  341        position: DisplayPoint,
  342        add: bool,
  343        click_count: usize,
  344    },
  345    BeginColumnar {
  346        position: DisplayPoint,
  347        reset: bool,
  348        goal_column: u32,
  349    },
  350    Extend {
  351        position: DisplayPoint,
  352        click_count: usize,
  353    },
  354    Update {
  355        position: DisplayPoint,
  356        goal_column: u32,
  357        scroll_delta: gpui::Point<f32>,
  358    },
  359    End,
  360}
  361
  362#[derive(Clone, Debug)]
  363pub enum SelectMode {
  364    Character,
  365    Word(Range<Anchor>),
  366    Line(Range<Anchor>),
  367    All,
  368}
  369
  370#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  371pub enum EditorMode {
  372    SingleLine { auto_width: bool },
  373    AutoHeight { max_lines: usize },
  374    Full,
  375}
  376
  377#[derive(Copy, Clone, Debug)]
  378pub enum SoftWrap {
  379    /// Prefer not to wrap at all.
  380    ///
  381    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  382    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  383    GitDiff,
  384    /// Prefer a single line generally, unless an overly long line is encountered.
  385    None,
  386    /// Soft wrap lines that exceed the editor width.
  387    EditorWidth,
  388    /// Soft wrap lines at the preferred line length.
  389    Column(u32),
  390    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  391    Bounded(u32),
  392}
  393
  394#[derive(Clone)]
  395pub struct EditorStyle {
  396    pub background: Hsla,
  397    pub local_player: PlayerColor,
  398    pub text: TextStyle,
  399    pub scrollbar_width: Pixels,
  400    pub syntax: Arc<SyntaxTheme>,
  401    pub status: StatusColors,
  402    pub inlay_hints_style: HighlightStyle,
  403    pub suggestions_style: HighlightStyle,
  404    pub unnecessary_code_fade: f32,
  405}
  406
  407impl Default for EditorStyle {
  408    fn default() -> Self {
  409        Self {
  410            background: Hsla::default(),
  411            local_player: PlayerColor::default(),
  412            text: TextStyle::default(),
  413            scrollbar_width: Pixels::default(),
  414            syntax: Default::default(),
  415            // HACK: Status colors don't have a real default.
  416            // We should look into removing the status colors from the editor
  417            // style and retrieve them directly from the theme.
  418            status: StatusColors::dark(),
  419            inlay_hints_style: HighlightStyle::default(),
  420            suggestions_style: HighlightStyle::default(),
  421            unnecessary_code_fade: Default::default(),
  422        }
  423    }
  424}
  425
  426pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  427    let show_background = language_settings::language_settings(None, None, cx)
  428        .inlay_hints
  429        .show_background;
  430
  431    HighlightStyle {
  432        color: Some(cx.theme().status().hint),
  433        background_color: show_background.then(|| cx.theme().status().hint_background),
  434        ..HighlightStyle::default()
  435    }
  436}
  437
  438type CompletionId = usize;
  439
  440#[derive(Clone, Debug)]
  441struct CompletionState {
  442    // render_inlay_ids represents the inlay hints that are inserted
  443    // for rendering the inline completions. They may be discontinuous
  444    // in the event that the completion provider returns some intersection
  445    // with the existing content.
  446    render_inlay_ids: Vec<InlayId>,
  447    // text is the resulting rope that is inserted when the user accepts a completion.
  448    text: Rope,
  449    // position is the position of the cursor when the completion was triggered.
  450    position: multi_buffer::Anchor,
  451    // delete_range is the range of text that this completion state covers.
  452    // if the completion is accepted, this range should be deleted.
  453    delete_range: Option<Range<multi_buffer::Anchor>>,
  454}
  455
  456#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  457struct EditorActionId(usize);
  458
  459impl EditorActionId {
  460    pub fn post_inc(&mut self) -> Self {
  461        let answer = self.0;
  462
  463        *self = Self(answer + 1);
  464
  465        Self(answer)
  466    }
  467}
  468
  469// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  470// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  471
  472type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  473type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  474
  475#[derive(Default)]
  476struct ScrollbarMarkerState {
  477    scrollbar_size: Size<Pixels>,
  478    dirty: bool,
  479    markers: Arc<[PaintQuad]>,
  480    pending_refresh: Option<Task<Result<()>>>,
  481}
  482
  483impl ScrollbarMarkerState {
  484    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  485        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  486    }
  487}
  488
  489#[derive(Clone, Debug)]
  490struct RunnableTasks {
  491    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  492    offset: MultiBufferOffset,
  493    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  494    column: u32,
  495    // Values of all named captures, including those starting with '_'
  496    extra_variables: HashMap<String, String>,
  497    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  498    context_range: Range<BufferOffset>,
  499}
  500
  501impl RunnableTasks {
  502    fn resolve<'a>(
  503        &'a self,
  504        cx: &'a task::TaskContext,
  505    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  506        self.templates.iter().filter_map(|(kind, template)| {
  507            template
  508                .resolve_task(&kind.to_id_base(), cx)
  509                .map(|task| (kind.clone(), task))
  510        })
  511    }
  512}
  513
  514#[derive(Clone)]
  515struct ResolvedTasks {
  516    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  517    position: Anchor,
  518}
  519#[derive(Copy, Clone, Debug)]
  520struct MultiBufferOffset(usize);
  521#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  522struct BufferOffset(usize);
  523
  524// Addons allow storing per-editor state in other crates (e.g. Vim)
  525pub trait Addon: 'static {
  526    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  527
  528    fn to_any(&self) -> &dyn std::any::Any;
  529}
  530
  531#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  532pub enum IsVimMode {
  533    Yes,
  534    No,
  535}
  536
  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    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  600    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  601    code_actions_task: Option<Task<Result<()>>>,
  602    document_highlights_task: Option<Task<()>>,
  603    linked_editing_range_task: Option<Task<Option<()>>>,
  604    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  605    pending_rename: Option<RenameState>,
  606    searchable: bool,
  607    cursor_shape: CursorShape,
  608    current_line_highlight: Option<CurrentLineHighlight>,
  609    collapse_matches: bool,
  610    autoindent_mode: Option<AutoindentMode>,
  611    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  612    input_enabled: bool,
  613    use_modal_editing: bool,
  614    read_only: bool,
  615    leader_peer_id: Option<PeerId>,
  616    remote_id: Option<ViewId>,
  617    hover_state: HoverState,
  618    gutter_hovered: bool,
  619    hovered_link_state: Option<HoveredLinkState>,
  620    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  621    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  622    active_inline_completion: Option<CompletionState>,
  623    // enable_inline_completions is a switch that Vim can use to disable
  624    // inline completions based on its mode.
  625    enable_inline_completions: bool,
  626    show_inline_completions_override: Option<bool>,
  627    inlay_hint_cache: InlayHintCache,
  628    expanded_hunks: ExpandedHunks,
  629    next_inlay_id: usize,
  630    _subscriptions: Vec<Subscription>,
  631    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  632    gutter_dimensions: GutterDimensions,
  633    style: Option<EditorStyle>,
  634    text_style_refinement: Option<TextStyleRefinement>,
  635    next_editor_action_id: EditorActionId,
  636    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  637    use_autoclose: bool,
  638    use_auto_surround: bool,
  639    auto_replace_emoji_shortcode: bool,
  640    show_git_blame_gutter: bool,
  641    show_git_blame_inline: bool,
  642    show_git_blame_inline_delay_task: Option<Task<()>>,
  643    git_blame_inline_enabled: bool,
  644    serialize_dirty_buffers: bool,
  645    show_selection_menu: Option<bool>,
  646    blame: Option<Model<GitBlame>>,
  647    blame_subscription: Option<Subscription>,
  648    custom_context_menu: Option<
  649        Box<
  650            dyn 'static
  651                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  652        >,
  653    >,
  654    last_bounds: Option<Bounds<Pixels>>,
  655    expect_bounds_change: Option<Bounds<Pixels>>,
  656    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  657    tasks_update_task: Option<Task<()>>,
  658    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  659    breadcrumb_header: Option<String>,
  660    focused_block: Option<FocusedBlock>,
  661    next_scroll_position: NextScrollCursorCenterTopBottom,
  662    addons: HashMap<TypeId, Box<dyn Addon>>,
  663    _scroll_cursor_center_top_bottom_task: Task<()>,
  664}
  665
  666#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  667enum NextScrollCursorCenterTopBottom {
  668    #[default]
  669    Center,
  670    Top,
  671    Bottom,
  672}
  673
  674impl NextScrollCursorCenterTopBottom {
  675    fn next(&self) -> Self {
  676        match self {
  677            Self::Center => Self::Top,
  678            Self::Top => Self::Bottom,
  679            Self::Bottom => Self::Center,
  680        }
  681    }
  682}
  683
  684#[derive(Clone)]
  685pub struct EditorSnapshot {
  686    pub mode: EditorMode,
  687    show_gutter: bool,
  688    show_line_numbers: Option<bool>,
  689    show_git_diff_gutter: Option<bool>,
  690    show_code_actions: Option<bool>,
  691    show_runnables: Option<bool>,
  692    git_blame_gutter_max_author_length: Option<usize>,
  693    pub display_snapshot: DisplaySnapshot,
  694    pub placeholder_text: Option<Arc<str>>,
  695    is_focused: bool,
  696    scroll_anchor: ScrollAnchor,
  697    ongoing_scroll: OngoingScroll,
  698    current_line_highlight: CurrentLineHighlight,
  699    gutter_hovered: bool,
  700}
  701
  702const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  703
  704#[derive(Default, Debug, Clone, Copy)]
  705pub struct GutterDimensions {
  706    pub left_padding: Pixels,
  707    pub right_padding: Pixels,
  708    pub width: Pixels,
  709    pub margin: Pixels,
  710    pub git_blame_entries_width: Option<Pixels>,
  711}
  712
  713impl GutterDimensions {
  714    /// The full width of the space taken up by the gutter.
  715    pub fn full_width(&self) -> Pixels {
  716        self.margin + self.width
  717    }
  718
  719    /// The width of the space reserved for the fold indicators,
  720    /// use alongside 'justify_end' and `gutter_width` to
  721    /// right align content with the line numbers
  722    pub fn fold_area_width(&self) -> Pixels {
  723        self.margin + self.right_padding
  724    }
  725}
  726
  727#[derive(Debug)]
  728pub struct RemoteSelection {
  729    pub replica_id: ReplicaId,
  730    pub selection: Selection<Anchor>,
  731    pub cursor_shape: CursorShape,
  732    pub peer_id: PeerId,
  733    pub line_mode: bool,
  734    pub participant_index: Option<ParticipantIndex>,
  735    pub user_name: Option<SharedString>,
  736}
  737
  738#[derive(Clone, Debug)]
  739struct SelectionHistoryEntry {
  740    selections: Arc<[Selection<Anchor>]>,
  741    select_next_state: Option<SelectNextState>,
  742    select_prev_state: Option<SelectNextState>,
  743    add_selections_state: Option<AddSelectionsState>,
  744}
  745
  746enum SelectionHistoryMode {
  747    Normal,
  748    Undoing,
  749    Redoing,
  750}
  751
  752#[derive(Clone, PartialEq, Eq, Hash)]
  753struct HoveredCursor {
  754    replica_id: u16,
  755    selection_id: usize,
  756}
  757
  758impl Default for SelectionHistoryMode {
  759    fn default() -> Self {
  760        Self::Normal
  761    }
  762}
  763
  764#[derive(Default)]
  765struct SelectionHistory {
  766    #[allow(clippy::type_complexity)]
  767    selections_by_transaction:
  768        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  769    mode: SelectionHistoryMode,
  770    undo_stack: VecDeque<SelectionHistoryEntry>,
  771    redo_stack: VecDeque<SelectionHistoryEntry>,
  772}
  773
  774impl SelectionHistory {
  775    fn insert_transaction(
  776        &mut self,
  777        transaction_id: TransactionId,
  778        selections: Arc<[Selection<Anchor>]>,
  779    ) {
  780        self.selections_by_transaction
  781            .insert(transaction_id, (selections, None));
  782    }
  783
  784    #[allow(clippy::type_complexity)]
  785    fn transaction(
  786        &self,
  787        transaction_id: TransactionId,
  788    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  789        self.selections_by_transaction.get(&transaction_id)
  790    }
  791
  792    #[allow(clippy::type_complexity)]
  793    fn transaction_mut(
  794        &mut self,
  795        transaction_id: TransactionId,
  796    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  797        self.selections_by_transaction.get_mut(&transaction_id)
  798    }
  799
  800    fn push(&mut self, entry: SelectionHistoryEntry) {
  801        if !entry.selections.is_empty() {
  802            match self.mode {
  803                SelectionHistoryMode::Normal => {
  804                    self.push_undo(entry);
  805                    self.redo_stack.clear();
  806                }
  807                SelectionHistoryMode::Undoing => self.push_redo(entry),
  808                SelectionHistoryMode::Redoing => self.push_undo(entry),
  809            }
  810        }
  811    }
  812
  813    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  814        if self
  815            .undo_stack
  816            .back()
  817            .map_or(true, |e| e.selections != entry.selections)
  818        {
  819            self.undo_stack.push_back(entry);
  820            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  821                self.undo_stack.pop_front();
  822            }
  823        }
  824    }
  825
  826    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  827        if self
  828            .redo_stack
  829            .back()
  830            .map_or(true, |e| e.selections != entry.selections)
  831        {
  832            self.redo_stack.push_back(entry);
  833            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  834                self.redo_stack.pop_front();
  835            }
  836        }
  837    }
  838}
  839
  840struct RowHighlight {
  841    index: usize,
  842    range: Range<Anchor>,
  843    color: Hsla,
  844    should_autoscroll: bool,
  845}
  846
  847#[derive(Clone, Debug)]
  848struct AddSelectionsState {
  849    above: bool,
  850    stack: Vec<usize>,
  851}
  852
  853#[derive(Clone)]
  854struct SelectNextState {
  855    query: AhoCorasick,
  856    wordwise: bool,
  857    done: bool,
  858}
  859
  860impl std::fmt::Debug for SelectNextState {
  861    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  862        f.debug_struct(std::any::type_name::<Self>())
  863            .field("wordwise", &self.wordwise)
  864            .field("done", &self.done)
  865            .finish()
  866    }
  867}
  868
  869#[derive(Debug)]
  870struct AutocloseRegion {
  871    selection_id: usize,
  872    range: Range<Anchor>,
  873    pair: BracketPair,
  874}
  875
  876#[derive(Debug)]
  877struct SnippetState {
  878    ranges: Vec<Vec<Range<Anchor>>>,
  879    active_index: usize,
  880    choices: Vec<Option<Vec<String>>>,
  881}
  882
  883#[doc(hidden)]
  884pub struct RenameState {
  885    pub range: Range<Anchor>,
  886    pub old_name: Arc<str>,
  887    pub editor: View<Editor>,
  888    block_id: CustomBlockId,
  889}
  890
  891struct InvalidationStack<T>(Vec<T>);
  892
  893struct RegisteredInlineCompletionProvider {
  894    provider: Arc<dyn InlineCompletionProviderHandle>,
  895    _subscription: Subscription,
  896}
  897
  898enum ContextMenu {
  899    Completions(CompletionsMenu),
  900    CodeActions(CodeActionsMenu),
  901}
  902
  903impl ContextMenu {
  904    fn select_first(
  905        &mut self,
  906        provider: Option<&dyn CompletionProvider>,
  907        cx: &mut ViewContext<Editor>,
  908    ) -> bool {
  909        if self.visible() {
  910            match self {
  911                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  912                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  913            }
  914            true
  915        } else {
  916            false
  917        }
  918    }
  919
  920    fn select_prev(
  921        &mut self,
  922        provider: Option<&dyn CompletionProvider>,
  923        cx: &mut ViewContext<Editor>,
  924    ) -> bool {
  925        if self.visible() {
  926            match self {
  927                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  928                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  929            }
  930            true
  931        } else {
  932            false
  933        }
  934    }
  935
  936    fn select_next(
  937        &mut self,
  938        provider: Option<&dyn CompletionProvider>,
  939        cx: &mut ViewContext<Editor>,
  940    ) -> bool {
  941        if self.visible() {
  942            match self {
  943                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  944                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  945            }
  946            true
  947        } else {
  948            false
  949        }
  950    }
  951
  952    fn select_last(
  953        &mut self,
  954        provider: Option<&dyn CompletionProvider>,
  955        cx: &mut ViewContext<Editor>,
  956    ) -> bool {
  957        if self.visible() {
  958            match self {
  959                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  960                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  961            }
  962            true
  963        } else {
  964            false
  965        }
  966    }
  967
  968    fn visible(&self) -> bool {
  969        match self {
  970            ContextMenu::Completions(menu) => menu.visible(),
  971            ContextMenu::CodeActions(menu) => menu.visible(),
  972        }
  973    }
  974
  975    fn render(
  976        &self,
  977        cursor_position: DisplayPoint,
  978        style: &EditorStyle,
  979        max_height: Pixels,
  980        workspace: Option<WeakView<Workspace>>,
  981        cx: &mut ViewContext<Editor>,
  982    ) -> (ContextMenuOrigin, AnyElement) {
  983        match self {
  984            ContextMenu::Completions(menu) => (
  985                ContextMenuOrigin::EditorPoint(cursor_position),
  986                menu.render(style, max_height, workspace, cx),
  987            ),
  988            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  989        }
  990    }
  991}
  992
  993enum ContextMenuOrigin {
  994    EditorPoint(DisplayPoint),
  995    GutterIndicator(DisplayRow),
  996}
  997
  998#[derive(Clone, Debug)]
  999struct CompletionsMenu {
 1000    id: CompletionId,
 1001    sort_completions: bool,
 1002    initial_position: Anchor,
 1003    buffer: Model<Buffer>,
 1004    completions: Arc<RwLock<Box<[Completion]>>>,
 1005    match_candidates: Arc<[StringMatchCandidate]>,
 1006    matches: Arc<[StringMatch]>,
 1007    selected_item: usize,
 1008    scroll_handle: UniformListScrollHandle,
 1009    selected_completion_documentation_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
 1010}
 1011
 1012impl CompletionsMenu {
 1013    fn new(
 1014        id: CompletionId,
 1015        sort_completions: bool,
 1016        initial_position: Anchor,
 1017        buffer: Model<Buffer>,
 1018        completions: Box<[Completion]>,
 1019    ) -> Self {
 1020        let match_candidates = completions
 1021            .iter()
 1022            .enumerate()
 1023            .map(|(id, completion)| {
 1024                StringMatchCandidate::new(
 1025                    id,
 1026                    completion.label.text[completion.label.filter_range.clone()].into(),
 1027                )
 1028            })
 1029            .collect();
 1030
 1031        Self {
 1032            id,
 1033            sort_completions,
 1034            initial_position,
 1035            buffer,
 1036            completions: Arc::new(RwLock::new(completions)),
 1037            match_candidates,
 1038            matches: Vec::new().into(),
 1039            selected_item: 0,
 1040            scroll_handle: UniformListScrollHandle::new(),
 1041            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1042                DebouncedDelay::new(),
 1043            ))),
 1044        }
 1045    }
 1046
 1047    fn new_snippet_choices(
 1048        id: CompletionId,
 1049        sort_completions: bool,
 1050        choices: &Vec<String>,
 1051        selection: Range<Anchor>,
 1052        buffer: Model<Buffer>,
 1053    ) -> Self {
 1054        let completions = choices
 1055            .iter()
 1056            .map(|choice| Completion {
 1057                old_range: selection.start.text_anchor..selection.end.text_anchor,
 1058                new_text: choice.to_string(),
 1059                label: CodeLabel {
 1060                    text: choice.to_string(),
 1061                    runs: Default::default(),
 1062                    filter_range: Default::default(),
 1063                },
 1064                server_id: LanguageServerId(usize::MAX),
 1065                documentation: None,
 1066                lsp_completion: Default::default(),
 1067                confirm: None,
 1068            })
 1069            .collect();
 1070
 1071        let match_candidates = choices
 1072            .iter()
 1073            .enumerate()
 1074            .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
 1075            .collect();
 1076        let matches = choices
 1077            .iter()
 1078            .enumerate()
 1079            .map(|(id, completion)| StringMatch {
 1080                candidate_id: id,
 1081                score: 1.,
 1082                positions: vec![],
 1083                string: completion.clone(),
 1084            })
 1085            .collect();
 1086        Self {
 1087            id,
 1088            sort_completions,
 1089            initial_position: selection.start,
 1090            buffer,
 1091            completions: Arc::new(RwLock::new(completions)),
 1092            match_candidates,
 1093            matches,
 1094            selected_item: 0,
 1095            scroll_handle: UniformListScrollHandle::new(),
 1096            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1097                DebouncedDelay::new(),
 1098            ))),
 1099        }
 1100    }
 1101
 1102    fn suppress_documentation_resolution(mut self) -> Self {
 1103        self.selected_completion_documentation_resolve_debounce
 1104            .take();
 1105        self
 1106    }
 1107
 1108    fn select_first(
 1109        &mut self,
 1110        provider: Option<&dyn CompletionProvider>,
 1111        cx: &mut ViewContext<Editor>,
 1112    ) {
 1113        self.selected_item = 0;
 1114        self.scroll_handle
 1115            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1116        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1117        cx.notify();
 1118    }
 1119
 1120    fn select_prev(
 1121        &mut self,
 1122        provider: Option<&dyn CompletionProvider>,
 1123        cx: &mut ViewContext<Editor>,
 1124    ) {
 1125        if self.selected_item > 0 {
 1126            self.selected_item -= 1;
 1127        } else {
 1128            self.selected_item = self.matches.len() - 1;
 1129        }
 1130        self.scroll_handle
 1131            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1132        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1133        cx.notify();
 1134    }
 1135
 1136    fn select_next(
 1137        &mut self,
 1138        provider: Option<&dyn CompletionProvider>,
 1139        cx: &mut ViewContext<Editor>,
 1140    ) {
 1141        if self.selected_item + 1 < self.matches.len() {
 1142            self.selected_item += 1;
 1143        } else {
 1144            self.selected_item = 0;
 1145        }
 1146        self.scroll_handle
 1147            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1148        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1149        cx.notify();
 1150    }
 1151
 1152    fn select_last(
 1153        &mut self,
 1154        provider: Option<&dyn CompletionProvider>,
 1155        cx: &mut ViewContext<Editor>,
 1156    ) {
 1157        self.selected_item = self.matches.len() - 1;
 1158        self.scroll_handle
 1159            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1160        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1161        cx.notify();
 1162    }
 1163
 1164    fn pre_resolve_completion_documentation(
 1165        buffer: Model<Buffer>,
 1166        completions: Arc<RwLock<Box<[Completion]>>>,
 1167        matches: Arc<[StringMatch]>,
 1168        editor: &Editor,
 1169        cx: &mut ViewContext<Editor>,
 1170    ) -> Task<()> {
 1171        let settings = EditorSettings::get_global(cx);
 1172        if !settings.show_completion_documentation {
 1173            return Task::ready(());
 1174        }
 1175
 1176        let Some(provider) = editor.completion_provider.as_ref() else {
 1177            return Task::ready(());
 1178        };
 1179
 1180        let resolve_task = provider.resolve_completions(
 1181            buffer,
 1182            matches.iter().map(|m| m.candidate_id).collect(),
 1183            completions.clone(),
 1184            cx,
 1185        );
 1186
 1187        cx.spawn(move |this, mut cx| async move {
 1188            if let Some(true) = resolve_task.await.log_err() {
 1189                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1190            }
 1191        })
 1192    }
 1193
 1194    fn attempt_resolve_selected_completion_documentation(
 1195        &mut self,
 1196        provider: Option<&dyn CompletionProvider>,
 1197        cx: &mut ViewContext<Editor>,
 1198    ) {
 1199        let settings = EditorSettings::get_global(cx);
 1200        if !settings.show_completion_documentation {
 1201            return;
 1202        }
 1203
 1204        let completion_index = self.matches[self.selected_item].candidate_id;
 1205        let Some(provider) = provider else {
 1206            return;
 1207        };
 1208        let Some(documentation_resolve) = self
 1209            .selected_completion_documentation_resolve_debounce
 1210            .as_ref()
 1211        else {
 1212            return;
 1213        };
 1214
 1215        let resolve_task = provider.resolve_completions(
 1216            self.buffer.clone(),
 1217            vec![completion_index],
 1218            self.completions.clone(),
 1219            cx,
 1220        );
 1221
 1222        let delay_ms =
 1223            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1224        let delay = Duration::from_millis(delay_ms);
 1225
 1226        documentation_resolve.lock().fire_new(delay, cx, |_, cx| {
 1227            cx.spawn(move |this, mut cx| async move {
 1228                if let Some(true) = resolve_task.await.log_err() {
 1229                    this.update(&mut cx, |_, cx| cx.notify()).ok();
 1230                }
 1231            })
 1232        });
 1233    }
 1234
 1235    fn visible(&self) -> bool {
 1236        !self.matches.is_empty()
 1237    }
 1238
 1239    fn render(
 1240        &self,
 1241        style: &EditorStyle,
 1242        max_height: Pixels,
 1243        workspace: Option<WeakView<Workspace>>,
 1244        cx: &mut ViewContext<Editor>,
 1245    ) -> AnyElement {
 1246        let settings = EditorSettings::get_global(cx);
 1247        let show_completion_documentation = settings.show_completion_documentation;
 1248
 1249        let widest_completion_ix = self
 1250            .matches
 1251            .iter()
 1252            .enumerate()
 1253            .max_by_key(|(_, mat)| {
 1254                let completions = self.completions.read();
 1255                let completion = &completions[mat.candidate_id];
 1256                let documentation = &completion.documentation;
 1257
 1258                let mut len = completion.label.text.chars().count();
 1259                if let Some(Documentation::SingleLine(text)) = documentation {
 1260                    if show_completion_documentation {
 1261                        len += text.chars().count();
 1262                    }
 1263                }
 1264
 1265                len
 1266            })
 1267            .map(|(ix, _)| ix);
 1268
 1269        let completions = self.completions.clone();
 1270        let matches = self.matches.clone();
 1271        let selected_item = self.selected_item;
 1272        let style = style.clone();
 1273
 1274        let multiline_docs = if show_completion_documentation {
 1275            let mat = &self.matches[selected_item];
 1276            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1277                Some(Documentation::MultiLinePlainText(text)) => {
 1278                    Some(div().child(SharedString::from(text.clone())))
 1279                }
 1280                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1281                    Some(div().child(render_parsed_markdown(
 1282                        "completions_markdown",
 1283                        parsed,
 1284                        &style,
 1285                        workspace,
 1286                        cx,
 1287                    )))
 1288                }
 1289                _ => None,
 1290            };
 1291            multiline_docs.map(|div| {
 1292                div.id("multiline_docs")
 1293                    .max_h(max_height)
 1294                    .flex_1()
 1295                    .px_1p5()
 1296                    .py_1()
 1297                    .min_w(px(260.))
 1298                    .max_w(px(640.))
 1299                    .w(px(500.))
 1300                    .overflow_y_scroll()
 1301                    .occlude()
 1302            })
 1303        } else {
 1304            None
 1305        };
 1306
 1307        let list = uniform_list(
 1308            cx.view().clone(),
 1309            "completions",
 1310            matches.len(),
 1311            move |_editor, range, cx| {
 1312                let start_ix = range.start;
 1313                let completions_guard = completions.read();
 1314
 1315                matches[range]
 1316                    .iter()
 1317                    .enumerate()
 1318                    .map(|(ix, mat)| {
 1319                        let item_ix = start_ix + ix;
 1320                        let candidate_id = mat.candidate_id;
 1321                        let completion = &completions_guard[candidate_id];
 1322
 1323                        let documentation = if show_completion_documentation {
 1324                            &completion.documentation
 1325                        } else {
 1326                            &None
 1327                        };
 1328
 1329                        let highlights = gpui::combine_highlights(
 1330                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1331                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1332                                |(range, mut highlight)| {
 1333                                    // Ignore font weight for syntax highlighting, as we'll use it
 1334                                    // for fuzzy matches.
 1335                                    highlight.font_weight = None;
 1336
 1337                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1338                                        highlight.strikethrough = Some(StrikethroughStyle {
 1339                                            thickness: 1.0.into(),
 1340                                            ..Default::default()
 1341                                        });
 1342                                        highlight.color = Some(cx.theme().colors().text_muted);
 1343                                    }
 1344
 1345                                    (range, highlight)
 1346                                },
 1347                            ),
 1348                        );
 1349                        let completion_label = StyledText::new(completion.label.text.clone())
 1350                            .with_highlights(&style.text, highlights);
 1351                        let documentation_label =
 1352                            if let Some(Documentation::SingleLine(text)) = documentation {
 1353                                if text.trim().is_empty() {
 1354                                    None
 1355                                } else {
 1356                                    Some(
 1357                                        Label::new(text.clone())
 1358                                            .ml_4()
 1359                                            .size(LabelSize::Small)
 1360                                            .color(Color::Muted),
 1361                                    )
 1362                                }
 1363                            } else {
 1364                                None
 1365                            };
 1366
 1367                        let color_swatch = completion
 1368                            .color()
 1369                            .map(|color| div().size_4().bg(color).rounded_sm());
 1370
 1371                        div().min_w(px(220.)).max_w(px(540.)).child(
 1372                            ListItem::new(mat.candidate_id)
 1373                                .inset(true)
 1374                                .selected(item_ix == selected_item)
 1375                                .on_click(cx.listener(move |editor, _event, cx| {
 1376                                    cx.stop_propagation();
 1377                                    if let Some(task) = editor.confirm_completion(
 1378                                        &ConfirmCompletion {
 1379                                            item_ix: Some(item_ix),
 1380                                        },
 1381                                        cx,
 1382                                    ) {
 1383                                        task.detach_and_log_err(cx)
 1384                                    }
 1385                                }))
 1386                                .start_slot::<Div>(color_swatch)
 1387                                .child(h_flex().overflow_hidden().child(completion_label))
 1388                                .end_slot::<Label>(documentation_label),
 1389                        )
 1390                    })
 1391                    .collect()
 1392            },
 1393        )
 1394        .occlude()
 1395        .max_h(max_height)
 1396        .track_scroll(self.scroll_handle.clone())
 1397        .with_width_from_item(widest_completion_ix)
 1398        .with_sizing_behavior(ListSizingBehavior::Infer);
 1399
 1400        Popover::new()
 1401            .child(list)
 1402            .when_some(multiline_docs, |popover, multiline_docs| {
 1403                popover.aside(multiline_docs)
 1404            })
 1405            .into_any_element()
 1406    }
 1407
 1408    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1409        let mut matches = if let Some(query) = query {
 1410            fuzzy::match_strings(
 1411                &self.match_candidates,
 1412                query,
 1413                query.chars().any(|c| c.is_uppercase()),
 1414                100,
 1415                &Default::default(),
 1416                executor,
 1417            )
 1418            .await
 1419        } else {
 1420            self.match_candidates
 1421                .iter()
 1422                .enumerate()
 1423                .map(|(candidate_id, candidate)| StringMatch {
 1424                    candidate_id,
 1425                    score: Default::default(),
 1426                    positions: Default::default(),
 1427                    string: candidate.string.clone(),
 1428                })
 1429                .collect()
 1430        };
 1431
 1432        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1433        if let Some(query) = query {
 1434            if let Some(query_start) = query.chars().next() {
 1435                matches.retain(|string_match| {
 1436                    split_words(&string_match.string).any(|word| {
 1437                        // Check that the first codepoint of the word as lowercase matches the first
 1438                        // codepoint of the query as lowercase
 1439                        word.chars()
 1440                            .flat_map(|codepoint| codepoint.to_lowercase())
 1441                            .zip(query_start.to_lowercase())
 1442                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1443                    })
 1444                });
 1445            }
 1446        }
 1447
 1448        let completions = self.completions.read();
 1449        if self.sort_completions {
 1450            matches.sort_unstable_by_key(|mat| {
 1451                // We do want to strike a balance here between what the language server tells us
 1452                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1453                // `Creat` and there is a local variable called `CreateComponent`).
 1454                // So what we do is: we bucket all matches into two buckets
 1455                // - Strong matches
 1456                // - Weak matches
 1457                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1458                // and the Weak matches are the rest.
 1459                //
 1460                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1461                // matches, we prefer language-server sort_text first.
 1462                //
 1463                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1464                // Rest of the matches(weak) can be sorted as language-server expects.
 1465
 1466                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1467                enum MatchScore<'a> {
 1468                    Strong {
 1469                        score: Reverse<OrderedFloat<f64>>,
 1470                        sort_text: Option<&'a str>,
 1471                        sort_key: (usize, &'a str),
 1472                    },
 1473                    Weak {
 1474                        sort_text: Option<&'a str>,
 1475                        score: Reverse<OrderedFloat<f64>>,
 1476                        sort_key: (usize, &'a str),
 1477                    },
 1478                }
 1479
 1480                let completion = &completions[mat.candidate_id];
 1481                let sort_key = completion.sort_key();
 1482                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1483                let score = Reverse(OrderedFloat(mat.score));
 1484
 1485                if mat.score >= 0.2 {
 1486                    MatchScore::Strong {
 1487                        score,
 1488                        sort_text,
 1489                        sort_key,
 1490                    }
 1491                } else {
 1492                    MatchScore::Weak {
 1493                        sort_text,
 1494                        score,
 1495                        sort_key,
 1496                    }
 1497                }
 1498            });
 1499        }
 1500
 1501        for mat in &mut matches {
 1502            let completion = &completions[mat.candidate_id];
 1503            mat.string.clone_from(&completion.label.text);
 1504            for position in &mut mat.positions {
 1505                *position += completion.label.filter_range.start;
 1506            }
 1507        }
 1508        drop(completions);
 1509
 1510        self.matches = matches.into();
 1511        self.selected_item = 0;
 1512    }
 1513}
 1514
 1515#[derive(Clone)]
 1516struct AvailableCodeAction {
 1517    excerpt_id: ExcerptId,
 1518    action: CodeAction,
 1519    provider: Arc<dyn CodeActionProvider>,
 1520}
 1521
 1522#[derive(Clone)]
 1523struct CodeActionContents {
 1524    tasks: Option<Arc<ResolvedTasks>>,
 1525    actions: Option<Arc<[AvailableCodeAction]>>,
 1526}
 1527
 1528impl CodeActionContents {
 1529    fn len(&self) -> usize {
 1530        match (&self.tasks, &self.actions) {
 1531            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1532            (Some(tasks), None) => tasks.templates.len(),
 1533            (None, Some(actions)) => actions.len(),
 1534            (None, None) => 0,
 1535        }
 1536    }
 1537
 1538    fn is_empty(&self) -> bool {
 1539        match (&self.tasks, &self.actions) {
 1540            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1541            (Some(tasks), None) => tasks.templates.is_empty(),
 1542            (None, Some(actions)) => actions.is_empty(),
 1543            (None, None) => true,
 1544        }
 1545    }
 1546
 1547    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1548        self.tasks
 1549            .iter()
 1550            .flat_map(|tasks| {
 1551                tasks
 1552                    .templates
 1553                    .iter()
 1554                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1555            })
 1556            .chain(self.actions.iter().flat_map(|actions| {
 1557                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1558                    excerpt_id: available.excerpt_id,
 1559                    action: available.action.clone(),
 1560                    provider: available.provider.clone(),
 1561                })
 1562            }))
 1563    }
 1564    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1565        match (&self.tasks, &self.actions) {
 1566            (Some(tasks), Some(actions)) => {
 1567                if index < tasks.templates.len() {
 1568                    tasks
 1569                        .templates
 1570                        .get(index)
 1571                        .cloned()
 1572                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1573                } else {
 1574                    actions.get(index - tasks.templates.len()).map(|available| {
 1575                        CodeActionsItem::CodeAction {
 1576                            excerpt_id: available.excerpt_id,
 1577                            action: available.action.clone(),
 1578                            provider: available.provider.clone(),
 1579                        }
 1580                    })
 1581                }
 1582            }
 1583            (Some(tasks), None) => tasks
 1584                .templates
 1585                .get(index)
 1586                .cloned()
 1587                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1588            (None, Some(actions)) => {
 1589                actions
 1590                    .get(index)
 1591                    .map(|available| CodeActionsItem::CodeAction {
 1592                        excerpt_id: available.excerpt_id,
 1593                        action: available.action.clone(),
 1594                        provider: available.provider.clone(),
 1595                    })
 1596            }
 1597            (None, None) => None,
 1598        }
 1599    }
 1600}
 1601
 1602#[allow(clippy::large_enum_variant)]
 1603#[derive(Clone)]
 1604enum CodeActionsItem {
 1605    Task(TaskSourceKind, ResolvedTask),
 1606    CodeAction {
 1607        excerpt_id: ExcerptId,
 1608        action: CodeAction,
 1609        provider: Arc<dyn CodeActionProvider>,
 1610    },
 1611}
 1612
 1613impl CodeActionsItem {
 1614    fn as_task(&self) -> Option<&ResolvedTask> {
 1615        let Self::Task(_, task) = self else {
 1616            return None;
 1617        };
 1618        Some(task)
 1619    }
 1620    fn as_code_action(&self) -> Option<&CodeAction> {
 1621        let Self::CodeAction { action, .. } = self else {
 1622            return None;
 1623        };
 1624        Some(action)
 1625    }
 1626    fn label(&self) -> String {
 1627        match self {
 1628            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1629            Self::Task(_, task) => task.resolved_label.clone(),
 1630        }
 1631    }
 1632}
 1633
 1634struct CodeActionsMenu {
 1635    actions: CodeActionContents,
 1636    buffer: Model<Buffer>,
 1637    selected_item: usize,
 1638    scroll_handle: UniformListScrollHandle,
 1639    deployed_from_indicator: Option<DisplayRow>,
 1640}
 1641
 1642impl CodeActionsMenu {
 1643    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1644        self.selected_item = 0;
 1645        self.scroll_handle
 1646            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1647        cx.notify()
 1648    }
 1649
 1650    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1651        if self.selected_item > 0 {
 1652            self.selected_item -= 1;
 1653        } else {
 1654            self.selected_item = self.actions.len() - 1;
 1655        }
 1656        self.scroll_handle
 1657            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1658        cx.notify();
 1659    }
 1660
 1661    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1662        if self.selected_item + 1 < self.actions.len() {
 1663            self.selected_item += 1;
 1664        } else {
 1665            self.selected_item = 0;
 1666        }
 1667        self.scroll_handle
 1668            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1669        cx.notify();
 1670    }
 1671
 1672    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1673        self.selected_item = self.actions.len() - 1;
 1674        self.scroll_handle
 1675            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1676        cx.notify()
 1677    }
 1678
 1679    fn visible(&self) -> bool {
 1680        !self.actions.is_empty()
 1681    }
 1682
 1683    fn render(
 1684        &self,
 1685        cursor_position: DisplayPoint,
 1686        _style: &EditorStyle,
 1687        max_height: Pixels,
 1688        cx: &mut ViewContext<Editor>,
 1689    ) -> (ContextMenuOrigin, AnyElement) {
 1690        let actions = self.actions.clone();
 1691        let selected_item = self.selected_item;
 1692        let element = uniform_list(
 1693            cx.view().clone(),
 1694            "code_actions_menu",
 1695            self.actions.len(),
 1696            move |_this, range, cx| {
 1697                actions
 1698                    .iter()
 1699                    .skip(range.start)
 1700                    .take(range.end - range.start)
 1701                    .enumerate()
 1702                    .map(|(ix, action)| {
 1703                        let item_ix = range.start + ix;
 1704                        let selected = selected_item == item_ix;
 1705                        let colors = cx.theme().colors();
 1706                        div()
 1707                            .px_1()
 1708                            .rounded_md()
 1709                            .text_color(colors.text)
 1710                            .when(selected, |style| {
 1711                                style
 1712                                    .bg(colors.element_active)
 1713                                    .text_color(colors.text_accent)
 1714                            })
 1715                            .hover(|style| {
 1716                                style
 1717                                    .bg(colors.element_hover)
 1718                                    .text_color(colors.text_accent)
 1719                            })
 1720                            .whitespace_nowrap()
 1721                            .when_some(action.as_code_action(), |this, action| {
 1722                                this.on_mouse_down(
 1723                                    MouseButton::Left,
 1724                                    cx.listener(move |editor, _, cx| {
 1725                                        cx.stop_propagation();
 1726                                        if let Some(task) = editor.confirm_code_action(
 1727                                            &ConfirmCodeAction {
 1728                                                item_ix: Some(item_ix),
 1729                                            },
 1730                                            cx,
 1731                                        ) {
 1732                                            task.detach_and_log_err(cx)
 1733                                        }
 1734                                    }),
 1735                                )
 1736                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1737                                .child(SharedString::from(action.lsp_action.title.clone()))
 1738                            })
 1739                            .when_some(action.as_task(), |this, task| {
 1740                                this.on_mouse_down(
 1741                                    MouseButton::Left,
 1742                                    cx.listener(move |editor, _, cx| {
 1743                                        cx.stop_propagation();
 1744                                        if let Some(task) = editor.confirm_code_action(
 1745                                            &ConfirmCodeAction {
 1746                                                item_ix: Some(item_ix),
 1747                                            },
 1748                                            cx,
 1749                                        ) {
 1750                                            task.detach_and_log_err(cx)
 1751                                        }
 1752                                    }),
 1753                                )
 1754                                .child(SharedString::from(task.resolved_label.clone()))
 1755                            })
 1756                    })
 1757                    .collect()
 1758            },
 1759        )
 1760        .elevation_1(cx)
 1761        .p_1()
 1762        .max_h(max_height)
 1763        .occlude()
 1764        .track_scroll(self.scroll_handle.clone())
 1765        .with_width_from_item(
 1766            self.actions
 1767                .iter()
 1768                .enumerate()
 1769                .max_by_key(|(_, action)| match action {
 1770                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1771                    CodeActionsItem::CodeAction { action, .. } => {
 1772                        action.lsp_action.title.chars().count()
 1773                    }
 1774                })
 1775                .map(|(ix, _)| ix),
 1776        )
 1777        .with_sizing_behavior(ListSizingBehavior::Infer)
 1778        .into_any_element();
 1779
 1780        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1781            ContextMenuOrigin::GutterIndicator(row)
 1782        } else {
 1783            ContextMenuOrigin::EditorPoint(cursor_position)
 1784        };
 1785
 1786        (cursor_position, element)
 1787    }
 1788}
 1789
 1790#[derive(Debug)]
 1791struct ActiveDiagnosticGroup {
 1792    primary_range: Range<Anchor>,
 1793    primary_message: String,
 1794    group_id: usize,
 1795    blocks: HashMap<CustomBlockId, Diagnostic>,
 1796    is_valid: bool,
 1797}
 1798
 1799#[derive(Serialize, Deserialize, Clone, Debug)]
 1800pub struct ClipboardSelection {
 1801    pub len: usize,
 1802    pub is_entire_line: bool,
 1803    pub first_line_indent: u32,
 1804}
 1805
 1806#[derive(Debug)]
 1807pub(crate) struct NavigationData {
 1808    cursor_anchor: Anchor,
 1809    cursor_position: Point,
 1810    scroll_anchor: ScrollAnchor,
 1811    scroll_top_row: u32,
 1812}
 1813
 1814#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1815pub enum GotoDefinitionKind {
 1816    Symbol,
 1817    Declaration,
 1818    Type,
 1819    Implementation,
 1820}
 1821
 1822#[derive(Debug, Clone)]
 1823enum InlayHintRefreshReason {
 1824    Toggle(bool),
 1825    SettingsChange(InlayHintSettings),
 1826    NewLinesShown,
 1827    BufferEdited(HashSet<Arc<Language>>),
 1828    RefreshRequested,
 1829    ExcerptsRemoved(Vec<ExcerptId>),
 1830}
 1831
 1832impl InlayHintRefreshReason {
 1833    fn description(&self) -> &'static str {
 1834        match self {
 1835            Self::Toggle(_) => "toggle",
 1836            Self::SettingsChange(_) => "settings change",
 1837            Self::NewLinesShown => "new lines shown",
 1838            Self::BufferEdited(_) => "buffer edited",
 1839            Self::RefreshRequested => "refresh requested",
 1840            Self::ExcerptsRemoved(_) => "excerpts removed",
 1841        }
 1842    }
 1843}
 1844
 1845pub(crate) struct FocusedBlock {
 1846    id: BlockId,
 1847    focus_handle: WeakFocusHandle,
 1848}
 1849
 1850#[derive(Clone)]
 1851struct JumpData {
 1852    excerpt_id: ExcerptId,
 1853    position: Point,
 1854    anchor: text::Anchor,
 1855    path: Option<project::ProjectPath>,
 1856    line_offset_from_top: u32,
 1857}
 1858
 1859impl Editor {
 1860    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1861        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1862        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1863        Self::new(
 1864            EditorMode::SingleLine { auto_width: false },
 1865            buffer,
 1866            None,
 1867            false,
 1868            cx,
 1869        )
 1870    }
 1871
 1872    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1873        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1874        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1875        Self::new(EditorMode::Full, buffer, None, false, cx)
 1876    }
 1877
 1878    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1879        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1880        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1881        Self::new(
 1882            EditorMode::SingleLine { auto_width: true },
 1883            buffer,
 1884            None,
 1885            false,
 1886            cx,
 1887        )
 1888    }
 1889
 1890    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1891        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1892        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1893        Self::new(
 1894            EditorMode::AutoHeight { max_lines },
 1895            buffer,
 1896            None,
 1897            false,
 1898            cx,
 1899        )
 1900    }
 1901
 1902    pub fn for_buffer(
 1903        buffer: Model<Buffer>,
 1904        project: Option<Model<Project>>,
 1905        cx: &mut ViewContext<Self>,
 1906    ) -> Self {
 1907        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1908        Self::new(EditorMode::Full, buffer, project, false, cx)
 1909    }
 1910
 1911    pub fn for_multibuffer(
 1912        buffer: Model<MultiBuffer>,
 1913        project: Option<Model<Project>>,
 1914        show_excerpt_controls: bool,
 1915        cx: &mut ViewContext<Self>,
 1916    ) -> Self {
 1917        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1918    }
 1919
 1920    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1921        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1922        let mut clone = Self::new(
 1923            self.mode,
 1924            self.buffer.clone(),
 1925            self.project.clone(),
 1926            show_excerpt_controls,
 1927            cx,
 1928        );
 1929        self.display_map.update(cx, |display_map, cx| {
 1930            let snapshot = display_map.snapshot(cx);
 1931            clone.display_map.update(cx, |display_map, cx| {
 1932                display_map.set_state(&snapshot, cx);
 1933            });
 1934        });
 1935        clone.selections.clone_state(&self.selections);
 1936        clone.scroll_manager.clone_state(&self.scroll_manager);
 1937        clone.searchable = self.searchable;
 1938        clone
 1939    }
 1940
 1941    pub fn new(
 1942        mode: EditorMode,
 1943        buffer: Model<MultiBuffer>,
 1944        project: Option<Model<Project>>,
 1945        show_excerpt_controls: bool,
 1946        cx: &mut ViewContext<Self>,
 1947    ) -> Self {
 1948        let style = cx.text_style();
 1949        let font_size = style.font_size.to_pixels(cx.rem_size());
 1950        let editor = cx.view().downgrade();
 1951        let fold_placeholder = FoldPlaceholder {
 1952            constrain_width: true,
 1953            render: Arc::new(move |fold_id, fold_range, cx| {
 1954                let editor = editor.clone();
 1955                div()
 1956                    .id(fold_id)
 1957                    .bg(cx.theme().colors().ghost_element_background)
 1958                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1959                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1960                    .rounded_sm()
 1961                    .size_full()
 1962                    .cursor_pointer()
 1963                    .child("")
 1964                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1965                    .on_click(move |_, cx| {
 1966                        editor
 1967                            .update(cx, |editor, cx| {
 1968                                editor.unfold_ranges(
 1969                                    &[fold_range.start..fold_range.end],
 1970                                    true,
 1971                                    false,
 1972                                    cx,
 1973                                );
 1974                                cx.stop_propagation();
 1975                            })
 1976                            .ok();
 1977                    })
 1978                    .into_any()
 1979            }),
 1980            merge_adjacent: true,
 1981            ..Default::default()
 1982        };
 1983        let display_map = cx.new_model(|cx| {
 1984            DisplayMap::new(
 1985                buffer.clone(),
 1986                style.font(),
 1987                font_size,
 1988                None,
 1989                show_excerpt_controls,
 1990                FILE_HEADER_HEIGHT,
 1991                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1992                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1993                fold_placeholder,
 1994                cx,
 1995            )
 1996        });
 1997
 1998        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1999
 2000        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 2001
 2002        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 2003            .then(|| language_settings::SoftWrap::None);
 2004
 2005        let mut project_subscriptions = Vec::new();
 2006        if mode == EditorMode::Full {
 2007            if let Some(project) = project.as_ref() {
 2008                if buffer.read(cx).is_singleton() {
 2009                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 2010                        cx.emit(EditorEvent::TitleChanged);
 2011                    }));
 2012                }
 2013                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 2014                    if let project::Event::RefreshInlayHints = event {
 2015                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 2016                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 2017                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 2018                            let focus_handle = editor.focus_handle(cx);
 2019                            if focus_handle.is_focused(cx) {
 2020                                let snapshot = buffer.read(cx).snapshot();
 2021                                for (range, snippet) in snippet_edits {
 2022                                    let editor_range =
 2023                                        language::range_from_lsp(*range).to_offset(&snapshot);
 2024                                    editor
 2025                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 2026                                        .ok();
 2027                                }
 2028                            }
 2029                        }
 2030                    }
 2031                }));
 2032                if let Some(task_inventory) = project
 2033                    .read(cx)
 2034                    .task_store()
 2035                    .read(cx)
 2036                    .task_inventory()
 2037                    .cloned()
 2038                {
 2039                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 2040                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 2041                    }));
 2042                }
 2043            }
 2044        }
 2045
 2046        let inlay_hint_settings = inlay_hint_settings(
 2047            selections.newest_anchor().head(),
 2048            &buffer.read(cx).snapshot(cx),
 2049            cx,
 2050        );
 2051        let focus_handle = cx.focus_handle();
 2052        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 2053        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 2054            .detach();
 2055        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 2056            .detach();
 2057        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 2058
 2059        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 2060            Some(false)
 2061        } else {
 2062            None
 2063        };
 2064
 2065        let mut code_action_providers = Vec::new();
 2066        if let Some(project) = project.clone() {
 2067            code_action_providers.push(Arc::new(project) as Arc<_>);
 2068        }
 2069
 2070        let mut this = Self {
 2071            focus_handle,
 2072            show_cursor_when_unfocused: false,
 2073            last_focused_descendant: None,
 2074            buffer: buffer.clone(),
 2075            display_map: display_map.clone(),
 2076            selections,
 2077            scroll_manager: ScrollManager::new(cx),
 2078            columnar_selection_tail: None,
 2079            add_selections_state: None,
 2080            select_next_state: None,
 2081            select_prev_state: None,
 2082            selection_history: Default::default(),
 2083            autoclose_regions: Default::default(),
 2084            snippet_stack: Default::default(),
 2085            select_larger_syntax_node_stack: Vec::new(),
 2086            ime_transaction: Default::default(),
 2087            active_diagnostics: None,
 2088            soft_wrap_mode_override,
 2089            completion_provider: project.clone().map(|project| Box::new(project) as _),
 2090            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 2091            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 2092            project,
 2093            blink_manager: blink_manager.clone(),
 2094            show_local_selections: true,
 2095            mode,
 2096            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2097            show_gutter: mode == EditorMode::Full,
 2098            show_line_numbers: None,
 2099            use_relative_line_numbers: None,
 2100            show_git_diff_gutter: None,
 2101            show_code_actions: None,
 2102            show_runnables: None,
 2103            show_wrap_guides: None,
 2104            show_indent_guides,
 2105            placeholder_text: None,
 2106            highlight_order: 0,
 2107            highlighted_rows: HashMap::default(),
 2108            background_highlights: Default::default(),
 2109            gutter_highlights: TreeMap::default(),
 2110            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2111            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2112            nav_history: None,
 2113            context_menu: RwLock::new(None),
 2114            mouse_context_menu: None,
 2115            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2116            completion_tasks: Default::default(),
 2117            signature_help_state: SignatureHelpState::default(),
 2118            auto_signature_help: None,
 2119            find_all_references_task_sources: Vec::new(),
 2120            next_completion_id: 0,
 2121            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2122            next_inlay_id: 0,
 2123            code_action_providers,
 2124            available_code_actions: Default::default(),
 2125            code_actions_task: Default::default(),
 2126            document_highlights_task: Default::default(),
 2127            linked_editing_range_task: Default::default(),
 2128            pending_rename: Default::default(),
 2129            searchable: true,
 2130            cursor_shape: EditorSettings::get_global(cx)
 2131                .cursor_shape
 2132                .unwrap_or_default(),
 2133            current_line_highlight: None,
 2134            autoindent_mode: Some(AutoindentMode::EachLine),
 2135            collapse_matches: false,
 2136            workspace: None,
 2137            input_enabled: true,
 2138            use_modal_editing: mode == EditorMode::Full,
 2139            read_only: false,
 2140            use_autoclose: true,
 2141            use_auto_surround: true,
 2142            auto_replace_emoji_shortcode: false,
 2143            leader_peer_id: None,
 2144            remote_id: None,
 2145            hover_state: Default::default(),
 2146            hovered_link_state: Default::default(),
 2147            inline_completion_provider: None,
 2148            active_inline_completion: None,
 2149            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2150            expanded_hunks: ExpandedHunks::default(),
 2151            gutter_hovered: false,
 2152            pixel_position_of_newest_cursor: None,
 2153            last_bounds: None,
 2154            expect_bounds_change: None,
 2155            gutter_dimensions: GutterDimensions::default(),
 2156            style: None,
 2157            show_cursor_names: false,
 2158            hovered_cursors: Default::default(),
 2159            next_editor_action_id: EditorActionId::default(),
 2160            editor_actions: Rc::default(),
 2161            show_inline_completions_override: None,
 2162            enable_inline_completions: true,
 2163            custom_context_menu: None,
 2164            show_git_blame_gutter: false,
 2165            show_git_blame_inline: false,
 2166            show_selection_menu: None,
 2167            show_git_blame_inline_delay_task: None,
 2168            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2169            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2170                .session
 2171                .restore_unsaved_buffers,
 2172            blame: None,
 2173            blame_subscription: None,
 2174            tasks: Default::default(),
 2175            _subscriptions: vec![
 2176                cx.observe(&buffer, Self::on_buffer_changed),
 2177                cx.subscribe(&buffer, Self::on_buffer_event),
 2178                cx.observe(&display_map, Self::on_display_map_changed),
 2179                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2180                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2181                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2182                cx.observe_window_activation(|editor, cx| {
 2183                    let active = cx.is_window_active();
 2184                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2185                        if active {
 2186                            blink_manager.enable(cx);
 2187                        } else {
 2188                            blink_manager.disable(cx);
 2189                        }
 2190                    });
 2191                }),
 2192            ],
 2193            tasks_update_task: None,
 2194            linked_edit_ranges: Default::default(),
 2195            previous_search_ranges: None,
 2196            breadcrumb_header: None,
 2197            focused_block: None,
 2198            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2199            addons: HashMap::default(),
 2200            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2201            text_style_refinement: None,
 2202        };
 2203        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2204        this._subscriptions.extend(project_subscriptions);
 2205
 2206        this.end_selection(cx);
 2207        this.scroll_manager.show_scrollbar(cx);
 2208
 2209        if mode == EditorMode::Full {
 2210            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2211            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2212
 2213            if this.git_blame_inline_enabled {
 2214                this.git_blame_inline_enabled = true;
 2215                this.start_git_blame_inline(false, cx);
 2216            }
 2217        }
 2218
 2219        this.report_editor_event("open", None, cx);
 2220        this
 2221    }
 2222
 2223    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2224        self.mouse_context_menu
 2225            .as_ref()
 2226            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2227    }
 2228
 2229    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2230        let mut key_context = KeyContext::new_with_defaults();
 2231        key_context.add("Editor");
 2232        let mode = match self.mode {
 2233            EditorMode::SingleLine { .. } => "single_line",
 2234            EditorMode::AutoHeight { .. } => "auto_height",
 2235            EditorMode::Full => "full",
 2236        };
 2237
 2238        if EditorSettings::jupyter_enabled(cx) {
 2239            key_context.add("jupyter");
 2240        }
 2241
 2242        key_context.set("mode", mode);
 2243        if self.pending_rename.is_some() {
 2244            key_context.add("renaming");
 2245        }
 2246        if self.context_menu_visible() {
 2247            match self.context_menu.read().as_ref() {
 2248                Some(ContextMenu::Completions(_)) => {
 2249                    key_context.add("menu");
 2250                    key_context.add("showing_completions")
 2251                }
 2252                Some(ContextMenu::CodeActions(_)) => {
 2253                    key_context.add("menu");
 2254                    key_context.add("showing_code_actions")
 2255                }
 2256                None => {}
 2257            }
 2258        }
 2259
 2260        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2261        if !self.focus_handle(cx).contains_focused(cx)
 2262            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2263        {
 2264            for addon in self.addons.values() {
 2265                addon.extend_key_context(&mut key_context, cx)
 2266            }
 2267        }
 2268
 2269        if let Some(extension) = self
 2270            .buffer
 2271            .read(cx)
 2272            .as_singleton()
 2273            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2274        {
 2275            key_context.set("extension", extension.to_string());
 2276        }
 2277
 2278        if self.has_active_inline_completion(cx) {
 2279            key_context.add("copilot_suggestion");
 2280            key_context.add("inline_completion");
 2281        }
 2282
 2283        key_context
 2284    }
 2285
 2286    pub fn new_file(
 2287        workspace: &mut Workspace,
 2288        _: &workspace::NewFile,
 2289        cx: &mut ViewContext<Workspace>,
 2290    ) {
 2291        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2292            "Failed to create buffer",
 2293            cx,
 2294            |e, _| match e.error_code() {
 2295                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2296                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2297                e.error_tag("required").unwrap_or("the latest version")
 2298            )),
 2299                _ => None,
 2300            },
 2301        );
 2302    }
 2303
 2304    pub fn new_in_workspace(
 2305        workspace: &mut Workspace,
 2306        cx: &mut ViewContext<Workspace>,
 2307    ) -> Task<Result<View<Editor>>> {
 2308        let project = workspace.project().clone();
 2309        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2310
 2311        cx.spawn(|workspace, mut cx| async move {
 2312            let buffer = create.await?;
 2313            workspace.update(&mut cx, |workspace, cx| {
 2314                let editor =
 2315                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2316                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2317                editor
 2318            })
 2319        })
 2320    }
 2321
 2322    fn new_file_vertical(
 2323        workspace: &mut Workspace,
 2324        _: &workspace::NewFileSplitVertical,
 2325        cx: &mut ViewContext<Workspace>,
 2326    ) {
 2327        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2328    }
 2329
 2330    fn new_file_horizontal(
 2331        workspace: &mut Workspace,
 2332        _: &workspace::NewFileSplitHorizontal,
 2333        cx: &mut ViewContext<Workspace>,
 2334    ) {
 2335        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2336    }
 2337
 2338    fn new_file_in_direction(
 2339        workspace: &mut Workspace,
 2340        direction: SplitDirection,
 2341        cx: &mut ViewContext<Workspace>,
 2342    ) {
 2343        let project = workspace.project().clone();
 2344        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2345
 2346        cx.spawn(|workspace, mut cx| async move {
 2347            let buffer = create.await?;
 2348            workspace.update(&mut cx, move |workspace, cx| {
 2349                workspace.split_item(
 2350                    direction,
 2351                    Box::new(
 2352                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2353                    ),
 2354                    cx,
 2355                )
 2356            })?;
 2357            anyhow::Ok(())
 2358        })
 2359        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2360            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2361                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2362                e.error_tag("required").unwrap_or("the latest version")
 2363            )),
 2364            _ => None,
 2365        });
 2366    }
 2367
 2368    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2369        self.leader_peer_id
 2370    }
 2371
 2372    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2373        &self.buffer
 2374    }
 2375
 2376    pub fn workspace(&self) -> Option<View<Workspace>> {
 2377        self.workspace.as_ref()?.0.upgrade()
 2378    }
 2379
 2380    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2381        self.buffer().read(cx).title(cx)
 2382    }
 2383
 2384    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2385        let git_blame_gutter_max_author_length = self
 2386            .render_git_blame_gutter(cx)
 2387            .then(|| {
 2388                if let Some(blame) = self.blame.as_ref() {
 2389                    let max_author_length =
 2390                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2391                    Some(max_author_length)
 2392                } else {
 2393                    None
 2394                }
 2395            })
 2396            .flatten();
 2397
 2398        EditorSnapshot {
 2399            mode: self.mode,
 2400            show_gutter: self.show_gutter,
 2401            show_line_numbers: self.show_line_numbers,
 2402            show_git_diff_gutter: self.show_git_diff_gutter,
 2403            show_code_actions: self.show_code_actions,
 2404            show_runnables: self.show_runnables,
 2405            git_blame_gutter_max_author_length,
 2406            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2407            scroll_anchor: self.scroll_manager.anchor(),
 2408            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2409            placeholder_text: self.placeholder_text.clone(),
 2410            is_focused: self.focus_handle.is_focused(cx),
 2411            current_line_highlight: self
 2412                .current_line_highlight
 2413                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2414            gutter_hovered: self.gutter_hovered,
 2415        }
 2416    }
 2417
 2418    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2419        self.buffer.read(cx).language_at(point, cx)
 2420    }
 2421
 2422    pub fn file_at<T: ToOffset>(
 2423        &self,
 2424        point: T,
 2425        cx: &AppContext,
 2426    ) -> Option<Arc<dyn language::File>> {
 2427        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2428    }
 2429
 2430    pub fn active_excerpt(
 2431        &self,
 2432        cx: &AppContext,
 2433    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2434        self.buffer
 2435            .read(cx)
 2436            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2437    }
 2438
 2439    pub fn mode(&self) -> EditorMode {
 2440        self.mode
 2441    }
 2442
 2443    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2444        self.collaboration_hub.as_deref()
 2445    }
 2446
 2447    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2448        self.collaboration_hub = Some(hub);
 2449    }
 2450
 2451    pub fn set_custom_context_menu(
 2452        &mut self,
 2453        f: impl 'static
 2454            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2455    ) {
 2456        self.custom_context_menu = Some(Box::new(f))
 2457    }
 2458
 2459    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2460        self.completion_provider = provider;
 2461    }
 2462
 2463    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2464        self.semantics_provider.clone()
 2465    }
 2466
 2467    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2468        self.semantics_provider = provider;
 2469    }
 2470
 2471    pub fn set_inline_completion_provider<T>(
 2472        &mut self,
 2473        provider: Option<Model<T>>,
 2474        cx: &mut ViewContext<Self>,
 2475    ) where
 2476        T: InlineCompletionProvider,
 2477    {
 2478        self.inline_completion_provider =
 2479            provider.map(|provider| RegisteredInlineCompletionProvider {
 2480                _subscription: cx.observe(&provider, |this, _, cx| {
 2481                    if this.focus_handle.is_focused(cx) {
 2482                        this.update_visible_inline_completion(cx);
 2483                    }
 2484                }),
 2485                provider: Arc::new(provider),
 2486            });
 2487        self.refresh_inline_completion(false, false, cx);
 2488    }
 2489
 2490    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2491        self.placeholder_text.as_deref()
 2492    }
 2493
 2494    pub fn set_placeholder_text(
 2495        &mut self,
 2496        placeholder_text: impl Into<Arc<str>>,
 2497        cx: &mut ViewContext<Self>,
 2498    ) {
 2499        let placeholder_text = Some(placeholder_text.into());
 2500        if self.placeholder_text != placeholder_text {
 2501            self.placeholder_text = placeholder_text;
 2502            cx.notify();
 2503        }
 2504    }
 2505
 2506    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2507        self.cursor_shape = cursor_shape;
 2508
 2509        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2510        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2511
 2512        cx.notify();
 2513    }
 2514
 2515    pub fn set_current_line_highlight(
 2516        &mut self,
 2517        current_line_highlight: Option<CurrentLineHighlight>,
 2518    ) {
 2519        self.current_line_highlight = current_line_highlight;
 2520    }
 2521
 2522    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2523        self.collapse_matches = collapse_matches;
 2524    }
 2525
 2526    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2527        if self.collapse_matches {
 2528            return range.start..range.start;
 2529        }
 2530        range.clone()
 2531    }
 2532
 2533    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2534        if self.display_map.read(cx).clip_at_line_ends != clip {
 2535            self.display_map
 2536                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2537        }
 2538    }
 2539
 2540    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2541        self.input_enabled = input_enabled;
 2542    }
 2543
 2544    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2545        self.enable_inline_completions = enabled;
 2546    }
 2547
 2548    pub fn set_autoindent(&mut self, autoindent: bool) {
 2549        if autoindent {
 2550            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2551        } else {
 2552            self.autoindent_mode = None;
 2553        }
 2554    }
 2555
 2556    pub fn read_only(&self, cx: &AppContext) -> bool {
 2557        self.read_only || self.buffer.read(cx).read_only()
 2558    }
 2559
 2560    pub fn set_read_only(&mut self, read_only: bool) {
 2561        self.read_only = read_only;
 2562    }
 2563
 2564    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2565        self.use_autoclose = autoclose;
 2566    }
 2567
 2568    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2569        self.use_auto_surround = auto_surround;
 2570    }
 2571
 2572    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2573        self.auto_replace_emoji_shortcode = auto_replace;
 2574    }
 2575
 2576    pub fn toggle_inline_completions(
 2577        &mut self,
 2578        _: &ToggleInlineCompletions,
 2579        cx: &mut ViewContext<Self>,
 2580    ) {
 2581        if self.show_inline_completions_override.is_some() {
 2582            self.set_show_inline_completions(None, cx);
 2583        } else {
 2584            let cursor = self.selections.newest_anchor().head();
 2585            if let Some((buffer, cursor_buffer_position)) =
 2586                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2587            {
 2588                let show_inline_completions =
 2589                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2590                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2591            }
 2592        }
 2593    }
 2594
 2595    pub fn set_show_inline_completions(
 2596        &mut self,
 2597        show_inline_completions: Option<bool>,
 2598        cx: &mut ViewContext<Self>,
 2599    ) {
 2600        self.show_inline_completions_override = show_inline_completions;
 2601        self.refresh_inline_completion(false, true, cx);
 2602    }
 2603
 2604    fn should_show_inline_completions(
 2605        &self,
 2606        buffer: &Model<Buffer>,
 2607        buffer_position: language::Anchor,
 2608        cx: &AppContext,
 2609    ) -> bool {
 2610        if !self.snippet_stack.is_empty() {
 2611            return false;
 2612        }
 2613
 2614        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2615            return false;
 2616        }
 2617
 2618        if let Some(provider) = self.inline_completion_provider() {
 2619            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2620                show_inline_completions
 2621            } else {
 2622                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2623            }
 2624        } else {
 2625            false
 2626        }
 2627    }
 2628
 2629    fn inline_completions_disabled_in_scope(
 2630        &self,
 2631        buffer: &Model<Buffer>,
 2632        buffer_position: language::Anchor,
 2633        cx: &AppContext,
 2634    ) -> bool {
 2635        let snapshot = buffer.read(cx).snapshot();
 2636        let settings = snapshot.settings_at(buffer_position, cx);
 2637
 2638        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2639            return false;
 2640        };
 2641
 2642        scope.override_name().map_or(false, |scope_name| {
 2643            settings
 2644                .inline_completions_disabled_in
 2645                .iter()
 2646                .any(|s| s == scope_name)
 2647        })
 2648    }
 2649
 2650    pub fn set_use_modal_editing(&mut self, to: bool) {
 2651        self.use_modal_editing = to;
 2652    }
 2653
 2654    pub fn use_modal_editing(&self) -> bool {
 2655        self.use_modal_editing
 2656    }
 2657
 2658    fn selections_did_change(
 2659        &mut self,
 2660        local: bool,
 2661        old_cursor_position: &Anchor,
 2662        show_completions: bool,
 2663        cx: &mut ViewContext<Self>,
 2664    ) {
 2665        cx.invalidate_character_coordinates();
 2666
 2667        // Copy selections to primary selection buffer
 2668        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2669        if local {
 2670            let selections = self.selections.all::<usize>(cx);
 2671            let buffer_handle = self.buffer.read(cx).read(cx);
 2672
 2673            let mut text = String::new();
 2674            for (index, selection) in selections.iter().enumerate() {
 2675                let text_for_selection = buffer_handle
 2676                    .text_for_range(selection.start..selection.end)
 2677                    .collect::<String>();
 2678
 2679                text.push_str(&text_for_selection);
 2680                if index != selections.len() - 1 {
 2681                    text.push('\n');
 2682                }
 2683            }
 2684
 2685            if !text.is_empty() {
 2686                cx.write_to_primary(ClipboardItem::new_string(text));
 2687            }
 2688        }
 2689
 2690        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2691            self.buffer.update(cx, |buffer, cx| {
 2692                buffer.set_active_selections(
 2693                    &self.selections.disjoint_anchors(),
 2694                    self.selections.line_mode,
 2695                    self.cursor_shape,
 2696                    cx,
 2697                )
 2698            });
 2699        }
 2700        let display_map = self
 2701            .display_map
 2702            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2703        let buffer = &display_map.buffer_snapshot;
 2704        self.add_selections_state = None;
 2705        self.select_next_state = None;
 2706        self.select_prev_state = None;
 2707        self.select_larger_syntax_node_stack.clear();
 2708        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2709        self.snippet_stack
 2710            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2711        self.take_rename(false, cx);
 2712
 2713        let new_cursor_position = self.selections.newest_anchor().head();
 2714
 2715        self.push_to_nav_history(
 2716            *old_cursor_position,
 2717            Some(new_cursor_position.to_point(buffer)),
 2718            cx,
 2719        );
 2720
 2721        if local {
 2722            let new_cursor_position = self.selections.newest_anchor().head();
 2723            let mut context_menu = self.context_menu.write();
 2724            let completion_menu = match context_menu.as_ref() {
 2725                Some(ContextMenu::Completions(menu)) => Some(menu),
 2726
 2727                _ => {
 2728                    *context_menu = None;
 2729                    None
 2730                }
 2731            };
 2732
 2733            if let Some(completion_menu) = completion_menu {
 2734                let cursor_position = new_cursor_position.to_offset(buffer);
 2735                let (word_range, kind) =
 2736                    buffer.surrounding_word(completion_menu.initial_position, true);
 2737                if kind == Some(CharKind::Word)
 2738                    && word_range.to_inclusive().contains(&cursor_position)
 2739                {
 2740                    let mut completion_menu = completion_menu.clone();
 2741                    drop(context_menu);
 2742
 2743                    let query = Self::completion_query(buffer, cursor_position);
 2744                    cx.spawn(move |this, mut cx| async move {
 2745                        completion_menu
 2746                            .filter(query.as_deref(), cx.background_executor().clone())
 2747                            .await;
 2748
 2749                        this.update(&mut cx, |this, cx| {
 2750                            let mut context_menu = this.context_menu.write();
 2751                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2752                                return;
 2753                            };
 2754
 2755                            if menu.id > completion_menu.id {
 2756                                return;
 2757                            }
 2758
 2759                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2760                            drop(context_menu);
 2761                            cx.notify();
 2762                        })
 2763                    })
 2764                    .detach();
 2765
 2766                    if show_completions {
 2767                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2768                    }
 2769                } else {
 2770                    drop(context_menu);
 2771                    self.hide_context_menu(cx);
 2772                }
 2773            } else {
 2774                drop(context_menu);
 2775            }
 2776
 2777            hide_hover(self, cx);
 2778
 2779            if old_cursor_position.to_display_point(&display_map).row()
 2780                != new_cursor_position.to_display_point(&display_map).row()
 2781            {
 2782                self.available_code_actions.take();
 2783            }
 2784            self.refresh_code_actions(cx);
 2785            self.refresh_document_highlights(cx);
 2786            refresh_matching_bracket_highlights(self, cx);
 2787            self.discard_inline_completion(false, cx);
 2788            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2789            if self.git_blame_inline_enabled {
 2790                self.start_inline_blame_timer(cx);
 2791            }
 2792        }
 2793
 2794        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2795        cx.emit(EditorEvent::SelectionsChanged { local });
 2796
 2797        if self.selections.disjoint_anchors().len() == 1 {
 2798            cx.emit(SearchEvent::ActiveMatchChanged)
 2799        }
 2800        cx.notify();
 2801    }
 2802
 2803    pub fn change_selections<R>(
 2804        &mut self,
 2805        autoscroll: Option<Autoscroll>,
 2806        cx: &mut ViewContext<Self>,
 2807        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2808    ) -> R {
 2809        self.change_selections_inner(autoscroll, true, cx, change)
 2810    }
 2811
 2812    pub fn change_selections_inner<R>(
 2813        &mut self,
 2814        autoscroll: Option<Autoscroll>,
 2815        request_completions: bool,
 2816        cx: &mut ViewContext<Self>,
 2817        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2818    ) -> R {
 2819        let old_cursor_position = self.selections.newest_anchor().head();
 2820        self.push_to_selection_history();
 2821
 2822        let (changed, result) = self.selections.change_with(cx, change);
 2823
 2824        if changed {
 2825            if let Some(autoscroll) = autoscroll {
 2826                self.request_autoscroll(autoscroll, cx);
 2827            }
 2828            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2829
 2830            if self.should_open_signature_help_automatically(
 2831                &old_cursor_position,
 2832                self.signature_help_state.backspace_pressed(),
 2833                cx,
 2834            ) {
 2835                self.show_signature_help(&ShowSignatureHelp, cx);
 2836            }
 2837            self.signature_help_state.set_backspace_pressed(false);
 2838        }
 2839
 2840        result
 2841    }
 2842
 2843    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2844    where
 2845        I: IntoIterator<Item = (Range<S>, T)>,
 2846        S: ToOffset,
 2847        T: Into<Arc<str>>,
 2848    {
 2849        if self.read_only(cx) {
 2850            return;
 2851        }
 2852
 2853        self.buffer
 2854            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2855    }
 2856
 2857    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2858    where
 2859        I: IntoIterator<Item = (Range<S>, T)>,
 2860        S: ToOffset,
 2861        T: Into<Arc<str>>,
 2862    {
 2863        if self.read_only(cx) {
 2864            return;
 2865        }
 2866
 2867        self.buffer.update(cx, |buffer, cx| {
 2868            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2869        });
 2870    }
 2871
 2872    pub fn edit_with_block_indent<I, S, T>(
 2873        &mut self,
 2874        edits: I,
 2875        original_indent_columns: Vec<u32>,
 2876        cx: &mut ViewContext<Self>,
 2877    ) where
 2878        I: IntoIterator<Item = (Range<S>, T)>,
 2879        S: ToOffset,
 2880        T: Into<Arc<str>>,
 2881    {
 2882        if self.read_only(cx) {
 2883            return;
 2884        }
 2885
 2886        self.buffer.update(cx, |buffer, cx| {
 2887            buffer.edit(
 2888                edits,
 2889                Some(AutoindentMode::Block {
 2890                    original_indent_columns,
 2891                }),
 2892                cx,
 2893            )
 2894        });
 2895    }
 2896
 2897    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2898        self.hide_context_menu(cx);
 2899
 2900        match phase {
 2901            SelectPhase::Begin {
 2902                position,
 2903                add,
 2904                click_count,
 2905            } => self.begin_selection(position, add, click_count, cx),
 2906            SelectPhase::BeginColumnar {
 2907                position,
 2908                goal_column,
 2909                reset,
 2910            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2911            SelectPhase::Extend {
 2912                position,
 2913                click_count,
 2914            } => self.extend_selection(position, click_count, cx),
 2915            SelectPhase::Update {
 2916                position,
 2917                goal_column,
 2918                scroll_delta,
 2919            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2920            SelectPhase::End => self.end_selection(cx),
 2921        }
 2922    }
 2923
 2924    fn extend_selection(
 2925        &mut self,
 2926        position: DisplayPoint,
 2927        click_count: usize,
 2928        cx: &mut ViewContext<Self>,
 2929    ) {
 2930        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2931        let tail = self.selections.newest::<usize>(cx).tail();
 2932        self.begin_selection(position, false, click_count, cx);
 2933
 2934        let position = position.to_offset(&display_map, Bias::Left);
 2935        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2936
 2937        let mut pending_selection = self
 2938            .selections
 2939            .pending_anchor()
 2940            .expect("extend_selection not called with pending selection");
 2941        if position >= tail {
 2942            pending_selection.start = tail_anchor;
 2943        } else {
 2944            pending_selection.end = tail_anchor;
 2945            pending_selection.reversed = true;
 2946        }
 2947
 2948        let mut pending_mode = self.selections.pending_mode().unwrap();
 2949        match &mut pending_mode {
 2950            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2951            _ => {}
 2952        }
 2953
 2954        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2955            s.set_pending(pending_selection, pending_mode)
 2956        });
 2957    }
 2958
 2959    fn begin_selection(
 2960        &mut self,
 2961        position: DisplayPoint,
 2962        add: bool,
 2963        click_count: usize,
 2964        cx: &mut ViewContext<Self>,
 2965    ) {
 2966        if !self.focus_handle.is_focused(cx) {
 2967            self.last_focused_descendant = None;
 2968            cx.focus(&self.focus_handle);
 2969        }
 2970
 2971        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2972        let buffer = &display_map.buffer_snapshot;
 2973        let newest_selection = self.selections.newest_anchor().clone();
 2974        let position = display_map.clip_point(position, Bias::Left);
 2975
 2976        let start;
 2977        let end;
 2978        let mode;
 2979        let auto_scroll;
 2980        match click_count {
 2981            1 => {
 2982                start = buffer.anchor_before(position.to_point(&display_map));
 2983                end = start;
 2984                mode = SelectMode::Character;
 2985                auto_scroll = true;
 2986            }
 2987            2 => {
 2988                let range = movement::surrounding_word(&display_map, position);
 2989                start = buffer.anchor_before(range.start.to_point(&display_map));
 2990                end = buffer.anchor_before(range.end.to_point(&display_map));
 2991                mode = SelectMode::Word(start..end);
 2992                auto_scroll = true;
 2993            }
 2994            3 => {
 2995                let position = display_map
 2996                    .clip_point(position, Bias::Left)
 2997                    .to_point(&display_map);
 2998                let line_start = display_map.prev_line_boundary(position).0;
 2999                let next_line_start = buffer.clip_point(
 3000                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3001                    Bias::Left,
 3002                );
 3003                start = buffer.anchor_before(line_start);
 3004                end = buffer.anchor_before(next_line_start);
 3005                mode = SelectMode::Line(start..end);
 3006                auto_scroll = true;
 3007            }
 3008            _ => {
 3009                start = buffer.anchor_before(0);
 3010                end = buffer.anchor_before(buffer.len());
 3011                mode = SelectMode::All;
 3012                auto_scroll = false;
 3013            }
 3014        }
 3015
 3016        let point_to_delete: Option<usize> = {
 3017            let selected_points: Vec<Selection<Point>> =
 3018                self.selections.disjoint_in_range(start..end, cx);
 3019
 3020            if !add || click_count > 1 {
 3021                None
 3022            } else if !selected_points.is_empty() {
 3023                Some(selected_points[0].id)
 3024            } else {
 3025                let clicked_point_already_selected =
 3026                    self.selections.disjoint.iter().find(|selection| {
 3027                        selection.start.to_point(buffer) == start.to_point(buffer)
 3028                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3029                    });
 3030
 3031                clicked_point_already_selected.map(|selection| selection.id)
 3032            }
 3033        };
 3034
 3035        let selections_count = self.selections.count();
 3036
 3037        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 3038            if let Some(point_to_delete) = point_to_delete {
 3039                s.delete(point_to_delete);
 3040
 3041                if selections_count == 1 {
 3042                    s.set_pending_anchor_range(start..end, mode);
 3043                }
 3044            } else {
 3045                if !add {
 3046                    s.clear_disjoint();
 3047                } else if click_count > 1 {
 3048                    s.delete(newest_selection.id)
 3049                }
 3050
 3051                s.set_pending_anchor_range(start..end, mode);
 3052            }
 3053        });
 3054    }
 3055
 3056    fn begin_columnar_selection(
 3057        &mut self,
 3058        position: DisplayPoint,
 3059        goal_column: u32,
 3060        reset: bool,
 3061        cx: &mut ViewContext<Self>,
 3062    ) {
 3063        if !self.focus_handle.is_focused(cx) {
 3064            self.last_focused_descendant = None;
 3065            cx.focus(&self.focus_handle);
 3066        }
 3067
 3068        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3069
 3070        if reset {
 3071            let pointer_position = display_map
 3072                .buffer_snapshot
 3073                .anchor_before(position.to_point(&display_map));
 3074
 3075            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 3076                s.clear_disjoint();
 3077                s.set_pending_anchor_range(
 3078                    pointer_position..pointer_position,
 3079                    SelectMode::Character,
 3080                );
 3081            });
 3082        }
 3083
 3084        let tail = self.selections.newest::<Point>(cx).tail();
 3085        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3086
 3087        if !reset {
 3088            self.select_columns(
 3089                tail.to_display_point(&display_map),
 3090                position,
 3091                goal_column,
 3092                &display_map,
 3093                cx,
 3094            );
 3095        }
 3096    }
 3097
 3098    fn update_selection(
 3099        &mut self,
 3100        position: DisplayPoint,
 3101        goal_column: u32,
 3102        scroll_delta: gpui::Point<f32>,
 3103        cx: &mut ViewContext<Self>,
 3104    ) {
 3105        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3106
 3107        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3108            let tail = tail.to_display_point(&display_map);
 3109            self.select_columns(tail, position, goal_column, &display_map, cx);
 3110        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3111            let buffer = self.buffer.read(cx).snapshot(cx);
 3112            let head;
 3113            let tail;
 3114            let mode = self.selections.pending_mode().unwrap();
 3115            match &mode {
 3116                SelectMode::Character => {
 3117                    head = position.to_point(&display_map);
 3118                    tail = pending.tail().to_point(&buffer);
 3119                }
 3120                SelectMode::Word(original_range) => {
 3121                    let original_display_range = original_range.start.to_display_point(&display_map)
 3122                        ..original_range.end.to_display_point(&display_map);
 3123                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3124                        ..original_display_range.end.to_point(&display_map);
 3125                    if movement::is_inside_word(&display_map, position)
 3126                        || original_display_range.contains(&position)
 3127                    {
 3128                        let word_range = movement::surrounding_word(&display_map, position);
 3129                        if word_range.start < original_display_range.start {
 3130                            head = word_range.start.to_point(&display_map);
 3131                        } else {
 3132                            head = word_range.end.to_point(&display_map);
 3133                        }
 3134                    } else {
 3135                        head = position.to_point(&display_map);
 3136                    }
 3137
 3138                    if head <= original_buffer_range.start {
 3139                        tail = original_buffer_range.end;
 3140                    } else {
 3141                        tail = original_buffer_range.start;
 3142                    }
 3143                }
 3144                SelectMode::Line(original_range) => {
 3145                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3146
 3147                    let position = display_map
 3148                        .clip_point(position, Bias::Left)
 3149                        .to_point(&display_map);
 3150                    let line_start = display_map.prev_line_boundary(position).0;
 3151                    let next_line_start = buffer.clip_point(
 3152                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3153                        Bias::Left,
 3154                    );
 3155
 3156                    if line_start < original_range.start {
 3157                        head = line_start
 3158                    } else {
 3159                        head = next_line_start
 3160                    }
 3161
 3162                    if head <= original_range.start {
 3163                        tail = original_range.end;
 3164                    } else {
 3165                        tail = original_range.start;
 3166                    }
 3167                }
 3168                SelectMode::All => {
 3169                    return;
 3170                }
 3171            };
 3172
 3173            if head < tail {
 3174                pending.start = buffer.anchor_before(head);
 3175                pending.end = buffer.anchor_before(tail);
 3176                pending.reversed = true;
 3177            } else {
 3178                pending.start = buffer.anchor_before(tail);
 3179                pending.end = buffer.anchor_before(head);
 3180                pending.reversed = false;
 3181            }
 3182
 3183            self.change_selections(None, cx, |s| {
 3184                s.set_pending(pending, mode);
 3185            });
 3186        } else {
 3187            log::error!("update_selection dispatched with no pending selection");
 3188            return;
 3189        }
 3190
 3191        self.apply_scroll_delta(scroll_delta, cx);
 3192        cx.notify();
 3193    }
 3194
 3195    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3196        self.columnar_selection_tail.take();
 3197        if self.selections.pending_anchor().is_some() {
 3198            let selections = self.selections.all::<usize>(cx);
 3199            self.change_selections(None, cx, |s| {
 3200                s.select(selections);
 3201                s.clear_pending();
 3202            });
 3203        }
 3204    }
 3205
 3206    fn select_columns(
 3207        &mut self,
 3208        tail: DisplayPoint,
 3209        head: DisplayPoint,
 3210        goal_column: u32,
 3211        display_map: &DisplaySnapshot,
 3212        cx: &mut ViewContext<Self>,
 3213    ) {
 3214        let start_row = cmp::min(tail.row(), head.row());
 3215        let end_row = cmp::max(tail.row(), head.row());
 3216        let start_column = cmp::min(tail.column(), goal_column);
 3217        let end_column = cmp::max(tail.column(), goal_column);
 3218        let reversed = start_column < tail.column();
 3219
 3220        let selection_ranges = (start_row.0..=end_row.0)
 3221            .map(DisplayRow)
 3222            .filter_map(|row| {
 3223                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3224                    let start = display_map
 3225                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3226                        .to_point(display_map);
 3227                    let end = display_map
 3228                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3229                        .to_point(display_map);
 3230                    if reversed {
 3231                        Some(end..start)
 3232                    } else {
 3233                        Some(start..end)
 3234                    }
 3235                } else {
 3236                    None
 3237                }
 3238            })
 3239            .collect::<Vec<_>>();
 3240
 3241        self.change_selections(None, cx, |s| {
 3242            s.select_ranges(selection_ranges);
 3243        });
 3244        cx.notify();
 3245    }
 3246
 3247    pub fn has_pending_nonempty_selection(&self) -> bool {
 3248        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3249            Some(Selection { start, end, .. }) => start != end,
 3250            None => false,
 3251        };
 3252
 3253        pending_nonempty_selection
 3254            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3255    }
 3256
 3257    pub fn has_pending_selection(&self) -> bool {
 3258        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3259    }
 3260
 3261    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3262        if self.clear_expanded_diff_hunks(cx) {
 3263            cx.notify();
 3264            return;
 3265        }
 3266        if self.dismiss_menus_and_popups(true, cx) {
 3267            return;
 3268        }
 3269
 3270        if self.mode == EditorMode::Full
 3271            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3272        {
 3273            return;
 3274        }
 3275
 3276        cx.propagate();
 3277    }
 3278
 3279    pub fn dismiss_menus_and_popups(
 3280        &mut self,
 3281        should_report_inline_completion_event: bool,
 3282        cx: &mut ViewContext<Self>,
 3283    ) -> bool {
 3284        if self.take_rename(false, cx).is_some() {
 3285            return true;
 3286        }
 3287
 3288        if hide_hover(self, cx) {
 3289            return true;
 3290        }
 3291
 3292        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3293            return true;
 3294        }
 3295
 3296        if self.hide_context_menu(cx).is_some() {
 3297            return true;
 3298        }
 3299
 3300        if self.mouse_context_menu.take().is_some() {
 3301            return true;
 3302        }
 3303
 3304        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3305            return true;
 3306        }
 3307
 3308        if self.snippet_stack.pop().is_some() {
 3309            return true;
 3310        }
 3311
 3312        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3313            self.dismiss_diagnostics(cx);
 3314            return true;
 3315        }
 3316
 3317        false
 3318    }
 3319
 3320    fn linked_editing_ranges_for(
 3321        &self,
 3322        selection: Range<text::Anchor>,
 3323        cx: &AppContext,
 3324    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3325        if self.linked_edit_ranges.is_empty() {
 3326            return None;
 3327        }
 3328        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3329            selection.end.buffer_id.and_then(|end_buffer_id| {
 3330                if selection.start.buffer_id != Some(end_buffer_id) {
 3331                    return None;
 3332                }
 3333                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3334                let snapshot = buffer.read(cx).snapshot();
 3335                self.linked_edit_ranges
 3336                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3337                    .map(|ranges| (ranges, snapshot, buffer))
 3338            })?;
 3339        use text::ToOffset as TO;
 3340        // find offset from the start of current range to current cursor position
 3341        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3342
 3343        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3344        let start_difference = start_offset - start_byte_offset;
 3345        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3346        let end_difference = end_offset - start_byte_offset;
 3347        // Current range has associated linked ranges.
 3348        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3349        for range in linked_ranges.iter() {
 3350            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3351            let end_offset = start_offset + end_difference;
 3352            let start_offset = start_offset + start_difference;
 3353            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3354                continue;
 3355            }
 3356            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3357                if s.start.buffer_id != selection.start.buffer_id
 3358                    || s.end.buffer_id != selection.end.buffer_id
 3359                {
 3360                    return false;
 3361                }
 3362                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3363                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3364            }) {
 3365                continue;
 3366            }
 3367            let start = buffer_snapshot.anchor_after(start_offset);
 3368            let end = buffer_snapshot.anchor_after(end_offset);
 3369            linked_edits
 3370                .entry(buffer.clone())
 3371                .or_default()
 3372                .push(start..end);
 3373        }
 3374        Some(linked_edits)
 3375    }
 3376
 3377    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3378        let text: Arc<str> = text.into();
 3379
 3380        if self.read_only(cx) {
 3381            return;
 3382        }
 3383
 3384        let selections = self.selections.all_adjusted(cx);
 3385        let mut bracket_inserted = false;
 3386        let mut edits = Vec::new();
 3387        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3388        let mut new_selections = Vec::with_capacity(selections.len());
 3389        let mut new_autoclose_regions = Vec::new();
 3390        let snapshot = self.buffer.read(cx).read(cx);
 3391
 3392        for (selection, autoclose_region) in
 3393            self.selections_with_autoclose_regions(selections, &snapshot)
 3394        {
 3395            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3396                // Determine if the inserted text matches the opening or closing
 3397                // bracket of any of this language's bracket pairs.
 3398                let mut bracket_pair = None;
 3399                let mut is_bracket_pair_start = false;
 3400                let mut is_bracket_pair_end = false;
 3401                if !text.is_empty() {
 3402                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3403                    //  and they are removing the character that triggered IME popup.
 3404                    for (pair, enabled) in scope.brackets() {
 3405                        if !pair.close && !pair.surround {
 3406                            continue;
 3407                        }
 3408
 3409                        if enabled && pair.start.ends_with(text.as_ref()) {
 3410                            let prefix_len = pair.start.len() - text.len();
 3411                            let preceding_text_matches_prefix = prefix_len == 0
 3412                                || (selection.start.column >= (prefix_len as u32)
 3413                                    && snapshot.contains_str_at(
 3414                                        Point::new(
 3415                                            selection.start.row,
 3416                                            selection.start.column - (prefix_len as u32),
 3417                                        ),
 3418                                        &pair.start[..prefix_len],
 3419                                    ));
 3420                            if preceding_text_matches_prefix {
 3421                                bracket_pair = Some(pair.clone());
 3422                                is_bracket_pair_start = true;
 3423                                break;
 3424                            }
 3425                        }
 3426                        if pair.end.as_str() == text.as_ref() {
 3427                            bracket_pair = Some(pair.clone());
 3428                            is_bracket_pair_end = true;
 3429                            break;
 3430                        }
 3431                    }
 3432                }
 3433
 3434                if let Some(bracket_pair) = bracket_pair {
 3435                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3436                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3437                    let auto_surround =
 3438                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3439                    if selection.is_empty() {
 3440                        if is_bracket_pair_start {
 3441                            // If the inserted text is a suffix of an opening bracket and the
 3442                            // selection is preceded by the rest of the opening bracket, then
 3443                            // insert the closing bracket.
 3444                            let following_text_allows_autoclose = snapshot
 3445                                .chars_at(selection.start)
 3446                                .next()
 3447                                .map_or(true, |c| scope.should_autoclose_before(c));
 3448
 3449                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3450                                && bracket_pair.start.len() == 1
 3451                            {
 3452                                let target = bracket_pair.start.chars().next().unwrap();
 3453                                let current_line_count = snapshot
 3454                                    .reversed_chars_at(selection.start)
 3455                                    .take_while(|&c| c != '\n')
 3456                                    .filter(|&c| c == target)
 3457                                    .count();
 3458                                current_line_count % 2 == 1
 3459                            } else {
 3460                                false
 3461                            };
 3462
 3463                            if autoclose
 3464                                && bracket_pair.close
 3465                                && following_text_allows_autoclose
 3466                                && !is_closing_quote
 3467                            {
 3468                                let anchor = snapshot.anchor_before(selection.end);
 3469                                new_selections.push((selection.map(|_| anchor), text.len()));
 3470                                new_autoclose_regions.push((
 3471                                    anchor,
 3472                                    text.len(),
 3473                                    selection.id,
 3474                                    bracket_pair.clone(),
 3475                                ));
 3476                                edits.push((
 3477                                    selection.range(),
 3478                                    format!("{}{}", text, bracket_pair.end).into(),
 3479                                ));
 3480                                bracket_inserted = true;
 3481                                continue;
 3482                            }
 3483                        }
 3484
 3485                        if let Some(region) = autoclose_region {
 3486                            // If the selection is followed by an auto-inserted closing bracket,
 3487                            // then don't insert that closing bracket again; just move the selection
 3488                            // past the closing bracket.
 3489                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3490                                && text.as_ref() == region.pair.end.as_str();
 3491                            if should_skip {
 3492                                let anchor = snapshot.anchor_after(selection.end);
 3493                                new_selections
 3494                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3495                                continue;
 3496                            }
 3497                        }
 3498
 3499                        let always_treat_brackets_as_autoclosed = snapshot
 3500                            .settings_at(selection.start, cx)
 3501                            .always_treat_brackets_as_autoclosed;
 3502                        if always_treat_brackets_as_autoclosed
 3503                            && is_bracket_pair_end
 3504                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3505                        {
 3506                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3507                            // and the inserted text is a closing bracket and the selection is followed
 3508                            // by the closing bracket then move the selection past the closing bracket.
 3509                            let anchor = snapshot.anchor_after(selection.end);
 3510                            new_selections.push((selection.map(|_| anchor), text.len()));
 3511                            continue;
 3512                        }
 3513                    }
 3514                    // If an opening bracket is 1 character long and is typed while
 3515                    // text is selected, then surround that text with the bracket pair.
 3516                    else if auto_surround
 3517                        && bracket_pair.surround
 3518                        && is_bracket_pair_start
 3519                        && bracket_pair.start.chars().count() == 1
 3520                    {
 3521                        edits.push((selection.start..selection.start, text.clone()));
 3522                        edits.push((
 3523                            selection.end..selection.end,
 3524                            bracket_pair.end.as_str().into(),
 3525                        ));
 3526                        bracket_inserted = true;
 3527                        new_selections.push((
 3528                            Selection {
 3529                                id: selection.id,
 3530                                start: snapshot.anchor_after(selection.start),
 3531                                end: snapshot.anchor_before(selection.end),
 3532                                reversed: selection.reversed,
 3533                                goal: selection.goal,
 3534                            },
 3535                            0,
 3536                        ));
 3537                        continue;
 3538                    }
 3539                }
 3540            }
 3541
 3542            if self.auto_replace_emoji_shortcode
 3543                && selection.is_empty()
 3544                && text.as_ref().ends_with(':')
 3545            {
 3546                if let Some(possible_emoji_short_code) =
 3547                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3548                {
 3549                    if !possible_emoji_short_code.is_empty() {
 3550                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3551                            let emoji_shortcode_start = Point::new(
 3552                                selection.start.row,
 3553                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3554                            );
 3555
 3556                            // Remove shortcode from buffer
 3557                            edits.push((
 3558                                emoji_shortcode_start..selection.start,
 3559                                "".to_string().into(),
 3560                            ));
 3561                            new_selections.push((
 3562                                Selection {
 3563                                    id: selection.id,
 3564                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3565                                    end: snapshot.anchor_before(selection.start),
 3566                                    reversed: selection.reversed,
 3567                                    goal: selection.goal,
 3568                                },
 3569                                0,
 3570                            ));
 3571
 3572                            // Insert emoji
 3573                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3574                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3575                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3576
 3577                            continue;
 3578                        }
 3579                    }
 3580                }
 3581            }
 3582
 3583            // If not handling any auto-close operation, then just replace the selected
 3584            // text with the given input and move the selection to the end of the
 3585            // newly inserted text.
 3586            let anchor = snapshot.anchor_after(selection.end);
 3587            if !self.linked_edit_ranges.is_empty() {
 3588                let start_anchor = snapshot.anchor_before(selection.start);
 3589
 3590                let is_word_char = text.chars().next().map_or(true, |char| {
 3591                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3592                    classifier.is_word(char)
 3593                });
 3594
 3595                if is_word_char {
 3596                    if let Some(ranges) = self
 3597                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3598                    {
 3599                        for (buffer, edits) in ranges {
 3600                            linked_edits
 3601                                .entry(buffer.clone())
 3602                                .or_default()
 3603                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3604                        }
 3605                    }
 3606                }
 3607            }
 3608
 3609            new_selections.push((selection.map(|_| anchor), 0));
 3610            edits.push((selection.start..selection.end, text.clone()));
 3611        }
 3612
 3613        drop(snapshot);
 3614
 3615        self.transact(cx, |this, cx| {
 3616            this.buffer.update(cx, |buffer, cx| {
 3617                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3618            });
 3619            for (buffer, edits) in linked_edits {
 3620                buffer.update(cx, |buffer, cx| {
 3621                    let snapshot = buffer.snapshot();
 3622                    let edits = edits
 3623                        .into_iter()
 3624                        .map(|(range, text)| {
 3625                            use text::ToPoint as TP;
 3626                            let end_point = TP::to_point(&range.end, &snapshot);
 3627                            let start_point = TP::to_point(&range.start, &snapshot);
 3628                            (start_point..end_point, text)
 3629                        })
 3630                        .sorted_by_key(|(range, _)| range.start)
 3631                        .collect::<Vec<_>>();
 3632                    buffer.edit(edits, None, cx);
 3633                })
 3634            }
 3635            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3636            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3637            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3638            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3639                .zip(new_selection_deltas)
 3640                .map(|(selection, delta)| Selection {
 3641                    id: selection.id,
 3642                    start: selection.start + delta,
 3643                    end: selection.end + delta,
 3644                    reversed: selection.reversed,
 3645                    goal: SelectionGoal::None,
 3646                })
 3647                .collect::<Vec<_>>();
 3648
 3649            let mut i = 0;
 3650            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3651                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3652                let start = map.buffer_snapshot.anchor_before(position);
 3653                let end = map.buffer_snapshot.anchor_after(position);
 3654                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3655                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3656                        Ordering::Less => i += 1,
 3657                        Ordering::Greater => break,
 3658                        Ordering::Equal => {
 3659                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3660                                Ordering::Less => i += 1,
 3661                                Ordering::Equal => break,
 3662                                Ordering::Greater => break,
 3663                            }
 3664                        }
 3665                    }
 3666                }
 3667                this.autoclose_regions.insert(
 3668                    i,
 3669                    AutocloseRegion {
 3670                        selection_id,
 3671                        range: start..end,
 3672                        pair,
 3673                    },
 3674                );
 3675            }
 3676
 3677            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3678            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3679                s.select(new_selections)
 3680            });
 3681
 3682            if !bracket_inserted {
 3683                if let Some(on_type_format_task) =
 3684                    this.trigger_on_type_formatting(text.to_string(), cx)
 3685                {
 3686                    on_type_format_task.detach_and_log_err(cx);
 3687                }
 3688            }
 3689
 3690            let editor_settings = EditorSettings::get_global(cx);
 3691            if bracket_inserted
 3692                && (editor_settings.auto_signature_help
 3693                    || editor_settings.show_signature_help_after_edits)
 3694            {
 3695                this.show_signature_help(&ShowSignatureHelp, cx);
 3696            }
 3697
 3698            let trigger_in_words = !had_active_inline_completion;
 3699            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3700            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3701            this.refresh_inline_completion(true, false, cx);
 3702        });
 3703    }
 3704
 3705    fn find_possible_emoji_shortcode_at_position(
 3706        snapshot: &MultiBufferSnapshot,
 3707        position: Point,
 3708    ) -> Option<String> {
 3709        let mut chars = Vec::new();
 3710        let mut found_colon = false;
 3711        for char in snapshot.reversed_chars_at(position).take(100) {
 3712            // Found a possible emoji shortcode in the middle of the buffer
 3713            if found_colon {
 3714                if char.is_whitespace() {
 3715                    chars.reverse();
 3716                    return Some(chars.iter().collect());
 3717                }
 3718                // If the previous character is not a whitespace, we are in the middle of a word
 3719                // and we only want to complete the shortcode if the word is made up of other emojis
 3720                let mut containing_word = String::new();
 3721                for ch in snapshot
 3722                    .reversed_chars_at(position)
 3723                    .skip(chars.len() + 1)
 3724                    .take(100)
 3725                {
 3726                    if ch.is_whitespace() {
 3727                        break;
 3728                    }
 3729                    containing_word.push(ch);
 3730                }
 3731                let containing_word = containing_word.chars().rev().collect::<String>();
 3732                if util::word_consists_of_emojis(containing_word.as_str()) {
 3733                    chars.reverse();
 3734                    return Some(chars.iter().collect());
 3735                }
 3736            }
 3737
 3738            if char.is_whitespace() || !char.is_ascii() {
 3739                return None;
 3740            }
 3741            if char == ':' {
 3742                found_colon = true;
 3743            } else {
 3744                chars.push(char);
 3745            }
 3746        }
 3747        // Found a possible emoji shortcode at the beginning of the buffer
 3748        chars.reverse();
 3749        Some(chars.iter().collect())
 3750    }
 3751
 3752    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3753        self.transact(cx, |this, cx| {
 3754            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3755                let selections = this.selections.all::<usize>(cx);
 3756                let multi_buffer = this.buffer.read(cx);
 3757                let buffer = multi_buffer.snapshot(cx);
 3758                selections
 3759                    .iter()
 3760                    .map(|selection| {
 3761                        let start_point = selection.start.to_point(&buffer);
 3762                        let mut indent =
 3763                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3764                        indent.len = cmp::min(indent.len, start_point.column);
 3765                        let start = selection.start;
 3766                        let end = selection.end;
 3767                        let selection_is_empty = start == end;
 3768                        let language_scope = buffer.language_scope_at(start);
 3769                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3770                            &language_scope
 3771                        {
 3772                            let leading_whitespace_len = buffer
 3773                                .reversed_chars_at(start)
 3774                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3775                                .map(|c| c.len_utf8())
 3776                                .sum::<usize>();
 3777
 3778                            let trailing_whitespace_len = buffer
 3779                                .chars_at(end)
 3780                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3781                                .map(|c| c.len_utf8())
 3782                                .sum::<usize>();
 3783
 3784                            let insert_extra_newline =
 3785                                language.brackets().any(|(pair, enabled)| {
 3786                                    let pair_start = pair.start.trim_end();
 3787                                    let pair_end = pair.end.trim_start();
 3788
 3789                                    enabled
 3790                                        && pair.newline
 3791                                        && buffer.contains_str_at(
 3792                                            end + trailing_whitespace_len,
 3793                                            pair_end,
 3794                                        )
 3795                                        && buffer.contains_str_at(
 3796                                            (start - leading_whitespace_len)
 3797                                                .saturating_sub(pair_start.len()),
 3798                                            pair_start,
 3799                                        )
 3800                                });
 3801
 3802                            // Comment extension on newline is allowed only for cursor selections
 3803                            let comment_delimiter = maybe!({
 3804                                if !selection_is_empty {
 3805                                    return None;
 3806                                }
 3807
 3808                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3809                                    return None;
 3810                                }
 3811
 3812                                let delimiters = language.line_comment_prefixes();
 3813                                let max_len_of_delimiter =
 3814                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3815                                let (snapshot, range) =
 3816                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3817
 3818                                let mut index_of_first_non_whitespace = 0;
 3819                                let comment_candidate = snapshot
 3820                                    .chars_for_range(range)
 3821                                    .skip_while(|c| {
 3822                                        let should_skip = c.is_whitespace();
 3823                                        if should_skip {
 3824                                            index_of_first_non_whitespace += 1;
 3825                                        }
 3826                                        should_skip
 3827                                    })
 3828                                    .take(max_len_of_delimiter)
 3829                                    .collect::<String>();
 3830                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3831                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3832                                })?;
 3833                                let cursor_is_placed_after_comment_marker =
 3834                                    index_of_first_non_whitespace + comment_prefix.len()
 3835                                        <= start_point.column as usize;
 3836                                if cursor_is_placed_after_comment_marker {
 3837                                    Some(comment_prefix.clone())
 3838                                } else {
 3839                                    None
 3840                                }
 3841                            });
 3842                            (comment_delimiter, insert_extra_newline)
 3843                        } else {
 3844                            (None, false)
 3845                        };
 3846
 3847                        let capacity_for_delimiter = comment_delimiter
 3848                            .as_deref()
 3849                            .map(str::len)
 3850                            .unwrap_or_default();
 3851                        let mut new_text =
 3852                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3853                        new_text.push('\n');
 3854                        new_text.extend(indent.chars());
 3855                        if let Some(delimiter) = &comment_delimiter {
 3856                            new_text.push_str(delimiter);
 3857                        }
 3858                        if insert_extra_newline {
 3859                            new_text = new_text.repeat(2);
 3860                        }
 3861
 3862                        let anchor = buffer.anchor_after(end);
 3863                        let new_selection = selection.map(|_| anchor);
 3864                        (
 3865                            (start..end, new_text),
 3866                            (insert_extra_newline, new_selection),
 3867                        )
 3868                    })
 3869                    .unzip()
 3870            };
 3871
 3872            this.edit_with_autoindent(edits, cx);
 3873            let buffer = this.buffer.read(cx).snapshot(cx);
 3874            let new_selections = selection_fixup_info
 3875                .into_iter()
 3876                .map(|(extra_newline_inserted, new_selection)| {
 3877                    let mut cursor = new_selection.end.to_point(&buffer);
 3878                    if extra_newline_inserted {
 3879                        cursor.row -= 1;
 3880                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3881                    }
 3882                    new_selection.map(|_| cursor)
 3883                })
 3884                .collect();
 3885
 3886            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3887            this.refresh_inline_completion(true, false, cx);
 3888        });
 3889    }
 3890
 3891    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3892        let buffer = self.buffer.read(cx);
 3893        let snapshot = buffer.snapshot(cx);
 3894
 3895        let mut edits = Vec::new();
 3896        let mut rows = Vec::new();
 3897
 3898        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3899            let cursor = selection.head();
 3900            let row = cursor.row;
 3901
 3902            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3903
 3904            let newline = "\n".to_string();
 3905            edits.push((start_of_line..start_of_line, newline));
 3906
 3907            rows.push(row + rows_inserted as u32);
 3908        }
 3909
 3910        self.transact(cx, |editor, cx| {
 3911            editor.edit(edits, cx);
 3912
 3913            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3914                let mut index = 0;
 3915                s.move_cursors_with(|map, _, _| {
 3916                    let row = rows[index];
 3917                    index += 1;
 3918
 3919                    let point = Point::new(row, 0);
 3920                    let boundary = map.next_line_boundary(point).1;
 3921                    let clipped = map.clip_point(boundary, Bias::Left);
 3922
 3923                    (clipped, SelectionGoal::None)
 3924                });
 3925            });
 3926
 3927            let mut indent_edits = Vec::new();
 3928            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3929            for row in rows {
 3930                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3931                for (row, indent) in indents {
 3932                    if indent.len == 0 {
 3933                        continue;
 3934                    }
 3935
 3936                    let text = match indent.kind {
 3937                        IndentKind::Space => " ".repeat(indent.len as usize),
 3938                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3939                    };
 3940                    let point = Point::new(row.0, 0);
 3941                    indent_edits.push((point..point, text));
 3942                }
 3943            }
 3944            editor.edit(indent_edits, cx);
 3945        });
 3946    }
 3947
 3948    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3949        let buffer = self.buffer.read(cx);
 3950        let snapshot = buffer.snapshot(cx);
 3951
 3952        let mut edits = Vec::new();
 3953        let mut rows = Vec::new();
 3954        let mut rows_inserted = 0;
 3955
 3956        for selection in self.selections.all_adjusted(cx) {
 3957            let cursor = selection.head();
 3958            let row = cursor.row;
 3959
 3960            let point = Point::new(row + 1, 0);
 3961            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3962
 3963            let newline = "\n".to_string();
 3964            edits.push((start_of_line..start_of_line, newline));
 3965
 3966            rows_inserted += 1;
 3967            rows.push(row + rows_inserted);
 3968        }
 3969
 3970        self.transact(cx, |editor, cx| {
 3971            editor.edit(edits, cx);
 3972
 3973            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3974                let mut index = 0;
 3975                s.move_cursors_with(|map, _, _| {
 3976                    let row = rows[index];
 3977                    index += 1;
 3978
 3979                    let point = Point::new(row, 0);
 3980                    let boundary = map.next_line_boundary(point).1;
 3981                    let clipped = map.clip_point(boundary, Bias::Left);
 3982
 3983                    (clipped, SelectionGoal::None)
 3984                });
 3985            });
 3986
 3987            let mut indent_edits = Vec::new();
 3988            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3989            for row in rows {
 3990                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3991                for (row, indent) in indents {
 3992                    if indent.len == 0 {
 3993                        continue;
 3994                    }
 3995
 3996                    let text = match indent.kind {
 3997                        IndentKind::Space => " ".repeat(indent.len as usize),
 3998                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3999                    };
 4000                    let point = Point::new(row.0, 0);
 4001                    indent_edits.push((point..point, text));
 4002                }
 4003            }
 4004            editor.edit(indent_edits, cx);
 4005        });
 4006    }
 4007
 4008    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 4009        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4010            original_indent_columns: Vec::new(),
 4011        });
 4012        self.insert_with_autoindent_mode(text, autoindent, cx);
 4013    }
 4014
 4015    fn insert_with_autoindent_mode(
 4016        &mut self,
 4017        text: &str,
 4018        autoindent_mode: Option<AutoindentMode>,
 4019        cx: &mut ViewContext<Self>,
 4020    ) {
 4021        if self.read_only(cx) {
 4022            return;
 4023        }
 4024
 4025        let text: Arc<str> = text.into();
 4026        self.transact(cx, |this, cx| {
 4027            let old_selections = this.selections.all_adjusted(cx);
 4028            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4029                let anchors = {
 4030                    let snapshot = buffer.read(cx);
 4031                    old_selections
 4032                        .iter()
 4033                        .map(|s| {
 4034                            let anchor = snapshot.anchor_after(s.head());
 4035                            s.map(|_| anchor)
 4036                        })
 4037                        .collect::<Vec<_>>()
 4038                };
 4039                buffer.edit(
 4040                    old_selections
 4041                        .iter()
 4042                        .map(|s| (s.start..s.end, text.clone())),
 4043                    autoindent_mode,
 4044                    cx,
 4045                );
 4046                anchors
 4047            });
 4048
 4049            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4050                s.select_anchors(selection_anchors);
 4051            })
 4052        });
 4053    }
 4054
 4055    fn trigger_completion_on_input(
 4056        &mut self,
 4057        text: &str,
 4058        trigger_in_words: bool,
 4059        cx: &mut ViewContext<Self>,
 4060    ) {
 4061        if self.is_completion_trigger(text, trigger_in_words, cx) {
 4062            self.show_completions(
 4063                &ShowCompletions {
 4064                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4065                },
 4066                cx,
 4067            );
 4068        } else {
 4069            self.hide_context_menu(cx);
 4070        }
 4071    }
 4072
 4073    fn is_completion_trigger(
 4074        &self,
 4075        text: &str,
 4076        trigger_in_words: bool,
 4077        cx: &mut ViewContext<Self>,
 4078    ) -> bool {
 4079        let position = self.selections.newest_anchor().head();
 4080        let multibuffer = self.buffer.read(cx);
 4081        let Some(buffer) = position
 4082            .buffer_id
 4083            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4084        else {
 4085            return false;
 4086        };
 4087
 4088        if let Some(completion_provider) = &self.completion_provider {
 4089            completion_provider.is_completion_trigger(
 4090                &buffer,
 4091                position.text_anchor,
 4092                text,
 4093                trigger_in_words,
 4094                cx,
 4095            )
 4096        } else {
 4097            false
 4098        }
 4099    }
 4100
 4101    /// If any empty selections is touching the start of its innermost containing autoclose
 4102    /// region, expand it to select the brackets.
 4103    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4104        let selections = self.selections.all::<usize>(cx);
 4105        let buffer = self.buffer.read(cx).read(cx);
 4106        let new_selections = self
 4107            .selections_with_autoclose_regions(selections, &buffer)
 4108            .map(|(mut selection, region)| {
 4109                if !selection.is_empty() {
 4110                    return selection;
 4111                }
 4112
 4113                if let Some(region) = region {
 4114                    let mut range = region.range.to_offset(&buffer);
 4115                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4116                        range.start -= region.pair.start.len();
 4117                        if buffer.contains_str_at(range.start, &region.pair.start)
 4118                            && buffer.contains_str_at(range.end, &region.pair.end)
 4119                        {
 4120                            range.end += region.pair.end.len();
 4121                            selection.start = range.start;
 4122                            selection.end = range.end;
 4123
 4124                            return selection;
 4125                        }
 4126                    }
 4127                }
 4128
 4129                let always_treat_brackets_as_autoclosed = buffer
 4130                    .settings_at(selection.start, cx)
 4131                    .always_treat_brackets_as_autoclosed;
 4132
 4133                if !always_treat_brackets_as_autoclosed {
 4134                    return selection;
 4135                }
 4136
 4137                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4138                    for (pair, enabled) in scope.brackets() {
 4139                        if !enabled || !pair.close {
 4140                            continue;
 4141                        }
 4142
 4143                        if buffer.contains_str_at(selection.start, &pair.end) {
 4144                            let pair_start_len = pair.start.len();
 4145                            if buffer.contains_str_at(
 4146                                selection.start.saturating_sub(pair_start_len),
 4147                                &pair.start,
 4148                            ) {
 4149                                selection.start -= pair_start_len;
 4150                                selection.end += pair.end.len();
 4151
 4152                                return selection;
 4153                            }
 4154                        }
 4155                    }
 4156                }
 4157
 4158                selection
 4159            })
 4160            .collect();
 4161
 4162        drop(buffer);
 4163        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4164    }
 4165
 4166    /// Iterate the given selections, and for each one, find the smallest surrounding
 4167    /// autoclose region. This uses the ordering of the selections and the autoclose
 4168    /// regions to avoid repeated comparisons.
 4169    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4170        &'a self,
 4171        selections: impl IntoIterator<Item = Selection<D>>,
 4172        buffer: &'a MultiBufferSnapshot,
 4173    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4174        let mut i = 0;
 4175        let mut regions = self.autoclose_regions.as_slice();
 4176        selections.into_iter().map(move |selection| {
 4177            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4178
 4179            let mut enclosing = None;
 4180            while let Some(pair_state) = regions.get(i) {
 4181                if pair_state.range.end.to_offset(buffer) < range.start {
 4182                    regions = &regions[i + 1..];
 4183                    i = 0;
 4184                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4185                    break;
 4186                } else {
 4187                    if pair_state.selection_id == selection.id {
 4188                        enclosing = Some(pair_state);
 4189                    }
 4190                    i += 1;
 4191                }
 4192            }
 4193
 4194            (selection, enclosing)
 4195        })
 4196    }
 4197
 4198    /// Remove any autoclose regions that no longer contain their selection.
 4199    fn invalidate_autoclose_regions(
 4200        &mut self,
 4201        mut selections: &[Selection<Anchor>],
 4202        buffer: &MultiBufferSnapshot,
 4203    ) {
 4204        self.autoclose_regions.retain(|state| {
 4205            let mut i = 0;
 4206            while let Some(selection) = selections.get(i) {
 4207                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4208                    selections = &selections[1..];
 4209                    continue;
 4210                }
 4211                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4212                    break;
 4213                }
 4214                if selection.id == state.selection_id {
 4215                    return true;
 4216                } else {
 4217                    i += 1;
 4218                }
 4219            }
 4220            false
 4221        });
 4222    }
 4223
 4224    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4225        let offset = position.to_offset(buffer);
 4226        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4227        if offset > word_range.start && kind == Some(CharKind::Word) {
 4228            Some(
 4229                buffer
 4230                    .text_for_range(word_range.start..offset)
 4231                    .collect::<String>(),
 4232            )
 4233        } else {
 4234            None
 4235        }
 4236    }
 4237
 4238    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4239        self.refresh_inlay_hints(
 4240            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4241            cx,
 4242        );
 4243    }
 4244
 4245    pub fn inlay_hints_enabled(&self) -> bool {
 4246        self.inlay_hint_cache.enabled
 4247    }
 4248
 4249    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4250        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4251            return;
 4252        }
 4253
 4254        let reason_description = reason.description();
 4255        let ignore_debounce = matches!(
 4256            reason,
 4257            InlayHintRefreshReason::SettingsChange(_)
 4258                | InlayHintRefreshReason::Toggle(_)
 4259                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4260        );
 4261        let (invalidate_cache, required_languages) = match reason {
 4262            InlayHintRefreshReason::Toggle(enabled) => {
 4263                self.inlay_hint_cache.enabled = enabled;
 4264                if enabled {
 4265                    (InvalidationStrategy::RefreshRequested, None)
 4266                } else {
 4267                    self.inlay_hint_cache.clear();
 4268                    self.splice_inlays(
 4269                        self.visible_inlay_hints(cx)
 4270                            .iter()
 4271                            .map(|inlay| inlay.id)
 4272                            .collect(),
 4273                        Vec::new(),
 4274                        cx,
 4275                    );
 4276                    return;
 4277                }
 4278            }
 4279            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4280                match self.inlay_hint_cache.update_settings(
 4281                    &self.buffer,
 4282                    new_settings,
 4283                    self.visible_inlay_hints(cx),
 4284                    cx,
 4285                ) {
 4286                    ControlFlow::Break(Some(InlaySplice {
 4287                        to_remove,
 4288                        to_insert,
 4289                    })) => {
 4290                        self.splice_inlays(to_remove, to_insert, cx);
 4291                        return;
 4292                    }
 4293                    ControlFlow::Break(None) => return,
 4294                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4295                }
 4296            }
 4297            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4298                if let Some(InlaySplice {
 4299                    to_remove,
 4300                    to_insert,
 4301                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4302                {
 4303                    self.splice_inlays(to_remove, to_insert, cx);
 4304                }
 4305                return;
 4306            }
 4307            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4308            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4309                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4310            }
 4311            InlayHintRefreshReason::RefreshRequested => {
 4312                (InvalidationStrategy::RefreshRequested, None)
 4313            }
 4314        };
 4315
 4316        if let Some(InlaySplice {
 4317            to_remove,
 4318            to_insert,
 4319        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4320            reason_description,
 4321            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4322            invalidate_cache,
 4323            ignore_debounce,
 4324            cx,
 4325        ) {
 4326            self.splice_inlays(to_remove, to_insert, cx);
 4327        }
 4328    }
 4329
 4330    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4331        self.display_map
 4332            .read(cx)
 4333            .current_inlays()
 4334            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4335            .cloned()
 4336            .collect()
 4337    }
 4338
 4339    pub fn excerpts_for_inlay_hints_query(
 4340        &self,
 4341        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4342        cx: &mut ViewContext<Editor>,
 4343    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4344        let Some(project) = self.project.as_ref() else {
 4345            return HashMap::default();
 4346        };
 4347        let project = project.read(cx);
 4348        let multi_buffer = self.buffer().read(cx);
 4349        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4350        let multi_buffer_visible_start = self
 4351            .scroll_manager
 4352            .anchor()
 4353            .anchor
 4354            .to_point(&multi_buffer_snapshot);
 4355        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4356            multi_buffer_visible_start
 4357                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4358            Bias::Left,
 4359        );
 4360        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4361        multi_buffer
 4362            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4363            .into_iter()
 4364            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4365            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4366                let buffer = buffer_handle.read(cx);
 4367                let buffer_file = project::File::from_dyn(buffer.file())?;
 4368                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4369                let worktree_entry = buffer_worktree
 4370                    .read(cx)
 4371                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4372                if worktree_entry.is_ignored {
 4373                    return None;
 4374                }
 4375
 4376                let language = buffer.language()?;
 4377                if let Some(restrict_to_languages) = restrict_to_languages {
 4378                    if !restrict_to_languages.contains(language) {
 4379                        return None;
 4380                    }
 4381                }
 4382                Some((
 4383                    excerpt_id,
 4384                    (
 4385                        buffer_handle,
 4386                        buffer.version().clone(),
 4387                        excerpt_visible_range,
 4388                    ),
 4389                ))
 4390            })
 4391            .collect()
 4392    }
 4393
 4394    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4395        TextLayoutDetails {
 4396            text_system: cx.text_system().clone(),
 4397            editor_style: self.style.clone().unwrap(),
 4398            rem_size: cx.rem_size(),
 4399            scroll_anchor: self.scroll_manager.anchor(),
 4400            visible_rows: self.visible_line_count(),
 4401            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4402        }
 4403    }
 4404
 4405    fn splice_inlays(
 4406        &self,
 4407        to_remove: Vec<InlayId>,
 4408        to_insert: Vec<Inlay>,
 4409        cx: &mut ViewContext<Self>,
 4410    ) {
 4411        self.display_map.update(cx, |display_map, cx| {
 4412            display_map.splice_inlays(to_remove, to_insert, cx);
 4413        });
 4414        cx.notify();
 4415    }
 4416
 4417    fn trigger_on_type_formatting(
 4418        &self,
 4419        input: String,
 4420        cx: &mut ViewContext<Self>,
 4421    ) -> Option<Task<Result<()>>> {
 4422        if input.len() != 1 {
 4423            return None;
 4424        }
 4425
 4426        let project = self.project.as_ref()?;
 4427        let position = self.selections.newest_anchor().head();
 4428        let (buffer, buffer_position) = self
 4429            .buffer
 4430            .read(cx)
 4431            .text_anchor_for_position(position, cx)?;
 4432
 4433        let settings = language_settings::language_settings(
 4434            buffer
 4435                .read(cx)
 4436                .language_at(buffer_position)
 4437                .map(|l| l.name()),
 4438            buffer.read(cx).file(),
 4439            cx,
 4440        );
 4441        if !settings.use_on_type_format {
 4442            return None;
 4443        }
 4444
 4445        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4446        // hence we do LSP request & edit on host side only — add formats to host's history.
 4447        let push_to_lsp_host_history = true;
 4448        // If this is not the host, append its history with new edits.
 4449        let push_to_client_history = project.read(cx).is_via_collab();
 4450
 4451        let on_type_formatting = project.update(cx, |project, cx| {
 4452            project.on_type_format(
 4453                buffer.clone(),
 4454                buffer_position,
 4455                input,
 4456                push_to_lsp_host_history,
 4457                cx,
 4458            )
 4459        });
 4460        Some(cx.spawn(|editor, mut cx| async move {
 4461            if let Some(transaction) = on_type_formatting.await? {
 4462                if push_to_client_history {
 4463                    buffer
 4464                        .update(&mut cx, |buffer, _| {
 4465                            buffer.push_transaction(transaction, Instant::now());
 4466                        })
 4467                        .ok();
 4468                }
 4469                editor.update(&mut cx, |editor, cx| {
 4470                    editor.refresh_document_highlights(cx);
 4471                })?;
 4472            }
 4473            Ok(())
 4474        }))
 4475    }
 4476
 4477    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4478        if self.pending_rename.is_some() {
 4479            return;
 4480        }
 4481
 4482        let Some(provider) = self.completion_provider.as_ref() else {
 4483            return;
 4484        };
 4485
 4486        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4487            return;
 4488        }
 4489
 4490        let position = self.selections.newest_anchor().head();
 4491        let (buffer, buffer_position) =
 4492            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4493                output
 4494            } else {
 4495                return;
 4496            };
 4497
 4498        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4499        let is_followup_invoke = {
 4500            let context_menu_state = self.context_menu.read();
 4501            matches!(
 4502                context_menu_state.deref(),
 4503                Some(ContextMenu::Completions(_))
 4504            )
 4505        };
 4506        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4507            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4508            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4509                CompletionTriggerKind::TRIGGER_CHARACTER
 4510            }
 4511
 4512            _ => CompletionTriggerKind::INVOKED,
 4513        };
 4514        let completion_context = CompletionContext {
 4515            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4516                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4517                    Some(String::from(trigger))
 4518                } else {
 4519                    None
 4520                }
 4521            }),
 4522            trigger_kind,
 4523        };
 4524        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4525        let sort_completions = provider.sort_completions();
 4526
 4527        let id = post_inc(&mut self.next_completion_id);
 4528        let task = cx.spawn(|this, mut cx| {
 4529            async move {
 4530                this.update(&mut cx, |this, _| {
 4531                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4532                })?;
 4533                let completions = completions.await.log_err();
 4534                let menu = if let Some(completions) = completions {
 4535                    let mut menu = CompletionsMenu::new(
 4536                        id,
 4537                        sort_completions,
 4538                        position,
 4539                        buffer.clone(),
 4540                        completions.into(),
 4541                    );
 4542                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4543                        .await;
 4544
 4545                    if menu.matches.is_empty() {
 4546                        None
 4547                    } else {
 4548                        this.update(&mut cx, |editor, cx| {
 4549                            let completions = menu.completions.clone();
 4550                            let matches = menu.matches.clone();
 4551
 4552                            let delay_ms = EditorSettings::get_global(cx)
 4553                                .completion_documentation_secondary_query_debounce;
 4554                            let delay = Duration::from_millis(delay_ms);
 4555                            editor
 4556                                .completion_documentation_pre_resolve_debounce
 4557                                .fire_new(delay, cx, |editor, cx| {
 4558                                    CompletionsMenu::pre_resolve_completion_documentation(
 4559                                        buffer,
 4560                                        completions,
 4561                                        matches,
 4562                                        editor,
 4563                                        cx,
 4564                                    )
 4565                                });
 4566                        })
 4567                        .ok();
 4568                        Some(menu)
 4569                    }
 4570                } else {
 4571                    None
 4572                };
 4573
 4574                this.update(&mut cx, |this, cx| {
 4575                    let mut context_menu = this.context_menu.write();
 4576                    match context_menu.as_ref() {
 4577                        None => {}
 4578
 4579                        Some(ContextMenu::Completions(prev_menu)) => {
 4580                            if prev_menu.id > id {
 4581                                return;
 4582                            }
 4583                        }
 4584
 4585                        _ => return,
 4586                    }
 4587
 4588                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4589                        let menu = menu.unwrap();
 4590                        *context_menu = Some(ContextMenu::Completions(menu));
 4591                        drop(context_menu);
 4592                        this.discard_inline_completion(false, cx);
 4593                        cx.notify();
 4594                    } else if this.completion_tasks.len() <= 1 {
 4595                        // If there are no more completion tasks and the last menu was
 4596                        // empty, we should hide it. If it was already hidden, we should
 4597                        // also show the copilot completion when available.
 4598                        drop(context_menu);
 4599                        if this.hide_context_menu(cx).is_none() {
 4600                            this.update_visible_inline_completion(cx);
 4601                        }
 4602                    }
 4603                })?;
 4604
 4605                Ok::<_, anyhow::Error>(())
 4606            }
 4607            .log_err()
 4608        });
 4609
 4610        self.completion_tasks.push((id, task));
 4611    }
 4612
 4613    pub fn confirm_completion(
 4614        &mut self,
 4615        action: &ConfirmCompletion,
 4616        cx: &mut ViewContext<Self>,
 4617    ) -> Option<Task<Result<()>>> {
 4618        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4619    }
 4620
 4621    pub fn compose_completion(
 4622        &mut self,
 4623        action: &ComposeCompletion,
 4624        cx: &mut ViewContext<Self>,
 4625    ) -> Option<Task<Result<()>>> {
 4626        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4627    }
 4628
 4629    fn do_completion(
 4630        &mut self,
 4631        item_ix: Option<usize>,
 4632        intent: CompletionIntent,
 4633        cx: &mut ViewContext<Editor>,
 4634    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4635        use language::ToOffset as _;
 4636
 4637        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4638            menu
 4639        } else {
 4640            return None;
 4641        };
 4642
 4643        let mat = completions_menu
 4644            .matches
 4645            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4646        let buffer_handle = completions_menu.buffer;
 4647        let completions = completions_menu.completions.read();
 4648        let completion = completions.get(mat.candidate_id)?;
 4649        cx.stop_propagation();
 4650
 4651        let snippet;
 4652        let text;
 4653
 4654        if completion.is_snippet() {
 4655            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4656            text = snippet.as_ref().unwrap().text.clone();
 4657        } else {
 4658            snippet = None;
 4659            text = completion.new_text.clone();
 4660        };
 4661        let selections = self.selections.all::<usize>(cx);
 4662        let buffer = buffer_handle.read(cx);
 4663        let old_range = completion.old_range.to_offset(buffer);
 4664        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4665
 4666        let newest_selection = self.selections.newest_anchor();
 4667        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4668            return None;
 4669        }
 4670
 4671        let lookbehind = newest_selection
 4672            .start
 4673            .text_anchor
 4674            .to_offset(buffer)
 4675            .saturating_sub(old_range.start);
 4676        let lookahead = old_range
 4677            .end
 4678            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4679        let mut common_prefix_len = old_text
 4680            .bytes()
 4681            .zip(text.bytes())
 4682            .take_while(|(a, b)| a == b)
 4683            .count();
 4684
 4685        let snapshot = self.buffer.read(cx).snapshot(cx);
 4686        let mut range_to_replace: Option<Range<isize>> = None;
 4687        let mut ranges = Vec::new();
 4688        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4689        for selection in &selections {
 4690            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4691                let start = selection.start.saturating_sub(lookbehind);
 4692                let end = selection.end + lookahead;
 4693                if selection.id == newest_selection.id {
 4694                    range_to_replace = Some(
 4695                        ((start + common_prefix_len) as isize - selection.start as isize)
 4696                            ..(end as isize - selection.start as isize),
 4697                    );
 4698                }
 4699                ranges.push(start + common_prefix_len..end);
 4700            } else {
 4701                common_prefix_len = 0;
 4702                ranges.clear();
 4703                ranges.extend(selections.iter().map(|s| {
 4704                    if s.id == newest_selection.id {
 4705                        range_to_replace = Some(
 4706                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4707                                - selection.start as isize
 4708                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4709                                    - selection.start as isize,
 4710                        );
 4711                        old_range.clone()
 4712                    } else {
 4713                        s.start..s.end
 4714                    }
 4715                }));
 4716                break;
 4717            }
 4718            if !self.linked_edit_ranges.is_empty() {
 4719                let start_anchor = snapshot.anchor_before(selection.head());
 4720                let end_anchor = snapshot.anchor_after(selection.tail());
 4721                if let Some(ranges) = self
 4722                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4723                {
 4724                    for (buffer, edits) in ranges {
 4725                        linked_edits.entry(buffer.clone()).or_default().extend(
 4726                            edits
 4727                                .into_iter()
 4728                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4729                        );
 4730                    }
 4731                }
 4732            }
 4733        }
 4734        let text = &text[common_prefix_len..];
 4735
 4736        cx.emit(EditorEvent::InputHandled {
 4737            utf16_range_to_replace: range_to_replace,
 4738            text: text.into(),
 4739        });
 4740
 4741        self.transact(cx, |this, cx| {
 4742            if let Some(mut snippet) = snippet {
 4743                snippet.text = text.to_string();
 4744                for tabstop in snippet
 4745                    .tabstops
 4746                    .iter_mut()
 4747                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4748                {
 4749                    tabstop.start -= common_prefix_len as isize;
 4750                    tabstop.end -= common_prefix_len as isize;
 4751                }
 4752
 4753                this.insert_snippet(&ranges, snippet, cx).log_err();
 4754            } else {
 4755                this.buffer.update(cx, |buffer, cx| {
 4756                    buffer.edit(
 4757                        ranges.iter().map(|range| (range.clone(), text)),
 4758                        this.autoindent_mode.clone(),
 4759                        cx,
 4760                    );
 4761                });
 4762            }
 4763            for (buffer, edits) in linked_edits {
 4764                buffer.update(cx, |buffer, cx| {
 4765                    let snapshot = buffer.snapshot();
 4766                    let edits = edits
 4767                        .into_iter()
 4768                        .map(|(range, text)| {
 4769                            use text::ToPoint as TP;
 4770                            let end_point = TP::to_point(&range.end, &snapshot);
 4771                            let start_point = TP::to_point(&range.start, &snapshot);
 4772                            (start_point..end_point, text)
 4773                        })
 4774                        .sorted_by_key(|(range, _)| range.start)
 4775                        .collect::<Vec<_>>();
 4776                    buffer.edit(edits, None, cx);
 4777                })
 4778            }
 4779
 4780            this.refresh_inline_completion(true, false, cx);
 4781        });
 4782
 4783        let show_new_completions_on_confirm = completion
 4784            .confirm
 4785            .as_ref()
 4786            .map_or(false, |confirm| confirm(intent, cx));
 4787        if show_new_completions_on_confirm {
 4788            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4789        }
 4790
 4791        let provider = self.completion_provider.as_ref()?;
 4792        let apply_edits = provider.apply_additional_edits_for_completion(
 4793            buffer_handle,
 4794            completion.clone(),
 4795            true,
 4796            cx,
 4797        );
 4798
 4799        let editor_settings = EditorSettings::get_global(cx);
 4800        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4801            // After the code completion is finished, users often want to know what signatures are needed.
 4802            // so we should automatically call signature_help
 4803            self.show_signature_help(&ShowSignatureHelp, cx);
 4804        }
 4805
 4806        Some(cx.foreground_executor().spawn(async move {
 4807            apply_edits.await?;
 4808            Ok(())
 4809        }))
 4810    }
 4811
 4812    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4813        let mut context_menu = self.context_menu.write();
 4814        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4815            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4816                // Toggle if we're selecting the same one
 4817                *context_menu = None;
 4818                cx.notify();
 4819                return;
 4820            } else {
 4821                // Otherwise, clear it and start a new one
 4822                *context_menu = None;
 4823                cx.notify();
 4824            }
 4825        }
 4826        drop(context_menu);
 4827        let snapshot = self.snapshot(cx);
 4828        let deployed_from_indicator = action.deployed_from_indicator;
 4829        let mut task = self.code_actions_task.take();
 4830        let action = action.clone();
 4831        cx.spawn(|editor, mut cx| async move {
 4832            while let Some(prev_task) = task {
 4833                prev_task.await.log_err();
 4834                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4835            }
 4836
 4837            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4838                if editor.focus_handle.is_focused(cx) {
 4839                    let multibuffer_point = action
 4840                        .deployed_from_indicator
 4841                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4842                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4843                    let (buffer, buffer_row) = snapshot
 4844                        .buffer_snapshot
 4845                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4846                        .and_then(|(buffer_snapshot, range)| {
 4847                            editor
 4848                                .buffer
 4849                                .read(cx)
 4850                                .buffer(buffer_snapshot.remote_id())
 4851                                .map(|buffer| (buffer, range.start.row))
 4852                        })?;
 4853                    let (_, code_actions) = editor
 4854                        .available_code_actions
 4855                        .clone()
 4856                        .and_then(|(location, code_actions)| {
 4857                            let snapshot = location.buffer.read(cx).snapshot();
 4858                            let point_range = location.range.to_point(&snapshot);
 4859                            let point_range = point_range.start.row..=point_range.end.row;
 4860                            if point_range.contains(&buffer_row) {
 4861                                Some((location, code_actions))
 4862                            } else {
 4863                                None
 4864                            }
 4865                        })
 4866                        .unzip();
 4867                    let buffer_id = buffer.read(cx).remote_id();
 4868                    let tasks = editor
 4869                        .tasks
 4870                        .get(&(buffer_id, buffer_row))
 4871                        .map(|t| Arc::new(t.to_owned()));
 4872                    if tasks.is_none() && code_actions.is_none() {
 4873                        return None;
 4874                    }
 4875
 4876                    editor.completion_tasks.clear();
 4877                    editor.discard_inline_completion(false, cx);
 4878                    let task_context =
 4879                        tasks
 4880                            .as_ref()
 4881                            .zip(editor.project.clone())
 4882                            .map(|(tasks, project)| {
 4883                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4884                            });
 4885
 4886                    Some(cx.spawn(|editor, mut cx| async move {
 4887                        let task_context = match task_context {
 4888                            Some(task_context) => task_context.await,
 4889                            None => None,
 4890                        };
 4891                        let resolved_tasks =
 4892                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4893                                Arc::new(ResolvedTasks {
 4894                                    templates: tasks.resolve(&task_context).collect(),
 4895                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4896                                        multibuffer_point.row,
 4897                                        tasks.column,
 4898                                    )),
 4899                                })
 4900                            });
 4901                        let spawn_straight_away = resolved_tasks
 4902                            .as_ref()
 4903                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4904                            && code_actions
 4905                                .as_ref()
 4906                                .map_or(true, |actions| actions.is_empty());
 4907                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4908                            *editor.context_menu.write() =
 4909                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4910                                    buffer,
 4911                                    actions: CodeActionContents {
 4912                                        tasks: resolved_tasks,
 4913                                        actions: code_actions,
 4914                                    },
 4915                                    selected_item: Default::default(),
 4916                                    scroll_handle: UniformListScrollHandle::default(),
 4917                                    deployed_from_indicator,
 4918                                }));
 4919                            if spawn_straight_away {
 4920                                if let Some(task) = editor.confirm_code_action(
 4921                                    &ConfirmCodeAction { item_ix: Some(0) },
 4922                                    cx,
 4923                                ) {
 4924                                    cx.notify();
 4925                                    return task;
 4926                                }
 4927                            }
 4928                            cx.notify();
 4929                            Task::ready(Ok(()))
 4930                        }) {
 4931                            task.await
 4932                        } else {
 4933                            Ok(())
 4934                        }
 4935                    }))
 4936                } else {
 4937                    Some(Task::ready(Ok(())))
 4938                }
 4939            })?;
 4940            if let Some(task) = spawned_test_task {
 4941                task.await?;
 4942            }
 4943
 4944            Ok::<_, anyhow::Error>(())
 4945        })
 4946        .detach_and_log_err(cx);
 4947    }
 4948
 4949    pub fn confirm_code_action(
 4950        &mut self,
 4951        action: &ConfirmCodeAction,
 4952        cx: &mut ViewContext<Self>,
 4953    ) -> Option<Task<Result<()>>> {
 4954        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4955            menu
 4956        } else {
 4957            return None;
 4958        };
 4959        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4960        let action = actions_menu.actions.get(action_ix)?;
 4961        let title = action.label();
 4962        let buffer = actions_menu.buffer;
 4963        let workspace = self.workspace()?;
 4964
 4965        match action {
 4966            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4967                workspace.update(cx, |workspace, cx| {
 4968                    workspace::tasks::schedule_resolved_task(
 4969                        workspace,
 4970                        task_source_kind,
 4971                        resolved_task,
 4972                        false,
 4973                        cx,
 4974                    );
 4975
 4976                    Some(Task::ready(Ok(())))
 4977                })
 4978            }
 4979            CodeActionsItem::CodeAction {
 4980                excerpt_id,
 4981                action,
 4982                provider,
 4983            } => {
 4984                let apply_code_action =
 4985                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4986                let workspace = workspace.downgrade();
 4987                Some(cx.spawn(|editor, cx| async move {
 4988                    let project_transaction = apply_code_action.await?;
 4989                    Self::open_project_transaction(
 4990                        &editor,
 4991                        workspace,
 4992                        project_transaction,
 4993                        title,
 4994                        cx,
 4995                    )
 4996                    .await
 4997                }))
 4998            }
 4999        }
 5000    }
 5001
 5002    pub async fn open_project_transaction(
 5003        this: &WeakView<Editor>,
 5004        workspace: WeakView<Workspace>,
 5005        transaction: ProjectTransaction,
 5006        title: String,
 5007        mut cx: AsyncWindowContext,
 5008    ) -> Result<()> {
 5009        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5010        cx.update(|cx| {
 5011            entries.sort_unstable_by_key(|(buffer, _)| {
 5012                buffer.read(cx).file().map(|f| f.path().clone())
 5013            });
 5014        })?;
 5015
 5016        // If the project transaction's edits are all contained within this editor, then
 5017        // avoid opening a new editor to display them.
 5018
 5019        if let Some((buffer, transaction)) = entries.first() {
 5020            if entries.len() == 1 {
 5021                let excerpt = this.update(&mut cx, |editor, cx| {
 5022                    editor
 5023                        .buffer()
 5024                        .read(cx)
 5025                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5026                })?;
 5027                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5028                    if excerpted_buffer == *buffer {
 5029                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 5030                            let excerpt_range = excerpt_range.to_offset(buffer);
 5031                            buffer
 5032                                .edited_ranges_for_transaction::<usize>(transaction)
 5033                                .all(|range| {
 5034                                    excerpt_range.start <= range.start
 5035                                        && excerpt_range.end >= range.end
 5036                                })
 5037                        })?;
 5038
 5039                        if all_edits_within_excerpt {
 5040                            return Ok(());
 5041                        }
 5042                    }
 5043                }
 5044            }
 5045        } else {
 5046            return Ok(());
 5047        }
 5048
 5049        let mut ranges_to_highlight = Vec::new();
 5050        let excerpt_buffer = cx.new_model(|cx| {
 5051            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5052            for (buffer_handle, transaction) in &entries {
 5053                let buffer = buffer_handle.read(cx);
 5054                ranges_to_highlight.extend(
 5055                    multibuffer.push_excerpts_with_context_lines(
 5056                        buffer_handle.clone(),
 5057                        buffer
 5058                            .edited_ranges_for_transaction::<usize>(transaction)
 5059                            .collect(),
 5060                        DEFAULT_MULTIBUFFER_CONTEXT,
 5061                        cx,
 5062                    ),
 5063                );
 5064            }
 5065            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5066            multibuffer
 5067        })?;
 5068
 5069        workspace.update(&mut cx, |workspace, cx| {
 5070            let project = workspace.project().clone();
 5071            let editor =
 5072                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5073            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5074            editor.update(cx, |editor, cx| {
 5075                editor.highlight_background::<Self>(
 5076                    &ranges_to_highlight,
 5077                    |theme| theme.editor_highlighted_line_background,
 5078                    cx,
 5079                );
 5080            });
 5081        })?;
 5082
 5083        Ok(())
 5084    }
 5085
 5086    pub fn clear_code_action_providers(&mut self) {
 5087        self.code_action_providers.clear();
 5088        self.available_code_actions.take();
 5089    }
 5090
 5091    pub fn push_code_action_provider(
 5092        &mut self,
 5093        provider: Arc<dyn CodeActionProvider>,
 5094        cx: &mut ViewContext<Self>,
 5095    ) {
 5096        self.code_action_providers.push(provider);
 5097        self.refresh_code_actions(cx);
 5098    }
 5099
 5100    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5101        let buffer = self.buffer.read(cx);
 5102        let newest_selection = self.selections.newest_anchor().clone();
 5103        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5104        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5105        if start_buffer != end_buffer {
 5106            return None;
 5107        }
 5108
 5109        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5110            cx.background_executor()
 5111                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5112                .await;
 5113
 5114            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5115                let providers = this.code_action_providers.clone();
 5116                let tasks = this
 5117                    .code_action_providers
 5118                    .iter()
 5119                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5120                    .collect::<Vec<_>>();
 5121                (providers, tasks)
 5122            })?;
 5123
 5124            let mut actions = Vec::new();
 5125            for (provider, provider_actions) in
 5126                providers.into_iter().zip(future::join_all(tasks).await)
 5127            {
 5128                if let Some(provider_actions) = provider_actions.log_err() {
 5129                    actions.extend(provider_actions.into_iter().map(|action| {
 5130                        AvailableCodeAction {
 5131                            excerpt_id: newest_selection.start.excerpt_id,
 5132                            action,
 5133                            provider: provider.clone(),
 5134                        }
 5135                    }));
 5136                }
 5137            }
 5138
 5139            this.update(&mut cx, |this, cx| {
 5140                this.available_code_actions = if actions.is_empty() {
 5141                    None
 5142                } else {
 5143                    Some((
 5144                        Location {
 5145                            buffer: start_buffer,
 5146                            range: start..end,
 5147                        },
 5148                        actions.into(),
 5149                    ))
 5150                };
 5151                cx.notify();
 5152            })
 5153        }));
 5154        None
 5155    }
 5156
 5157    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5158        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5159            self.show_git_blame_inline = false;
 5160
 5161            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5162                cx.background_executor().timer(delay).await;
 5163
 5164                this.update(&mut cx, |this, cx| {
 5165                    this.show_git_blame_inline = true;
 5166                    cx.notify();
 5167                })
 5168                .log_err();
 5169            }));
 5170        }
 5171    }
 5172
 5173    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5174        if self.pending_rename.is_some() {
 5175            return None;
 5176        }
 5177
 5178        let provider = self.semantics_provider.clone()?;
 5179        let buffer = self.buffer.read(cx);
 5180        let newest_selection = self.selections.newest_anchor().clone();
 5181        let cursor_position = newest_selection.head();
 5182        let (cursor_buffer, cursor_buffer_position) =
 5183            buffer.text_anchor_for_position(cursor_position, cx)?;
 5184        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5185        if cursor_buffer != tail_buffer {
 5186            return None;
 5187        }
 5188
 5189        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5190            cx.background_executor()
 5191                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5192                .await;
 5193
 5194            let highlights = if let Some(highlights) = cx
 5195                .update(|cx| {
 5196                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5197                })
 5198                .ok()
 5199                .flatten()
 5200            {
 5201                highlights.await.log_err()
 5202            } else {
 5203                None
 5204            };
 5205
 5206            if let Some(highlights) = highlights {
 5207                this.update(&mut cx, |this, cx| {
 5208                    if this.pending_rename.is_some() {
 5209                        return;
 5210                    }
 5211
 5212                    let buffer_id = cursor_position.buffer_id;
 5213                    let buffer = this.buffer.read(cx);
 5214                    if !buffer
 5215                        .text_anchor_for_position(cursor_position, cx)
 5216                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5217                    {
 5218                        return;
 5219                    }
 5220
 5221                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5222                    let mut write_ranges = Vec::new();
 5223                    let mut read_ranges = Vec::new();
 5224                    for highlight in highlights {
 5225                        for (excerpt_id, excerpt_range) in
 5226                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5227                        {
 5228                            let start = highlight
 5229                                .range
 5230                                .start
 5231                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5232                            let end = highlight
 5233                                .range
 5234                                .end
 5235                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5236                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5237                                continue;
 5238                            }
 5239
 5240                            let range = Anchor {
 5241                                buffer_id,
 5242                                excerpt_id,
 5243                                text_anchor: start,
 5244                            }..Anchor {
 5245                                buffer_id,
 5246                                excerpt_id,
 5247                                text_anchor: end,
 5248                            };
 5249                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5250                                write_ranges.push(range);
 5251                            } else {
 5252                                read_ranges.push(range);
 5253                            }
 5254                        }
 5255                    }
 5256
 5257                    this.highlight_background::<DocumentHighlightRead>(
 5258                        &read_ranges,
 5259                        |theme| theme.editor_document_highlight_read_background,
 5260                        cx,
 5261                    );
 5262                    this.highlight_background::<DocumentHighlightWrite>(
 5263                        &write_ranges,
 5264                        |theme| theme.editor_document_highlight_write_background,
 5265                        cx,
 5266                    );
 5267                    cx.notify();
 5268                })
 5269                .log_err();
 5270            }
 5271        }));
 5272        None
 5273    }
 5274
 5275    pub fn refresh_inline_completion(
 5276        &mut self,
 5277        debounce: bool,
 5278        user_requested: bool,
 5279        cx: &mut ViewContext<Self>,
 5280    ) -> Option<()> {
 5281        let provider = self.inline_completion_provider()?;
 5282        let cursor = self.selections.newest_anchor().head();
 5283        let (buffer, cursor_buffer_position) =
 5284            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5285
 5286        if !user_requested
 5287            && (!self.enable_inline_completions
 5288                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5289        {
 5290            self.discard_inline_completion(false, cx);
 5291            return None;
 5292        }
 5293
 5294        self.update_visible_inline_completion(cx);
 5295        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5296        Some(())
 5297    }
 5298
 5299    fn cycle_inline_completion(
 5300        &mut self,
 5301        direction: Direction,
 5302        cx: &mut ViewContext<Self>,
 5303    ) -> Option<()> {
 5304        let provider = self.inline_completion_provider()?;
 5305        let cursor = self.selections.newest_anchor().head();
 5306        let (buffer, cursor_buffer_position) =
 5307            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5308        if !self.enable_inline_completions
 5309            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5310        {
 5311            return None;
 5312        }
 5313
 5314        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5315        self.update_visible_inline_completion(cx);
 5316
 5317        Some(())
 5318    }
 5319
 5320    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5321        if !self.has_active_inline_completion(cx) {
 5322            self.refresh_inline_completion(false, true, cx);
 5323            return;
 5324        }
 5325
 5326        self.update_visible_inline_completion(cx);
 5327    }
 5328
 5329    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5330        self.show_cursor_names(cx);
 5331    }
 5332
 5333    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5334        self.show_cursor_names = true;
 5335        cx.notify();
 5336        cx.spawn(|this, mut cx| async move {
 5337            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5338            this.update(&mut cx, |this, cx| {
 5339                this.show_cursor_names = false;
 5340                cx.notify()
 5341            })
 5342            .ok()
 5343        })
 5344        .detach();
 5345    }
 5346
 5347    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5348        if self.has_active_inline_completion(cx) {
 5349            self.cycle_inline_completion(Direction::Next, cx);
 5350        } else {
 5351            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5352            if is_copilot_disabled {
 5353                cx.propagate();
 5354            }
 5355        }
 5356    }
 5357
 5358    pub fn previous_inline_completion(
 5359        &mut self,
 5360        _: &PreviousInlineCompletion,
 5361        cx: &mut ViewContext<Self>,
 5362    ) {
 5363        if self.has_active_inline_completion(cx) {
 5364            self.cycle_inline_completion(Direction::Prev, cx);
 5365        } else {
 5366            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5367            if is_copilot_disabled {
 5368                cx.propagate();
 5369            }
 5370        }
 5371    }
 5372
 5373    pub fn accept_inline_completion(
 5374        &mut self,
 5375        _: &AcceptInlineCompletion,
 5376        cx: &mut ViewContext<Self>,
 5377    ) {
 5378        let Some(completion) = self.take_active_inline_completion(cx) else {
 5379            return;
 5380        };
 5381        if let Some(provider) = self.inline_completion_provider() {
 5382            provider.accept(cx);
 5383        }
 5384
 5385        cx.emit(EditorEvent::InputHandled {
 5386            utf16_range_to_replace: None,
 5387            text: completion.text.to_string().into(),
 5388        });
 5389
 5390        if let Some(range) = completion.delete_range {
 5391            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5392        }
 5393        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5394        self.refresh_inline_completion(true, true, cx);
 5395        cx.notify();
 5396    }
 5397
 5398    pub fn accept_partial_inline_completion(
 5399        &mut self,
 5400        _: &AcceptPartialInlineCompletion,
 5401        cx: &mut ViewContext<Self>,
 5402    ) {
 5403        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5404            if let Some(completion) = self.take_active_inline_completion(cx) {
 5405                let mut partial_completion = completion
 5406                    .text
 5407                    .chars()
 5408                    .by_ref()
 5409                    .take_while(|c| c.is_alphabetic())
 5410                    .collect::<String>();
 5411                if partial_completion.is_empty() {
 5412                    partial_completion = completion
 5413                        .text
 5414                        .chars()
 5415                        .by_ref()
 5416                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5417                        .collect::<String>();
 5418                }
 5419
 5420                cx.emit(EditorEvent::InputHandled {
 5421                    utf16_range_to_replace: None,
 5422                    text: partial_completion.clone().into(),
 5423                });
 5424
 5425                if let Some(range) = completion.delete_range {
 5426                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5427                }
 5428                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5429
 5430                self.refresh_inline_completion(true, true, cx);
 5431                cx.notify();
 5432            }
 5433        }
 5434    }
 5435
 5436    fn discard_inline_completion(
 5437        &mut self,
 5438        should_report_inline_completion_event: bool,
 5439        cx: &mut ViewContext<Self>,
 5440    ) -> bool {
 5441        if let Some(provider) = self.inline_completion_provider() {
 5442            provider.discard(should_report_inline_completion_event, cx);
 5443        }
 5444
 5445        self.take_active_inline_completion(cx).is_some()
 5446    }
 5447
 5448    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5449        if let Some(completion) = self.active_inline_completion.as_ref() {
 5450            let buffer = self.buffer.read(cx).read(cx);
 5451            completion.position.is_valid(&buffer)
 5452        } else {
 5453            false
 5454        }
 5455    }
 5456
 5457    fn take_active_inline_completion(
 5458        &mut self,
 5459        cx: &mut ViewContext<Self>,
 5460    ) -> Option<CompletionState> {
 5461        let completion = self.active_inline_completion.take()?;
 5462        let render_inlay_ids = completion.render_inlay_ids.clone();
 5463        self.display_map.update(cx, |map, cx| {
 5464            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5465        });
 5466        let buffer = self.buffer.read(cx).read(cx);
 5467
 5468        if completion.position.is_valid(&buffer) {
 5469            Some(completion)
 5470        } else {
 5471            None
 5472        }
 5473    }
 5474
 5475    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5476        let selection = self.selections.newest_anchor();
 5477        let cursor = selection.head();
 5478
 5479        let excerpt_id = cursor.excerpt_id;
 5480
 5481        if self.context_menu.read().is_none()
 5482            && self.completion_tasks.is_empty()
 5483            && selection.start == selection.end
 5484        {
 5485            if let Some(provider) = self.inline_completion_provider() {
 5486                if let Some((buffer, cursor_buffer_position)) =
 5487                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5488                {
 5489                    if let Some(proposal) =
 5490                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5491                    {
 5492                        let mut to_remove = Vec::new();
 5493                        if let Some(completion) = self.active_inline_completion.take() {
 5494                            to_remove.extend(completion.render_inlay_ids.iter());
 5495                        }
 5496
 5497                        let to_add = proposal
 5498                            .inlays
 5499                            .iter()
 5500                            .filter_map(|inlay| {
 5501                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5502                                let id = post_inc(&mut self.next_inlay_id);
 5503                                match inlay {
 5504                                    InlayProposal::Hint(position, hint) => {
 5505                                        let position =
 5506                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5507                                        Some(Inlay::hint(id, position, hint))
 5508                                    }
 5509                                    InlayProposal::Suggestion(position, text) => {
 5510                                        let position =
 5511                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5512                                        Some(Inlay::suggestion(id, position, text.clone()))
 5513                                    }
 5514                                }
 5515                            })
 5516                            .collect_vec();
 5517
 5518                        self.active_inline_completion = Some(CompletionState {
 5519                            position: cursor,
 5520                            text: proposal.text,
 5521                            delete_range: proposal.delete_range.and_then(|range| {
 5522                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5523                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5524                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5525                                Some(start?..end?)
 5526                            }),
 5527                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5528                        });
 5529
 5530                        self.display_map
 5531                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5532
 5533                        cx.notify();
 5534                        return;
 5535                    }
 5536                }
 5537            }
 5538        }
 5539
 5540        self.discard_inline_completion(false, cx);
 5541    }
 5542
 5543    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5544        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5545    }
 5546
 5547    fn render_code_actions_indicator(
 5548        &self,
 5549        _style: &EditorStyle,
 5550        row: DisplayRow,
 5551        is_active: bool,
 5552        cx: &mut ViewContext<Self>,
 5553    ) -> Option<IconButton> {
 5554        if self.available_code_actions.is_some() {
 5555            Some(
 5556                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5557                    .shape(ui::IconButtonShape::Square)
 5558                    .icon_size(IconSize::XSmall)
 5559                    .icon_color(Color::Muted)
 5560                    .selected(is_active)
 5561                    .tooltip({
 5562                        let focus_handle = self.focus_handle.clone();
 5563                        move |cx| {
 5564                            Tooltip::for_action_in(
 5565                                "Toggle Code Actions",
 5566                                &ToggleCodeActions {
 5567                                    deployed_from_indicator: None,
 5568                                },
 5569                                &focus_handle,
 5570                                cx,
 5571                            )
 5572                        }
 5573                    })
 5574                    .on_click(cx.listener(move |editor, _e, cx| {
 5575                        editor.focus(cx);
 5576                        editor.toggle_code_actions(
 5577                            &ToggleCodeActions {
 5578                                deployed_from_indicator: Some(row),
 5579                            },
 5580                            cx,
 5581                        );
 5582                    })),
 5583            )
 5584        } else {
 5585            None
 5586        }
 5587    }
 5588
 5589    fn clear_tasks(&mut self) {
 5590        self.tasks.clear()
 5591    }
 5592
 5593    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5594        if self.tasks.insert(key, value).is_some() {
 5595            // This case should hopefully be rare, but just in case...
 5596            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5597        }
 5598    }
 5599
 5600    fn build_tasks_context(
 5601        project: &Model<Project>,
 5602        buffer: &Model<Buffer>,
 5603        buffer_row: u32,
 5604        tasks: &Arc<RunnableTasks>,
 5605        cx: &mut ViewContext<Self>,
 5606    ) -> Task<Option<task::TaskContext>> {
 5607        let position = Point::new(buffer_row, tasks.column);
 5608        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5609        let location = Location {
 5610            buffer: buffer.clone(),
 5611            range: range_start..range_start,
 5612        };
 5613        // Fill in the environmental variables from the tree-sitter captures
 5614        let mut captured_task_variables = TaskVariables::default();
 5615        for (capture_name, value) in tasks.extra_variables.clone() {
 5616            captured_task_variables.insert(
 5617                task::VariableName::Custom(capture_name.into()),
 5618                value.clone(),
 5619            );
 5620        }
 5621        project.update(cx, |project, cx| {
 5622            project.task_store().update(cx, |task_store, cx| {
 5623                task_store.task_context_for_location(captured_task_variables, location, cx)
 5624            })
 5625        })
 5626    }
 5627
 5628    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5629        let Some((workspace, _)) = self.workspace.clone() else {
 5630            return;
 5631        };
 5632        let Some(project) = self.project.clone() else {
 5633            return;
 5634        };
 5635
 5636        // Try to find a closest, enclosing node using tree-sitter that has a
 5637        // task
 5638        let Some((buffer, buffer_row, tasks)) = self
 5639            .find_enclosing_node_task(cx)
 5640            // Or find the task that's closest in row-distance.
 5641            .or_else(|| self.find_closest_task(cx))
 5642        else {
 5643            return;
 5644        };
 5645
 5646        let reveal_strategy = action.reveal;
 5647        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5648        cx.spawn(|_, mut cx| async move {
 5649            let context = task_context.await?;
 5650            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5651
 5652            let resolved = resolved_task.resolved.as_mut()?;
 5653            resolved.reveal = reveal_strategy;
 5654
 5655            workspace
 5656                .update(&mut cx, |workspace, cx| {
 5657                    workspace::tasks::schedule_resolved_task(
 5658                        workspace,
 5659                        task_source_kind,
 5660                        resolved_task,
 5661                        false,
 5662                        cx,
 5663                    );
 5664                })
 5665                .ok()
 5666        })
 5667        .detach();
 5668    }
 5669
 5670    fn find_closest_task(
 5671        &mut self,
 5672        cx: &mut ViewContext<Self>,
 5673    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5674        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5675
 5676        let ((buffer_id, row), tasks) = self
 5677            .tasks
 5678            .iter()
 5679            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5680
 5681        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5682        let tasks = Arc::new(tasks.to_owned());
 5683        Some((buffer, *row, tasks))
 5684    }
 5685
 5686    fn find_enclosing_node_task(
 5687        &mut self,
 5688        cx: &mut ViewContext<Self>,
 5689    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5690        let snapshot = self.buffer.read(cx).snapshot(cx);
 5691        let offset = self.selections.newest::<usize>(cx).head();
 5692        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5693        let buffer_id = excerpt.buffer().remote_id();
 5694
 5695        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5696        let mut cursor = layer.node().walk();
 5697
 5698        while cursor.goto_first_child_for_byte(offset).is_some() {
 5699            if cursor.node().end_byte() == offset {
 5700                cursor.goto_next_sibling();
 5701            }
 5702        }
 5703
 5704        // Ascend to the smallest ancestor that contains the range and has a task.
 5705        loop {
 5706            let node = cursor.node();
 5707            let node_range = node.byte_range();
 5708            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5709
 5710            // Check if this node contains our offset
 5711            if node_range.start <= offset && node_range.end >= offset {
 5712                // If it contains offset, check for task
 5713                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5714                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5715                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5716                }
 5717            }
 5718
 5719            if !cursor.goto_parent() {
 5720                break;
 5721            }
 5722        }
 5723        None
 5724    }
 5725
 5726    fn render_run_indicator(
 5727        &self,
 5728        _style: &EditorStyle,
 5729        is_active: bool,
 5730        row: DisplayRow,
 5731        cx: &mut ViewContext<Self>,
 5732    ) -> IconButton {
 5733        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5734            .shape(ui::IconButtonShape::Square)
 5735            .icon_size(IconSize::XSmall)
 5736            .icon_color(Color::Muted)
 5737            .selected(is_active)
 5738            .on_click(cx.listener(move |editor, _e, cx| {
 5739                editor.focus(cx);
 5740                editor.toggle_code_actions(
 5741                    &ToggleCodeActions {
 5742                        deployed_from_indicator: Some(row),
 5743                    },
 5744                    cx,
 5745                );
 5746            }))
 5747    }
 5748
 5749    pub fn context_menu_visible(&self) -> bool {
 5750        self.context_menu
 5751            .read()
 5752            .as_ref()
 5753            .map_or(false, |menu| menu.visible())
 5754    }
 5755
 5756    fn render_context_menu(
 5757        &self,
 5758        cursor_position: DisplayPoint,
 5759        style: &EditorStyle,
 5760        max_height: Pixels,
 5761        cx: &mut ViewContext<Editor>,
 5762    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5763        self.context_menu.read().as_ref().map(|menu| {
 5764            menu.render(
 5765                cursor_position,
 5766                style,
 5767                max_height,
 5768                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5769                cx,
 5770            )
 5771        })
 5772    }
 5773
 5774    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5775        cx.notify();
 5776        self.completion_tasks.clear();
 5777        let context_menu = self.context_menu.write().take();
 5778        if context_menu.is_some() {
 5779            self.update_visible_inline_completion(cx);
 5780        }
 5781        context_menu
 5782    }
 5783
 5784    fn show_snippet_choices(
 5785        &mut self,
 5786        choices: &Vec<String>,
 5787        selection: Range<Anchor>,
 5788        cx: &mut ViewContext<Self>,
 5789    ) {
 5790        if selection.start.buffer_id.is_none() {
 5791            return;
 5792        }
 5793        let buffer_id = selection.start.buffer_id.unwrap();
 5794        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5795        let id = post_inc(&mut self.next_completion_id);
 5796
 5797        if let Some(buffer) = buffer {
 5798            *self.context_menu.write() = Some(ContextMenu::Completions(
 5799                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
 5800                    .suppress_documentation_resolution(),
 5801            ));
 5802        }
 5803    }
 5804
 5805    pub fn insert_snippet(
 5806        &mut self,
 5807        insertion_ranges: &[Range<usize>],
 5808        snippet: Snippet,
 5809        cx: &mut ViewContext<Self>,
 5810    ) -> Result<()> {
 5811        struct Tabstop<T> {
 5812            is_end_tabstop: bool,
 5813            ranges: Vec<Range<T>>,
 5814            choices: Option<Vec<String>>,
 5815        }
 5816
 5817        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5818            let snippet_text: Arc<str> = snippet.text.clone().into();
 5819            buffer.edit(
 5820                insertion_ranges
 5821                    .iter()
 5822                    .cloned()
 5823                    .map(|range| (range, snippet_text.clone())),
 5824                Some(AutoindentMode::EachLine),
 5825                cx,
 5826            );
 5827
 5828            let snapshot = &*buffer.read(cx);
 5829            let snippet = &snippet;
 5830            snippet
 5831                .tabstops
 5832                .iter()
 5833                .map(|tabstop| {
 5834                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5835                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5836                    });
 5837                    let mut tabstop_ranges = tabstop
 5838                        .ranges
 5839                        .iter()
 5840                        .flat_map(|tabstop_range| {
 5841                            let mut delta = 0_isize;
 5842                            insertion_ranges.iter().map(move |insertion_range| {
 5843                                let insertion_start = insertion_range.start as isize + delta;
 5844                                delta +=
 5845                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5846
 5847                                let start = ((insertion_start + tabstop_range.start) as usize)
 5848                                    .min(snapshot.len());
 5849                                let end = ((insertion_start + tabstop_range.end) as usize)
 5850                                    .min(snapshot.len());
 5851                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5852                            })
 5853                        })
 5854                        .collect::<Vec<_>>();
 5855                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5856
 5857                    Tabstop {
 5858                        is_end_tabstop,
 5859                        ranges: tabstop_ranges,
 5860                        choices: tabstop.choices.clone(),
 5861                    }
 5862                })
 5863                .collect::<Vec<_>>()
 5864        });
 5865        if let Some(tabstop) = tabstops.first() {
 5866            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5867                s.select_ranges(tabstop.ranges.iter().cloned());
 5868            });
 5869
 5870            if let Some(choices) = &tabstop.choices {
 5871                if let Some(selection) = tabstop.ranges.first() {
 5872                    self.show_snippet_choices(choices, selection.clone(), cx)
 5873                }
 5874            }
 5875
 5876            // If we're already at the last tabstop and it's at the end of the snippet,
 5877            // we're done, we don't need to keep the state around.
 5878            if !tabstop.is_end_tabstop {
 5879                let choices = tabstops
 5880                    .iter()
 5881                    .map(|tabstop| tabstop.choices.clone())
 5882                    .collect();
 5883
 5884                let ranges = tabstops
 5885                    .into_iter()
 5886                    .map(|tabstop| tabstop.ranges)
 5887                    .collect::<Vec<_>>();
 5888
 5889                self.snippet_stack.push(SnippetState {
 5890                    active_index: 0,
 5891                    ranges,
 5892                    choices,
 5893                });
 5894            }
 5895
 5896            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5897            if self.autoclose_regions.is_empty() {
 5898                let snapshot = self.buffer.read(cx).snapshot(cx);
 5899                for selection in &mut self.selections.all::<Point>(cx) {
 5900                    let selection_head = selection.head();
 5901                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5902                        continue;
 5903                    };
 5904
 5905                    let mut bracket_pair = None;
 5906                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5907                    let prev_chars = snapshot
 5908                        .reversed_chars_at(selection_head)
 5909                        .collect::<String>();
 5910                    for (pair, enabled) in scope.brackets() {
 5911                        if enabled
 5912                            && pair.close
 5913                            && prev_chars.starts_with(pair.start.as_str())
 5914                            && next_chars.starts_with(pair.end.as_str())
 5915                        {
 5916                            bracket_pair = Some(pair.clone());
 5917                            break;
 5918                        }
 5919                    }
 5920                    if let Some(pair) = bracket_pair {
 5921                        let start = snapshot.anchor_after(selection_head);
 5922                        let end = snapshot.anchor_after(selection_head);
 5923                        self.autoclose_regions.push(AutocloseRegion {
 5924                            selection_id: selection.id,
 5925                            range: start..end,
 5926                            pair,
 5927                        });
 5928                    }
 5929                }
 5930            }
 5931        }
 5932        Ok(())
 5933    }
 5934
 5935    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5936        self.move_to_snippet_tabstop(Bias::Right, cx)
 5937    }
 5938
 5939    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5940        self.move_to_snippet_tabstop(Bias::Left, cx)
 5941    }
 5942
 5943    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5944        if let Some(mut snippet) = self.snippet_stack.pop() {
 5945            match bias {
 5946                Bias::Left => {
 5947                    if snippet.active_index > 0 {
 5948                        snippet.active_index -= 1;
 5949                    } else {
 5950                        self.snippet_stack.push(snippet);
 5951                        return false;
 5952                    }
 5953                }
 5954                Bias::Right => {
 5955                    if snippet.active_index + 1 < snippet.ranges.len() {
 5956                        snippet.active_index += 1;
 5957                    } else {
 5958                        self.snippet_stack.push(snippet);
 5959                        return false;
 5960                    }
 5961                }
 5962            }
 5963            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5964                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5965                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5966                });
 5967
 5968                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5969                    if let Some(selection) = current_ranges.first() {
 5970                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5971                    }
 5972                }
 5973
 5974                // If snippet state is not at the last tabstop, push it back on the stack
 5975                if snippet.active_index + 1 < snippet.ranges.len() {
 5976                    self.snippet_stack.push(snippet);
 5977                }
 5978                return true;
 5979            }
 5980        }
 5981
 5982        false
 5983    }
 5984
 5985    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5986        self.transact(cx, |this, cx| {
 5987            this.select_all(&SelectAll, cx);
 5988            this.insert("", cx);
 5989        });
 5990    }
 5991
 5992    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5993        self.transact(cx, |this, cx| {
 5994            this.select_autoclose_pair(cx);
 5995            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5996            if !this.linked_edit_ranges.is_empty() {
 5997                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5998                let snapshot = this.buffer.read(cx).snapshot(cx);
 5999
 6000                for selection in selections.iter() {
 6001                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6002                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6003                    if selection_start.buffer_id != selection_end.buffer_id {
 6004                        continue;
 6005                    }
 6006                    if let Some(ranges) =
 6007                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6008                    {
 6009                        for (buffer, entries) in ranges {
 6010                            linked_ranges.entry(buffer).or_default().extend(entries);
 6011                        }
 6012                    }
 6013                }
 6014            }
 6015
 6016            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6017            if !this.selections.line_mode {
 6018                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6019                for selection in &mut selections {
 6020                    if selection.is_empty() {
 6021                        let old_head = selection.head();
 6022                        let mut new_head =
 6023                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6024                                .to_point(&display_map);
 6025                        if let Some((buffer, line_buffer_range)) = display_map
 6026                            .buffer_snapshot
 6027                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6028                        {
 6029                            let indent_size =
 6030                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6031                            let indent_len = match indent_size.kind {
 6032                                IndentKind::Space => {
 6033                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6034                                }
 6035                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6036                            };
 6037                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6038                                let indent_len = indent_len.get();
 6039                                new_head = cmp::min(
 6040                                    new_head,
 6041                                    MultiBufferPoint::new(
 6042                                        old_head.row,
 6043                                        ((old_head.column - 1) / indent_len) * indent_len,
 6044                                    ),
 6045                                );
 6046                            }
 6047                        }
 6048
 6049                        selection.set_head(new_head, SelectionGoal::None);
 6050                    }
 6051                }
 6052            }
 6053
 6054            this.signature_help_state.set_backspace_pressed(true);
 6055            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6056            this.insert("", cx);
 6057            let empty_str: Arc<str> = Arc::from("");
 6058            for (buffer, edits) in linked_ranges {
 6059                let snapshot = buffer.read(cx).snapshot();
 6060                use text::ToPoint as TP;
 6061
 6062                let edits = edits
 6063                    .into_iter()
 6064                    .map(|range| {
 6065                        let end_point = TP::to_point(&range.end, &snapshot);
 6066                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6067
 6068                        if end_point == start_point {
 6069                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6070                                .saturating_sub(1);
 6071                            start_point = TP::to_point(&offset, &snapshot);
 6072                        };
 6073
 6074                        (start_point..end_point, empty_str.clone())
 6075                    })
 6076                    .sorted_by_key(|(range, _)| range.start)
 6077                    .collect::<Vec<_>>();
 6078                buffer.update(cx, |this, cx| {
 6079                    this.edit(edits, None, cx);
 6080                })
 6081            }
 6082            this.refresh_inline_completion(true, false, cx);
 6083            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6084        });
 6085    }
 6086
 6087    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6088        self.transact(cx, |this, cx| {
 6089            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6090                let line_mode = s.line_mode;
 6091                s.move_with(|map, selection| {
 6092                    if selection.is_empty() && !line_mode {
 6093                        let cursor = movement::right(map, selection.head());
 6094                        selection.end = cursor;
 6095                        selection.reversed = true;
 6096                        selection.goal = SelectionGoal::None;
 6097                    }
 6098                })
 6099            });
 6100            this.insert("", cx);
 6101            this.refresh_inline_completion(true, false, cx);
 6102        });
 6103    }
 6104
 6105    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6106        if self.move_to_prev_snippet_tabstop(cx) {
 6107            return;
 6108        }
 6109
 6110        self.outdent(&Outdent, cx);
 6111    }
 6112
 6113    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6114        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6115            return;
 6116        }
 6117
 6118        let mut selections = self.selections.all_adjusted(cx);
 6119        let buffer = self.buffer.read(cx);
 6120        let snapshot = buffer.snapshot(cx);
 6121        let rows_iter = selections.iter().map(|s| s.head().row);
 6122        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6123
 6124        let mut edits = Vec::new();
 6125        let mut prev_edited_row = 0;
 6126        let mut row_delta = 0;
 6127        for selection in &mut selections {
 6128            if selection.start.row != prev_edited_row {
 6129                row_delta = 0;
 6130            }
 6131            prev_edited_row = selection.end.row;
 6132
 6133            // If the selection is non-empty, then increase the indentation of the selected lines.
 6134            if !selection.is_empty() {
 6135                row_delta =
 6136                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6137                continue;
 6138            }
 6139
 6140            // If the selection is empty and the cursor is in the leading whitespace before the
 6141            // suggested indentation, then auto-indent the line.
 6142            let cursor = selection.head();
 6143            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6144            if let Some(suggested_indent) =
 6145                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6146            {
 6147                if cursor.column < suggested_indent.len
 6148                    && cursor.column <= current_indent.len
 6149                    && current_indent.len <= suggested_indent.len
 6150                {
 6151                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6152                    selection.end = selection.start;
 6153                    if row_delta == 0 {
 6154                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6155                            cursor.row,
 6156                            current_indent,
 6157                            suggested_indent,
 6158                        ));
 6159                        row_delta = suggested_indent.len - current_indent.len;
 6160                    }
 6161                    continue;
 6162                }
 6163            }
 6164
 6165            // Otherwise, insert a hard or soft tab.
 6166            let settings = buffer.settings_at(cursor, cx);
 6167            let tab_size = if settings.hard_tabs {
 6168                IndentSize::tab()
 6169            } else {
 6170                let tab_size = settings.tab_size.get();
 6171                let char_column = snapshot
 6172                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6173                    .flat_map(str::chars)
 6174                    .count()
 6175                    + row_delta as usize;
 6176                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6177                IndentSize::spaces(chars_to_next_tab_stop)
 6178            };
 6179            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6180            selection.end = selection.start;
 6181            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6182            row_delta += tab_size.len;
 6183        }
 6184
 6185        self.transact(cx, |this, cx| {
 6186            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6187            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6188            this.refresh_inline_completion(true, false, cx);
 6189        });
 6190    }
 6191
 6192    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6193        if self.read_only(cx) {
 6194            return;
 6195        }
 6196        let mut selections = self.selections.all::<Point>(cx);
 6197        let mut prev_edited_row = 0;
 6198        let mut row_delta = 0;
 6199        let mut edits = Vec::new();
 6200        let buffer = self.buffer.read(cx);
 6201        let snapshot = buffer.snapshot(cx);
 6202        for selection in &mut selections {
 6203            if selection.start.row != prev_edited_row {
 6204                row_delta = 0;
 6205            }
 6206            prev_edited_row = selection.end.row;
 6207
 6208            row_delta =
 6209                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6210        }
 6211
 6212        self.transact(cx, |this, cx| {
 6213            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6214            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6215        });
 6216    }
 6217
 6218    fn indent_selection(
 6219        buffer: &MultiBuffer,
 6220        snapshot: &MultiBufferSnapshot,
 6221        selection: &mut Selection<Point>,
 6222        edits: &mut Vec<(Range<Point>, String)>,
 6223        delta_for_start_row: u32,
 6224        cx: &AppContext,
 6225    ) -> u32 {
 6226        let settings = buffer.settings_at(selection.start, cx);
 6227        let tab_size = settings.tab_size.get();
 6228        let indent_kind = if settings.hard_tabs {
 6229            IndentKind::Tab
 6230        } else {
 6231            IndentKind::Space
 6232        };
 6233        let mut start_row = selection.start.row;
 6234        let mut end_row = selection.end.row + 1;
 6235
 6236        // If a selection ends at the beginning of a line, don't indent
 6237        // that last line.
 6238        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6239            end_row -= 1;
 6240        }
 6241
 6242        // Avoid re-indenting a row that has already been indented by a
 6243        // previous selection, but still update this selection's column
 6244        // to reflect that indentation.
 6245        if delta_for_start_row > 0 {
 6246            start_row += 1;
 6247            selection.start.column += delta_for_start_row;
 6248            if selection.end.row == selection.start.row {
 6249                selection.end.column += delta_for_start_row;
 6250            }
 6251        }
 6252
 6253        let mut delta_for_end_row = 0;
 6254        let has_multiple_rows = start_row + 1 != end_row;
 6255        for row in start_row..end_row {
 6256            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6257            let indent_delta = match (current_indent.kind, indent_kind) {
 6258                (IndentKind::Space, IndentKind::Space) => {
 6259                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6260                    IndentSize::spaces(columns_to_next_tab_stop)
 6261                }
 6262                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6263                (_, IndentKind::Tab) => IndentSize::tab(),
 6264            };
 6265
 6266            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6267                0
 6268            } else {
 6269                selection.start.column
 6270            };
 6271            let row_start = Point::new(row, start);
 6272            edits.push((
 6273                row_start..row_start,
 6274                indent_delta.chars().collect::<String>(),
 6275            ));
 6276
 6277            // Update this selection's endpoints to reflect the indentation.
 6278            if row == selection.start.row {
 6279                selection.start.column += indent_delta.len;
 6280            }
 6281            if row == selection.end.row {
 6282                selection.end.column += indent_delta.len;
 6283                delta_for_end_row = indent_delta.len;
 6284            }
 6285        }
 6286
 6287        if selection.start.row == selection.end.row {
 6288            delta_for_start_row + delta_for_end_row
 6289        } else {
 6290            delta_for_end_row
 6291        }
 6292    }
 6293
 6294    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6295        if self.read_only(cx) {
 6296            return;
 6297        }
 6298        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6299        let selections = self.selections.all::<Point>(cx);
 6300        let mut deletion_ranges = Vec::new();
 6301        let mut last_outdent = None;
 6302        {
 6303            let buffer = self.buffer.read(cx);
 6304            let snapshot = buffer.snapshot(cx);
 6305            for selection in &selections {
 6306                let settings = buffer.settings_at(selection.start, cx);
 6307                let tab_size = settings.tab_size.get();
 6308                let mut rows = selection.spanned_rows(false, &display_map);
 6309
 6310                // Avoid re-outdenting a row that has already been outdented by a
 6311                // previous selection.
 6312                if let Some(last_row) = last_outdent {
 6313                    if last_row == rows.start {
 6314                        rows.start = rows.start.next_row();
 6315                    }
 6316                }
 6317                let has_multiple_rows = rows.len() > 1;
 6318                for row in rows.iter_rows() {
 6319                    let indent_size = snapshot.indent_size_for_line(row);
 6320                    if indent_size.len > 0 {
 6321                        let deletion_len = match indent_size.kind {
 6322                            IndentKind::Space => {
 6323                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6324                                if columns_to_prev_tab_stop == 0 {
 6325                                    tab_size
 6326                                } else {
 6327                                    columns_to_prev_tab_stop
 6328                                }
 6329                            }
 6330                            IndentKind::Tab => 1,
 6331                        };
 6332                        let start = if has_multiple_rows
 6333                            || deletion_len > selection.start.column
 6334                            || indent_size.len < selection.start.column
 6335                        {
 6336                            0
 6337                        } else {
 6338                            selection.start.column - deletion_len
 6339                        };
 6340                        deletion_ranges.push(
 6341                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6342                        );
 6343                        last_outdent = Some(row);
 6344                    }
 6345                }
 6346            }
 6347        }
 6348
 6349        self.transact(cx, |this, cx| {
 6350            this.buffer.update(cx, |buffer, cx| {
 6351                let empty_str: Arc<str> = Arc::default();
 6352                buffer.edit(
 6353                    deletion_ranges
 6354                        .into_iter()
 6355                        .map(|range| (range, empty_str.clone())),
 6356                    None,
 6357                    cx,
 6358                );
 6359            });
 6360            let selections = this.selections.all::<usize>(cx);
 6361            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6362        });
 6363    }
 6364
 6365    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 6366        if self.read_only(cx) {
 6367            return;
 6368        }
 6369        let selections = self
 6370            .selections
 6371            .all::<usize>(cx)
 6372            .into_iter()
 6373            .map(|s| s.range());
 6374
 6375        self.transact(cx, |this, cx| {
 6376            this.buffer.update(cx, |buffer, cx| {
 6377                buffer.autoindent_ranges(selections, cx);
 6378            });
 6379            let selections = this.selections.all::<usize>(cx);
 6380            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6381        });
 6382    }
 6383
 6384    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6385        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6386        let selections = self.selections.all::<Point>(cx);
 6387
 6388        let mut new_cursors = Vec::new();
 6389        let mut edit_ranges = Vec::new();
 6390        let mut selections = selections.iter().peekable();
 6391        while let Some(selection) = selections.next() {
 6392            let mut rows = selection.spanned_rows(false, &display_map);
 6393            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6394
 6395            // Accumulate contiguous regions of rows that we want to delete.
 6396            while let Some(next_selection) = selections.peek() {
 6397                let next_rows = next_selection.spanned_rows(false, &display_map);
 6398                if next_rows.start <= rows.end {
 6399                    rows.end = next_rows.end;
 6400                    selections.next().unwrap();
 6401                } else {
 6402                    break;
 6403                }
 6404            }
 6405
 6406            let buffer = &display_map.buffer_snapshot;
 6407            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6408            let edit_end;
 6409            let cursor_buffer_row;
 6410            if buffer.max_point().row >= rows.end.0 {
 6411                // If there's a line after the range, delete the \n from the end of the row range
 6412                // and position the cursor on the next line.
 6413                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6414                cursor_buffer_row = rows.end;
 6415            } else {
 6416                // If there isn't a line after the range, delete the \n from the line before the
 6417                // start of the row range and position the cursor there.
 6418                edit_start = edit_start.saturating_sub(1);
 6419                edit_end = buffer.len();
 6420                cursor_buffer_row = rows.start.previous_row();
 6421            }
 6422
 6423            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6424            *cursor.column_mut() =
 6425                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6426
 6427            new_cursors.push((
 6428                selection.id,
 6429                buffer.anchor_after(cursor.to_point(&display_map)),
 6430            ));
 6431            edit_ranges.push(edit_start..edit_end);
 6432        }
 6433
 6434        self.transact(cx, |this, cx| {
 6435            let buffer = this.buffer.update(cx, |buffer, cx| {
 6436                let empty_str: Arc<str> = Arc::default();
 6437                buffer.edit(
 6438                    edit_ranges
 6439                        .into_iter()
 6440                        .map(|range| (range, empty_str.clone())),
 6441                    None,
 6442                    cx,
 6443                );
 6444                buffer.snapshot(cx)
 6445            });
 6446            let new_selections = new_cursors
 6447                .into_iter()
 6448                .map(|(id, cursor)| {
 6449                    let cursor = cursor.to_point(&buffer);
 6450                    Selection {
 6451                        id,
 6452                        start: cursor,
 6453                        end: cursor,
 6454                        reversed: false,
 6455                        goal: SelectionGoal::None,
 6456                    }
 6457                })
 6458                .collect();
 6459
 6460            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6461                s.select(new_selections);
 6462            });
 6463        });
 6464    }
 6465
 6466    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6467        if self.read_only(cx) {
 6468            return;
 6469        }
 6470        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6471        for selection in self.selections.all::<Point>(cx) {
 6472            let start = MultiBufferRow(selection.start.row);
 6473            // Treat single line selections as if they include the next line. Otherwise this action
 6474            // would do nothing for single line selections individual cursors.
 6475            let end = if selection.start.row == selection.end.row {
 6476                MultiBufferRow(selection.start.row + 1)
 6477            } else {
 6478                MultiBufferRow(selection.end.row)
 6479            };
 6480
 6481            if let Some(last_row_range) = row_ranges.last_mut() {
 6482                if start <= last_row_range.end {
 6483                    last_row_range.end = end;
 6484                    continue;
 6485                }
 6486            }
 6487            row_ranges.push(start..end);
 6488        }
 6489
 6490        let snapshot = self.buffer.read(cx).snapshot(cx);
 6491        let mut cursor_positions = Vec::new();
 6492        for row_range in &row_ranges {
 6493            let anchor = snapshot.anchor_before(Point::new(
 6494                row_range.end.previous_row().0,
 6495                snapshot.line_len(row_range.end.previous_row()),
 6496            ));
 6497            cursor_positions.push(anchor..anchor);
 6498        }
 6499
 6500        self.transact(cx, |this, cx| {
 6501            for row_range in row_ranges.into_iter().rev() {
 6502                for row in row_range.iter_rows().rev() {
 6503                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6504                    let next_line_row = row.next_row();
 6505                    let indent = snapshot.indent_size_for_line(next_line_row);
 6506                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6507
 6508                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6509                        " "
 6510                    } else {
 6511                        ""
 6512                    };
 6513
 6514                    this.buffer.update(cx, |buffer, cx| {
 6515                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6516                    });
 6517                }
 6518            }
 6519
 6520            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6521                s.select_anchor_ranges(cursor_positions)
 6522            });
 6523        });
 6524    }
 6525
 6526    pub fn sort_lines_case_sensitive(
 6527        &mut self,
 6528        _: &SortLinesCaseSensitive,
 6529        cx: &mut ViewContext<Self>,
 6530    ) {
 6531        self.manipulate_lines(cx, |lines| lines.sort())
 6532    }
 6533
 6534    pub fn sort_lines_case_insensitive(
 6535        &mut self,
 6536        _: &SortLinesCaseInsensitive,
 6537        cx: &mut ViewContext<Self>,
 6538    ) {
 6539        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6540    }
 6541
 6542    pub fn unique_lines_case_insensitive(
 6543        &mut self,
 6544        _: &UniqueLinesCaseInsensitive,
 6545        cx: &mut ViewContext<Self>,
 6546    ) {
 6547        self.manipulate_lines(cx, |lines| {
 6548            let mut seen = HashSet::default();
 6549            lines.retain(|line| seen.insert(line.to_lowercase()));
 6550        })
 6551    }
 6552
 6553    pub fn unique_lines_case_sensitive(
 6554        &mut self,
 6555        _: &UniqueLinesCaseSensitive,
 6556        cx: &mut ViewContext<Self>,
 6557    ) {
 6558        self.manipulate_lines(cx, |lines| {
 6559            let mut seen = HashSet::default();
 6560            lines.retain(|line| seen.insert(*line));
 6561        })
 6562    }
 6563
 6564    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6565        let mut revert_changes = HashMap::default();
 6566        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6567        for hunk in hunks_for_rows(
 6568            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6569            &multi_buffer_snapshot,
 6570        ) {
 6571            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6572        }
 6573        if !revert_changes.is_empty() {
 6574            self.transact(cx, |editor, cx| {
 6575                editor.revert(revert_changes, cx);
 6576            });
 6577        }
 6578    }
 6579
 6580    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6581        let Some(project) = self.project.clone() else {
 6582            return;
 6583        };
 6584        self.reload(project, cx).detach_and_notify_err(cx);
 6585    }
 6586
 6587    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6588        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6589        if !revert_changes.is_empty() {
 6590            self.transact(cx, |editor, cx| {
 6591                editor.revert(revert_changes, cx);
 6592            });
 6593        }
 6594    }
 6595
 6596    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6597        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6598            let project_path = buffer.read(cx).project_path(cx)?;
 6599            let project = self.project.as_ref()?.read(cx);
 6600            let entry = project.entry_for_path(&project_path, cx)?;
 6601            let parent = match &entry.canonical_path {
 6602                Some(canonical_path) => canonical_path.to_path_buf(),
 6603                None => project.absolute_path(&project_path, cx)?,
 6604            }
 6605            .parent()?
 6606            .to_path_buf();
 6607            Some(parent)
 6608        }) {
 6609            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6610        }
 6611    }
 6612
 6613    fn gather_revert_changes(
 6614        &mut self,
 6615        selections: &[Selection<Anchor>],
 6616        cx: &mut ViewContext<'_, Editor>,
 6617    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6618        let mut revert_changes = HashMap::default();
 6619        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6620        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6621            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6622        }
 6623        revert_changes
 6624    }
 6625
 6626    pub fn prepare_revert_change(
 6627        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6628        multi_buffer: &Model<MultiBuffer>,
 6629        hunk: &MultiBufferDiffHunk,
 6630        cx: &AppContext,
 6631    ) -> Option<()> {
 6632        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6633        let buffer = buffer.read(cx);
 6634        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6635        let buffer_snapshot = buffer.snapshot();
 6636        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6637        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6638            probe
 6639                .0
 6640                .start
 6641                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6642                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6643        }) {
 6644            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6645            Some(())
 6646        } else {
 6647            None
 6648        }
 6649    }
 6650
 6651    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6652        self.manipulate_lines(cx, |lines| lines.reverse())
 6653    }
 6654
 6655    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6656        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6657    }
 6658
 6659    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6660    where
 6661        Fn: FnMut(&mut Vec<&str>),
 6662    {
 6663        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6664        let buffer = self.buffer.read(cx).snapshot(cx);
 6665
 6666        let mut edits = Vec::new();
 6667
 6668        let selections = self.selections.all::<Point>(cx);
 6669        let mut selections = selections.iter().peekable();
 6670        let mut contiguous_row_selections = Vec::new();
 6671        let mut new_selections = Vec::new();
 6672        let mut added_lines = 0;
 6673        let mut removed_lines = 0;
 6674
 6675        while let Some(selection) = selections.next() {
 6676            let (start_row, end_row) = consume_contiguous_rows(
 6677                &mut contiguous_row_selections,
 6678                selection,
 6679                &display_map,
 6680                &mut selections,
 6681            );
 6682
 6683            let start_point = Point::new(start_row.0, 0);
 6684            let end_point = Point::new(
 6685                end_row.previous_row().0,
 6686                buffer.line_len(end_row.previous_row()),
 6687            );
 6688            let text = buffer
 6689                .text_for_range(start_point..end_point)
 6690                .collect::<String>();
 6691
 6692            let mut lines = text.split('\n').collect_vec();
 6693
 6694            let lines_before = lines.len();
 6695            callback(&mut lines);
 6696            let lines_after = lines.len();
 6697
 6698            edits.push((start_point..end_point, lines.join("\n")));
 6699
 6700            // Selections must change based on added and removed line count
 6701            let start_row =
 6702                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6703            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6704            new_selections.push(Selection {
 6705                id: selection.id,
 6706                start: start_row,
 6707                end: end_row,
 6708                goal: SelectionGoal::None,
 6709                reversed: selection.reversed,
 6710            });
 6711
 6712            if lines_after > lines_before {
 6713                added_lines += lines_after - lines_before;
 6714            } else if lines_before > lines_after {
 6715                removed_lines += lines_before - lines_after;
 6716            }
 6717        }
 6718
 6719        self.transact(cx, |this, cx| {
 6720            let buffer = this.buffer.update(cx, |buffer, cx| {
 6721                buffer.edit(edits, None, cx);
 6722                buffer.snapshot(cx)
 6723            });
 6724
 6725            // Recalculate offsets on newly edited buffer
 6726            let new_selections = new_selections
 6727                .iter()
 6728                .map(|s| {
 6729                    let start_point = Point::new(s.start.0, 0);
 6730                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6731                    Selection {
 6732                        id: s.id,
 6733                        start: buffer.point_to_offset(start_point),
 6734                        end: buffer.point_to_offset(end_point),
 6735                        goal: s.goal,
 6736                        reversed: s.reversed,
 6737                    }
 6738                })
 6739                .collect();
 6740
 6741            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6742                s.select(new_selections);
 6743            });
 6744
 6745            this.request_autoscroll(Autoscroll::fit(), cx);
 6746        });
 6747    }
 6748
 6749    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6750        self.manipulate_text(cx, |text| text.to_uppercase())
 6751    }
 6752
 6753    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6754        self.manipulate_text(cx, |text| text.to_lowercase())
 6755    }
 6756
 6757    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6758        self.manipulate_text(cx, |text| {
 6759            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6760            // https://github.com/rutrum/convert-case/issues/16
 6761            text.split('\n')
 6762                .map(|line| line.to_case(Case::Title))
 6763                .join("\n")
 6764        })
 6765    }
 6766
 6767    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6768        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6769    }
 6770
 6771    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6772        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6773    }
 6774
 6775    pub fn convert_to_upper_camel_case(
 6776        &mut self,
 6777        _: &ConvertToUpperCamelCase,
 6778        cx: &mut ViewContext<Self>,
 6779    ) {
 6780        self.manipulate_text(cx, |text| {
 6781            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6782            // https://github.com/rutrum/convert-case/issues/16
 6783            text.split('\n')
 6784                .map(|line| line.to_case(Case::UpperCamel))
 6785                .join("\n")
 6786        })
 6787    }
 6788
 6789    pub fn convert_to_lower_camel_case(
 6790        &mut self,
 6791        _: &ConvertToLowerCamelCase,
 6792        cx: &mut ViewContext<Self>,
 6793    ) {
 6794        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6795    }
 6796
 6797    pub fn convert_to_opposite_case(
 6798        &mut self,
 6799        _: &ConvertToOppositeCase,
 6800        cx: &mut ViewContext<Self>,
 6801    ) {
 6802        self.manipulate_text(cx, |text| {
 6803            text.chars()
 6804                .fold(String::with_capacity(text.len()), |mut t, c| {
 6805                    if c.is_uppercase() {
 6806                        t.extend(c.to_lowercase());
 6807                    } else {
 6808                        t.extend(c.to_uppercase());
 6809                    }
 6810                    t
 6811                })
 6812        })
 6813    }
 6814
 6815    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6816    where
 6817        Fn: FnMut(&str) -> String,
 6818    {
 6819        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6820        let buffer = self.buffer.read(cx).snapshot(cx);
 6821
 6822        let mut new_selections = Vec::new();
 6823        let mut edits = Vec::new();
 6824        let mut selection_adjustment = 0i32;
 6825
 6826        for selection in self.selections.all::<usize>(cx) {
 6827            let selection_is_empty = selection.is_empty();
 6828
 6829            let (start, end) = if selection_is_empty {
 6830                let word_range = movement::surrounding_word(
 6831                    &display_map,
 6832                    selection.start.to_display_point(&display_map),
 6833                );
 6834                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6835                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6836                (start, end)
 6837            } else {
 6838                (selection.start, selection.end)
 6839            };
 6840
 6841            let text = buffer.text_for_range(start..end).collect::<String>();
 6842            let old_length = text.len() as i32;
 6843            let text = callback(&text);
 6844
 6845            new_selections.push(Selection {
 6846                start: (start as i32 - selection_adjustment) as usize,
 6847                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6848                goal: SelectionGoal::None,
 6849                ..selection
 6850            });
 6851
 6852            selection_adjustment += old_length - text.len() as i32;
 6853
 6854            edits.push((start..end, text));
 6855        }
 6856
 6857        self.transact(cx, |this, cx| {
 6858            this.buffer.update(cx, |buffer, cx| {
 6859                buffer.edit(edits, None, cx);
 6860            });
 6861
 6862            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6863                s.select(new_selections);
 6864            });
 6865
 6866            this.request_autoscroll(Autoscroll::fit(), cx);
 6867        });
 6868    }
 6869
 6870    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6871        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6872        let buffer = &display_map.buffer_snapshot;
 6873        let selections = self.selections.all::<Point>(cx);
 6874
 6875        let mut edits = Vec::new();
 6876        let mut selections_iter = selections.iter().peekable();
 6877        while let Some(selection) = selections_iter.next() {
 6878            // Avoid duplicating the same lines twice.
 6879            let mut rows = selection.spanned_rows(false, &display_map);
 6880
 6881            while let Some(next_selection) = selections_iter.peek() {
 6882                let next_rows = next_selection.spanned_rows(false, &display_map);
 6883                if next_rows.start < rows.end {
 6884                    rows.end = next_rows.end;
 6885                    selections_iter.next().unwrap();
 6886                } else {
 6887                    break;
 6888                }
 6889            }
 6890
 6891            // Copy the text from the selected row region and splice it either at the start
 6892            // or end of the region.
 6893            let start = Point::new(rows.start.0, 0);
 6894            let end = Point::new(
 6895                rows.end.previous_row().0,
 6896                buffer.line_len(rows.end.previous_row()),
 6897            );
 6898            let text = buffer
 6899                .text_for_range(start..end)
 6900                .chain(Some("\n"))
 6901                .collect::<String>();
 6902            let insert_location = if upwards {
 6903                Point::new(rows.end.0, 0)
 6904            } else {
 6905                start
 6906            };
 6907            edits.push((insert_location..insert_location, text));
 6908        }
 6909
 6910        self.transact(cx, |this, cx| {
 6911            this.buffer.update(cx, |buffer, cx| {
 6912                buffer.edit(edits, None, cx);
 6913            });
 6914
 6915            this.request_autoscroll(Autoscroll::fit(), cx);
 6916        });
 6917    }
 6918
 6919    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6920        self.duplicate_line(true, cx);
 6921    }
 6922
 6923    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6924        self.duplicate_line(false, cx);
 6925    }
 6926
 6927    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6928        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6929        let buffer = self.buffer.read(cx).snapshot(cx);
 6930
 6931        let mut edits = Vec::new();
 6932        let mut unfold_ranges = Vec::new();
 6933        let mut refold_creases = Vec::new();
 6934
 6935        let selections = self.selections.all::<Point>(cx);
 6936        let mut selections = selections.iter().peekable();
 6937        let mut contiguous_row_selections = Vec::new();
 6938        let mut new_selections = Vec::new();
 6939
 6940        while let Some(selection) = selections.next() {
 6941            // Find all the selections that span a contiguous row range
 6942            let (start_row, end_row) = consume_contiguous_rows(
 6943                &mut contiguous_row_selections,
 6944                selection,
 6945                &display_map,
 6946                &mut selections,
 6947            );
 6948
 6949            // Move the text spanned by the row range to be before the line preceding the row range
 6950            if start_row.0 > 0 {
 6951                let range_to_move = Point::new(
 6952                    start_row.previous_row().0,
 6953                    buffer.line_len(start_row.previous_row()),
 6954                )
 6955                    ..Point::new(
 6956                        end_row.previous_row().0,
 6957                        buffer.line_len(end_row.previous_row()),
 6958                    );
 6959                let insertion_point = display_map
 6960                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6961                    .0;
 6962
 6963                // Don't move lines across excerpts
 6964                if buffer
 6965                    .excerpt_boundaries_in_range((
 6966                        Bound::Excluded(insertion_point),
 6967                        Bound::Included(range_to_move.end),
 6968                    ))
 6969                    .next()
 6970                    .is_none()
 6971                {
 6972                    let text = buffer
 6973                        .text_for_range(range_to_move.clone())
 6974                        .flat_map(|s| s.chars())
 6975                        .skip(1)
 6976                        .chain(['\n'])
 6977                        .collect::<String>();
 6978
 6979                    edits.push((
 6980                        buffer.anchor_after(range_to_move.start)
 6981                            ..buffer.anchor_before(range_to_move.end),
 6982                        String::new(),
 6983                    ));
 6984                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6985                    edits.push((insertion_anchor..insertion_anchor, text));
 6986
 6987                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6988
 6989                    // Move selections up
 6990                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6991                        |mut selection| {
 6992                            selection.start.row -= row_delta;
 6993                            selection.end.row -= row_delta;
 6994                            selection
 6995                        },
 6996                    ));
 6997
 6998                    // Move folds up
 6999                    unfold_ranges.push(range_to_move.clone());
 7000                    for fold in display_map.folds_in_range(
 7001                        buffer.anchor_before(range_to_move.start)
 7002                            ..buffer.anchor_after(range_to_move.end),
 7003                    ) {
 7004                        let mut start = fold.range.start.to_point(&buffer);
 7005                        let mut end = fold.range.end.to_point(&buffer);
 7006                        start.row -= row_delta;
 7007                        end.row -= row_delta;
 7008                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7009                    }
 7010                }
 7011            }
 7012
 7013            // If we didn't move line(s), preserve the existing selections
 7014            new_selections.append(&mut contiguous_row_selections);
 7015        }
 7016
 7017        self.transact(cx, |this, cx| {
 7018            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7019            this.buffer.update(cx, |buffer, cx| {
 7020                for (range, text) in edits {
 7021                    buffer.edit([(range, text)], None, cx);
 7022                }
 7023            });
 7024            this.fold_creases(refold_creases, true, cx);
 7025            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7026                s.select(new_selections);
 7027            })
 7028        });
 7029    }
 7030
 7031    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 7032        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7033        let buffer = self.buffer.read(cx).snapshot(cx);
 7034
 7035        let mut edits = Vec::new();
 7036        let mut unfold_ranges = Vec::new();
 7037        let mut refold_creases = Vec::new();
 7038
 7039        let selections = self.selections.all::<Point>(cx);
 7040        let mut selections = selections.iter().peekable();
 7041        let mut contiguous_row_selections = Vec::new();
 7042        let mut new_selections = Vec::new();
 7043
 7044        while let Some(selection) = selections.next() {
 7045            // Find all the selections that span a contiguous row range
 7046            let (start_row, end_row) = consume_contiguous_rows(
 7047                &mut contiguous_row_selections,
 7048                selection,
 7049                &display_map,
 7050                &mut selections,
 7051            );
 7052
 7053            // Move the text spanned by the row range to be after the last line of the row range
 7054            if end_row.0 <= buffer.max_point().row {
 7055                let range_to_move =
 7056                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7057                let insertion_point = display_map
 7058                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7059                    .0;
 7060
 7061                // Don't move lines across excerpt boundaries
 7062                if buffer
 7063                    .excerpt_boundaries_in_range((
 7064                        Bound::Excluded(range_to_move.start),
 7065                        Bound::Included(insertion_point),
 7066                    ))
 7067                    .next()
 7068                    .is_none()
 7069                {
 7070                    let mut text = String::from("\n");
 7071                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7072                    text.pop(); // Drop trailing newline
 7073                    edits.push((
 7074                        buffer.anchor_after(range_to_move.start)
 7075                            ..buffer.anchor_before(range_to_move.end),
 7076                        String::new(),
 7077                    ));
 7078                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7079                    edits.push((insertion_anchor..insertion_anchor, text));
 7080
 7081                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7082
 7083                    // Move selections down
 7084                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7085                        |mut selection| {
 7086                            selection.start.row += row_delta;
 7087                            selection.end.row += row_delta;
 7088                            selection
 7089                        },
 7090                    ));
 7091
 7092                    // Move folds down
 7093                    unfold_ranges.push(range_to_move.clone());
 7094                    for fold in display_map.folds_in_range(
 7095                        buffer.anchor_before(range_to_move.start)
 7096                            ..buffer.anchor_after(range_to_move.end),
 7097                    ) {
 7098                        let mut start = fold.range.start.to_point(&buffer);
 7099                        let mut end = fold.range.end.to_point(&buffer);
 7100                        start.row += row_delta;
 7101                        end.row += row_delta;
 7102                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7103                    }
 7104                }
 7105            }
 7106
 7107            // If we didn't move line(s), preserve the existing selections
 7108            new_selections.append(&mut contiguous_row_selections);
 7109        }
 7110
 7111        self.transact(cx, |this, cx| {
 7112            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7113            this.buffer.update(cx, |buffer, cx| {
 7114                for (range, text) in edits {
 7115                    buffer.edit([(range, text)], None, cx);
 7116                }
 7117            });
 7118            this.fold_creases(refold_creases, true, cx);
 7119            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7120        });
 7121    }
 7122
 7123    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7124        let text_layout_details = &self.text_layout_details(cx);
 7125        self.transact(cx, |this, cx| {
 7126            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7127                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7128                let line_mode = s.line_mode;
 7129                s.move_with(|display_map, selection| {
 7130                    if !selection.is_empty() || line_mode {
 7131                        return;
 7132                    }
 7133
 7134                    let mut head = selection.head();
 7135                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7136                    if head.column() == display_map.line_len(head.row()) {
 7137                        transpose_offset = display_map
 7138                            .buffer_snapshot
 7139                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7140                    }
 7141
 7142                    if transpose_offset == 0 {
 7143                        return;
 7144                    }
 7145
 7146                    *head.column_mut() += 1;
 7147                    head = display_map.clip_point(head, Bias::Right);
 7148                    let goal = SelectionGoal::HorizontalPosition(
 7149                        display_map
 7150                            .x_for_display_point(head, text_layout_details)
 7151                            .into(),
 7152                    );
 7153                    selection.collapse_to(head, goal);
 7154
 7155                    let transpose_start = display_map
 7156                        .buffer_snapshot
 7157                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7158                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7159                        let transpose_end = display_map
 7160                            .buffer_snapshot
 7161                            .clip_offset(transpose_offset + 1, Bias::Right);
 7162                        if let Some(ch) =
 7163                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7164                        {
 7165                            edits.push((transpose_start..transpose_offset, String::new()));
 7166                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7167                        }
 7168                    }
 7169                });
 7170                edits
 7171            });
 7172            this.buffer
 7173                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7174            let selections = this.selections.all::<usize>(cx);
 7175            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7176                s.select(selections);
 7177            });
 7178        });
 7179    }
 7180
 7181    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7182        self.rewrap_impl(IsVimMode::No, cx)
 7183    }
 7184
 7185    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7186        let buffer = self.buffer.read(cx).snapshot(cx);
 7187        let selections = self.selections.all::<Point>(cx);
 7188        let mut selections = selections.iter().peekable();
 7189
 7190        let mut edits = Vec::new();
 7191        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7192
 7193        while let Some(selection) = selections.next() {
 7194            let mut start_row = selection.start.row;
 7195            let mut end_row = selection.end.row;
 7196
 7197            // Skip selections that overlap with a range that has already been rewrapped.
 7198            let selection_range = start_row..end_row;
 7199            if rewrapped_row_ranges
 7200                .iter()
 7201                .any(|range| range.overlaps(&selection_range))
 7202            {
 7203                continue;
 7204            }
 7205
 7206            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7207
 7208            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7209                match language_scope.language_name().0.as_ref() {
 7210                    "Markdown" | "Plain Text" => {
 7211                        should_rewrap = true;
 7212                    }
 7213                    _ => {}
 7214                }
 7215            }
 7216
 7217            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7218
 7219            // Since not all lines in the selection may be at the same indent
 7220            // level, choose the indent size that is the most common between all
 7221            // of the lines.
 7222            //
 7223            // If there is a tie, we use the deepest indent.
 7224            let (indent_size, indent_end) = {
 7225                let mut indent_size_occurrences = HashMap::default();
 7226                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7227
 7228                for row in start_row..=end_row {
 7229                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7230                    rows_by_indent_size.entry(indent).or_default().push(row);
 7231                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7232                }
 7233
 7234                let indent_size = indent_size_occurrences
 7235                    .into_iter()
 7236                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7237                    .map(|(indent, _)| indent)
 7238                    .unwrap_or_default();
 7239                let row = rows_by_indent_size[&indent_size][0];
 7240                let indent_end = Point::new(row, indent_size.len);
 7241
 7242                (indent_size, indent_end)
 7243            };
 7244
 7245            let mut line_prefix = indent_size.chars().collect::<String>();
 7246
 7247            if let Some(comment_prefix) =
 7248                buffer
 7249                    .language_scope_at(selection.head())
 7250                    .and_then(|language| {
 7251                        language
 7252                            .line_comment_prefixes()
 7253                            .iter()
 7254                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7255                            .cloned()
 7256                    })
 7257            {
 7258                line_prefix.push_str(&comment_prefix);
 7259                should_rewrap = true;
 7260            }
 7261
 7262            if !should_rewrap {
 7263                continue;
 7264            }
 7265
 7266            if selection.is_empty() {
 7267                'expand_upwards: while start_row > 0 {
 7268                    let prev_row = start_row - 1;
 7269                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7270                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7271                    {
 7272                        start_row = prev_row;
 7273                    } else {
 7274                        break 'expand_upwards;
 7275                    }
 7276                }
 7277
 7278                'expand_downwards: while end_row < buffer.max_point().row {
 7279                    let next_row = end_row + 1;
 7280                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7281                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7282                    {
 7283                        end_row = next_row;
 7284                    } else {
 7285                        break 'expand_downwards;
 7286                    }
 7287                }
 7288            }
 7289
 7290            let start = Point::new(start_row, 0);
 7291            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7292            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7293            let Some(lines_without_prefixes) = selection_text
 7294                .lines()
 7295                .map(|line| {
 7296                    line.strip_prefix(&line_prefix)
 7297                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7298                        .ok_or_else(|| {
 7299                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7300                        })
 7301                })
 7302                .collect::<Result<Vec<_>, _>>()
 7303                .log_err()
 7304            else {
 7305                continue;
 7306            };
 7307
 7308            let wrap_column = buffer
 7309                .settings_at(Point::new(start_row, 0), cx)
 7310                .preferred_line_length as usize;
 7311            let wrapped_text = wrap_with_prefix(
 7312                line_prefix,
 7313                lines_without_prefixes.join(" "),
 7314                wrap_column,
 7315                tab_size,
 7316            );
 7317
 7318            // TODO: should always use char-based diff while still supporting cursor behavior that
 7319            // matches vim.
 7320            let diff = match is_vim_mode {
 7321                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7322                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7323            };
 7324            let mut offset = start.to_offset(&buffer);
 7325            let mut moved_since_edit = true;
 7326
 7327            for change in diff.iter_all_changes() {
 7328                let value = change.value();
 7329                match change.tag() {
 7330                    ChangeTag::Equal => {
 7331                        offset += value.len();
 7332                        moved_since_edit = true;
 7333                    }
 7334                    ChangeTag::Delete => {
 7335                        let start = buffer.anchor_after(offset);
 7336                        let end = buffer.anchor_before(offset + value.len());
 7337
 7338                        if moved_since_edit {
 7339                            edits.push((start..end, String::new()));
 7340                        } else {
 7341                            edits.last_mut().unwrap().0.end = end;
 7342                        }
 7343
 7344                        offset += value.len();
 7345                        moved_since_edit = false;
 7346                    }
 7347                    ChangeTag::Insert => {
 7348                        if moved_since_edit {
 7349                            let anchor = buffer.anchor_after(offset);
 7350                            edits.push((anchor..anchor, value.to_string()));
 7351                        } else {
 7352                            edits.last_mut().unwrap().1.push_str(value);
 7353                        }
 7354
 7355                        moved_since_edit = false;
 7356                    }
 7357                }
 7358            }
 7359
 7360            rewrapped_row_ranges.push(start_row..=end_row);
 7361        }
 7362
 7363        self.buffer
 7364            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7365    }
 7366
 7367    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 7368        let mut text = String::new();
 7369        let buffer = self.buffer.read(cx).snapshot(cx);
 7370        let mut selections = self.selections.all::<Point>(cx);
 7371        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7372        {
 7373            let max_point = buffer.max_point();
 7374            let mut is_first = true;
 7375            for selection in &mut selections {
 7376                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7377                if is_entire_line {
 7378                    selection.start = Point::new(selection.start.row, 0);
 7379                    if !selection.is_empty() && selection.end.column == 0 {
 7380                        selection.end = cmp::min(max_point, selection.end);
 7381                    } else {
 7382                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7383                    }
 7384                    selection.goal = SelectionGoal::None;
 7385                }
 7386                if is_first {
 7387                    is_first = false;
 7388                } else {
 7389                    text += "\n";
 7390                }
 7391                let mut len = 0;
 7392                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7393                    text.push_str(chunk);
 7394                    len += chunk.len();
 7395                }
 7396                clipboard_selections.push(ClipboardSelection {
 7397                    len,
 7398                    is_entire_line,
 7399                    first_line_indent: buffer
 7400                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7401                        .len,
 7402                });
 7403            }
 7404        }
 7405
 7406        self.transact(cx, |this, cx| {
 7407            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7408                s.select(selections);
 7409            });
 7410            this.insert("", cx);
 7411        });
 7412        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7413    }
 7414
 7415    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7416        let item = self.cut_common(cx);
 7417        cx.write_to_clipboard(item);
 7418    }
 7419
 7420    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 7421        self.change_selections(None, cx, |s| {
 7422            s.move_with(|snapshot, sel| {
 7423                if sel.is_empty() {
 7424                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7425                }
 7426            });
 7427        });
 7428        let item = self.cut_common(cx);
 7429        cx.set_global(KillRing(item))
 7430    }
 7431
 7432    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 7433        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7434            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7435                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7436            } else {
 7437                return;
 7438            }
 7439        } else {
 7440            return;
 7441        };
 7442        self.do_paste(&text, metadata, false, cx);
 7443    }
 7444
 7445    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7446        let selections = self.selections.all::<Point>(cx);
 7447        let buffer = self.buffer.read(cx).read(cx);
 7448        let mut text = String::new();
 7449
 7450        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7451        {
 7452            let max_point = buffer.max_point();
 7453            let mut is_first = true;
 7454            for selection in selections.iter() {
 7455                let mut start = selection.start;
 7456                let mut end = selection.end;
 7457                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7458                if is_entire_line {
 7459                    start = Point::new(start.row, 0);
 7460                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7461                }
 7462                if is_first {
 7463                    is_first = false;
 7464                } else {
 7465                    text += "\n";
 7466                }
 7467                let mut len = 0;
 7468                for chunk in buffer.text_for_range(start..end) {
 7469                    text.push_str(chunk);
 7470                    len += chunk.len();
 7471                }
 7472                clipboard_selections.push(ClipboardSelection {
 7473                    len,
 7474                    is_entire_line,
 7475                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7476                });
 7477            }
 7478        }
 7479
 7480        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7481            text,
 7482            clipboard_selections,
 7483        ));
 7484    }
 7485
 7486    pub fn do_paste(
 7487        &mut self,
 7488        text: &String,
 7489        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7490        handle_entire_lines: bool,
 7491        cx: &mut ViewContext<Self>,
 7492    ) {
 7493        if self.read_only(cx) {
 7494            return;
 7495        }
 7496
 7497        let clipboard_text = Cow::Borrowed(text);
 7498
 7499        self.transact(cx, |this, cx| {
 7500            if let Some(mut clipboard_selections) = clipboard_selections {
 7501                let old_selections = this.selections.all::<usize>(cx);
 7502                let all_selections_were_entire_line =
 7503                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7504                let first_selection_indent_column =
 7505                    clipboard_selections.first().map(|s| s.first_line_indent);
 7506                if clipboard_selections.len() != old_selections.len() {
 7507                    clipboard_selections.drain(..);
 7508                }
 7509                let cursor_offset = this.selections.last::<usize>(cx).head();
 7510                let mut auto_indent_on_paste = true;
 7511
 7512                this.buffer.update(cx, |buffer, cx| {
 7513                    let snapshot = buffer.read(cx);
 7514                    auto_indent_on_paste =
 7515                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7516
 7517                    let mut start_offset = 0;
 7518                    let mut edits = Vec::new();
 7519                    let mut original_indent_columns = Vec::new();
 7520                    for (ix, selection) in old_selections.iter().enumerate() {
 7521                        let to_insert;
 7522                        let entire_line;
 7523                        let original_indent_column;
 7524                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7525                            let end_offset = start_offset + clipboard_selection.len;
 7526                            to_insert = &clipboard_text[start_offset..end_offset];
 7527                            entire_line = clipboard_selection.is_entire_line;
 7528                            start_offset = end_offset + 1;
 7529                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7530                        } else {
 7531                            to_insert = clipboard_text.as_str();
 7532                            entire_line = all_selections_were_entire_line;
 7533                            original_indent_column = first_selection_indent_column
 7534                        }
 7535
 7536                        // If the corresponding selection was empty when this slice of the
 7537                        // clipboard text was written, then the entire line containing the
 7538                        // selection was copied. If this selection is also currently empty,
 7539                        // then paste the line before the current line of the buffer.
 7540                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7541                            let column = selection.start.to_point(&snapshot).column as usize;
 7542                            let line_start = selection.start - column;
 7543                            line_start..line_start
 7544                        } else {
 7545                            selection.range()
 7546                        };
 7547
 7548                        edits.push((range, to_insert));
 7549                        original_indent_columns.extend(original_indent_column);
 7550                    }
 7551                    drop(snapshot);
 7552
 7553                    buffer.edit(
 7554                        edits,
 7555                        if auto_indent_on_paste {
 7556                            Some(AutoindentMode::Block {
 7557                                original_indent_columns,
 7558                            })
 7559                        } else {
 7560                            None
 7561                        },
 7562                        cx,
 7563                    );
 7564                });
 7565
 7566                let selections = this.selections.all::<usize>(cx);
 7567                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7568            } else {
 7569                this.insert(&clipboard_text, cx);
 7570            }
 7571        });
 7572    }
 7573
 7574    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7575        if let Some(item) = cx.read_from_clipboard() {
 7576            let entries = item.entries();
 7577
 7578            match entries.first() {
 7579                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7580                // of all the pasted entries.
 7581                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7582                    .do_paste(
 7583                        clipboard_string.text(),
 7584                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7585                        true,
 7586                        cx,
 7587                    ),
 7588                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7589            }
 7590        }
 7591    }
 7592
 7593    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7594        if self.read_only(cx) {
 7595            return;
 7596        }
 7597
 7598        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7599            if let Some((selections, _)) =
 7600                self.selection_history.transaction(transaction_id).cloned()
 7601            {
 7602                self.change_selections(None, cx, |s| {
 7603                    s.select_anchors(selections.to_vec());
 7604                });
 7605            }
 7606            self.request_autoscroll(Autoscroll::fit(), cx);
 7607            self.unmark_text(cx);
 7608            self.refresh_inline_completion(true, false, cx);
 7609            cx.emit(EditorEvent::Edited { transaction_id });
 7610            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7611        }
 7612    }
 7613
 7614    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7615        if self.read_only(cx) {
 7616            return;
 7617        }
 7618
 7619        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7620            if let Some((_, Some(selections))) =
 7621                self.selection_history.transaction(transaction_id).cloned()
 7622            {
 7623                self.change_selections(None, cx, |s| {
 7624                    s.select_anchors(selections.to_vec());
 7625                });
 7626            }
 7627            self.request_autoscroll(Autoscroll::fit(), cx);
 7628            self.unmark_text(cx);
 7629            self.refresh_inline_completion(true, false, cx);
 7630            cx.emit(EditorEvent::Edited { transaction_id });
 7631        }
 7632    }
 7633
 7634    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7635        self.buffer
 7636            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7637    }
 7638
 7639    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7640        self.buffer
 7641            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7642    }
 7643
 7644    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7645        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7646            let line_mode = s.line_mode;
 7647            s.move_with(|map, selection| {
 7648                let cursor = if selection.is_empty() && !line_mode {
 7649                    movement::left(map, selection.start)
 7650                } else {
 7651                    selection.start
 7652                };
 7653                selection.collapse_to(cursor, SelectionGoal::None);
 7654            });
 7655        })
 7656    }
 7657
 7658    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7659        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7660            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7661        })
 7662    }
 7663
 7664    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7665        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7666            let line_mode = s.line_mode;
 7667            s.move_with(|map, selection| {
 7668                let cursor = if selection.is_empty() && !line_mode {
 7669                    movement::right(map, selection.end)
 7670                } else {
 7671                    selection.end
 7672                };
 7673                selection.collapse_to(cursor, SelectionGoal::None)
 7674            });
 7675        })
 7676    }
 7677
 7678    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7679        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7680            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7681        })
 7682    }
 7683
 7684    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7685        if self.take_rename(true, cx).is_some() {
 7686            return;
 7687        }
 7688
 7689        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7690            cx.propagate();
 7691            return;
 7692        }
 7693
 7694        let text_layout_details = &self.text_layout_details(cx);
 7695        let selection_count = self.selections.count();
 7696        let first_selection = self.selections.first_anchor();
 7697
 7698        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7699            let line_mode = s.line_mode;
 7700            s.move_with(|map, selection| {
 7701                if !selection.is_empty() && !line_mode {
 7702                    selection.goal = SelectionGoal::None;
 7703                }
 7704                let (cursor, goal) = movement::up(
 7705                    map,
 7706                    selection.start,
 7707                    selection.goal,
 7708                    false,
 7709                    text_layout_details,
 7710                );
 7711                selection.collapse_to(cursor, goal);
 7712            });
 7713        });
 7714
 7715        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7716        {
 7717            cx.propagate();
 7718        }
 7719    }
 7720
 7721    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7722        if self.take_rename(true, cx).is_some() {
 7723            return;
 7724        }
 7725
 7726        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7727            cx.propagate();
 7728            return;
 7729        }
 7730
 7731        let text_layout_details = &self.text_layout_details(cx);
 7732
 7733        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7734            let line_mode = s.line_mode;
 7735            s.move_with(|map, selection| {
 7736                if !selection.is_empty() && !line_mode {
 7737                    selection.goal = SelectionGoal::None;
 7738                }
 7739                let (cursor, goal) = movement::up_by_rows(
 7740                    map,
 7741                    selection.start,
 7742                    action.lines,
 7743                    selection.goal,
 7744                    false,
 7745                    text_layout_details,
 7746                );
 7747                selection.collapse_to(cursor, goal);
 7748            });
 7749        })
 7750    }
 7751
 7752    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7753        if self.take_rename(true, cx).is_some() {
 7754            return;
 7755        }
 7756
 7757        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7758            cx.propagate();
 7759            return;
 7760        }
 7761
 7762        let text_layout_details = &self.text_layout_details(cx);
 7763
 7764        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7765            let line_mode = s.line_mode;
 7766            s.move_with(|map, selection| {
 7767                if !selection.is_empty() && !line_mode {
 7768                    selection.goal = SelectionGoal::None;
 7769                }
 7770                let (cursor, goal) = movement::down_by_rows(
 7771                    map,
 7772                    selection.start,
 7773                    action.lines,
 7774                    selection.goal,
 7775                    false,
 7776                    text_layout_details,
 7777                );
 7778                selection.collapse_to(cursor, goal);
 7779            });
 7780        })
 7781    }
 7782
 7783    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7784        let text_layout_details = &self.text_layout_details(cx);
 7785        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7786            s.move_heads_with(|map, head, goal| {
 7787                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7788            })
 7789        })
 7790    }
 7791
 7792    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7793        let text_layout_details = &self.text_layout_details(cx);
 7794        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7795            s.move_heads_with(|map, head, goal| {
 7796                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7797            })
 7798        })
 7799    }
 7800
 7801    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7802        let Some(row_count) = self.visible_row_count() else {
 7803            return;
 7804        };
 7805
 7806        let text_layout_details = &self.text_layout_details(cx);
 7807
 7808        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7809            s.move_heads_with(|map, head, goal| {
 7810                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7811            })
 7812        })
 7813    }
 7814
 7815    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7816        if self.take_rename(true, cx).is_some() {
 7817            return;
 7818        }
 7819
 7820        if self
 7821            .context_menu
 7822            .write()
 7823            .as_mut()
 7824            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7825            .unwrap_or(false)
 7826        {
 7827            return;
 7828        }
 7829
 7830        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7831            cx.propagate();
 7832            return;
 7833        }
 7834
 7835        let Some(row_count) = self.visible_row_count() else {
 7836            return;
 7837        };
 7838
 7839        let autoscroll = if action.center_cursor {
 7840            Autoscroll::center()
 7841        } else {
 7842            Autoscroll::fit()
 7843        };
 7844
 7845        let text_layout_details = &self.text_layout_details(cx);
 7846
 7847        self.change_selections(Some(autoscroll), cx, |s| {
 7848            let line_mode = s.line_mode;
 7849            s.move_with(|map, selection| {
 7850                if !selection.is_empty() && !line_mode {
 7851                    selection.goal = SelectionGoal::None;
 7852                }
 7853                let (cursor, goal) = movement::up_by_rows(
 7854                    map,
 7855                    selection.end,
 7856                    row_count,
 7857                    selection.goal,
 7858                    false,
 7859                    text_layout_details,
 7860                );
 7861                selection.collapse_to(cursor, goal);
 7862            });
 7863        });
 7864    }
 7865
 7866    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7867        let text_layout_details = &self.text_layout_details(cx);
 7868        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7869            s.move_heads_with(|map, head, goal| {
 7870                movement::up(map, head, goal, false, text_layout_details)
 7871            })
 7872        })
 7873    }
 7874
 7875    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7876        self.take_rename(true, cx);
 7877
 7878        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7879            cx.propagate();
 7880            return;
 7881        }
 7882
 7883        let text_layout_details = &self.text_layout_details(cx);
 7884        let selection_count = self.selections.count();
 7885        let first_selection = self.selections.first_anchor();
 7886
 7887        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7888            let line_mode = s.line_mode;
 7889            s.move_with(|map, selection| {
 7890                if !selection.is_empty() && !line_mode {
 7891                    selection.goal = SelectionGoal::None;
 7892                }
 7893                let (cursor, goal) = movement::down(
 7894                    map,
 7895                    selection.end,
 7896                    selection.goal,
 7897                    false,
 7898                    text_layout_details,
 7899                );
 7900                selection.collapse_to(cursor, goal);
 7901            });
 7902        });
 7903
 7904        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7905        {
 7906            cx.propagate();
 7907        }
 7908    }
 7909
 7910    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7911        let Some(row_count) = self.visible_row_count() else {
 7912            return;
 7913        };
 7914
 7915        let text_layout_details = &self.text_layout_details(cx);
 7916
 7917        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7918            s.move_heads_with(|map, head, goal| {
 7919                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7920            })
 7921        })
 7922    }
 7923
 7924    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7925        if self.take_rename(true, cx).is_some() {
 7926            return;
 7927        }
 7928
 7929        if self
 7930            .context_menu
 7931            .write()
 7932            .as_mut()
 7933            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7934            .unwrap_or(false)
 7935        {
 7936            return;
 7937        }
 7938
 7939        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7940            cx.propagate();
 7941            return;
 7942        }
 7943
 7944        let Some(row_count) = self.visible_row_count() else {
 7945            return;
 7946        };
 7947
 7948        let autoscroll = if action.center_cursor {
 7949            Autoscroll::center()
 7950        } else {
 7951            Autoscroll::fit()
 7952        };
 7953
 7954        let text_layout_details = &self.text_layout_details(cx);
 7955        self.change_selections(Some(autoscroll), cx, |s| {
 7956            let line_mode = s.line_mode;
 7957            s.move_with(|map, selection| {
 7958                if !selection.is_empty() && !line_mode {
 7959                    selection.goal = SelectionGoal::None;
 7960                }
 7961                let (cursor, goal) = movement::down_by_rows(
 7962                    map,
 7963                    selection.end,
 7964                    row_count,
 7965                    selection.goal,
 7966                    false,
 7967                    text_layout_details,
 7968                );
 7969                selection.collapse_to(cursor, goal);
 7970            });
 7971        });
 7972    }
 7973
 7974    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7975        let text_layout_details = &self.text_layout_details(cx);
 7976        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7977            s.move_heads_with(|map, head, goal| {
 7978                movement::down(map, head, goal, false, text_layout_details)
 7979            })
 7980        });
 7981    }
 7982
 7983    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7984        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7985            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7986        }
 7987    }
 7988
 7989    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7990        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7991            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7992        }
 7993    }
 7994
 7995    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7996        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7997            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7998        }
 7999    }
 8000
 8001    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 8002        if let Some(context_menu) = self.context_menu.write().as_mut() {
 8003            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8004        }
 8005    }
 8006
 8007    pub fn move_to_previous_word_start(
 8008        &mut self,
 8009        _: &MoveToPreviousWordStart,
 8010        cx: &mut ViewContext<Self>,
 8011    ) {
 8012        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8013            s.move_cursors_with(|map, head, _| {
 8014                (
 8015                    movement::previous_word_start(map, head),
 8016                    SelectionGoal::None,
 8017                )
 8018            });
 8019        })
 8020    }
 8021
 8022    pub fn move_to_previous_subword_start(
 8023        &mut self,
 8024        _: &MoveToPreviousSubwordStart,
 8025        cx: &mut ViewContext<Self>,
 8026    ) {
 8027        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8028            s.move_cursors_with(|map, head, _| {
 8029                (
 8030                    movement::previous_subword_start(map, head),
 8031                    SelectionGoal::None,
 8032                )
 8033            });
 8034        })
 8035    }
 8036
 8037    pub fn select_to_previous_word_start(
 8038        &mut self,
 8039        _: &SelectToPreviousWordStart,
 8040        cx: &mut ViewContext<Self>,
 8041    ) {
 8042        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8043            s.move_heads_with(|map, head, _| {
 8044                (
 8045                    movement::previous_word_start(map, head),
 8046                    SelectionGoal::None,
 8047                )
 8048            });
 8049        })
 8050    }
 8051
 8052    pub fn select_to_previous_subword_start(
 8053        &mut self,
 8054        _: &SelectToPreviousSubwordStart,
 8055        cx: &mut ViewContext<Self>,
 8056    ) {
 8057        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8058            s.move_heads_with(|map, head, _| {
 8059                (
 8060                    movement::previous_subword_start(map, head),
 8061                    SelectionGoal::None,
 8062                )
 8063            });
 8064        })
 8065    }
 8066
 8067    pub fn delete_to_previous_word_start(
 8068        &mut self,
 8069        action: &DeleteToPreviousWordStart,
 8070        cx: &mut ViewContext<Self>,
 8071    ) {
 8072        self.transact(cx, |this, cx| {
 8073            this.select_autoclose_pair(cx);
 8074            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8075                let line_mode = s.line_mode;
 8076                s.move_with(|map, selection| {
 8077                    if selection.is_empty() && !line_mode {
 8078                        let cursor = if action.ignore_newlines {
 8079                            movement::previous_word_start(map, selection.head())
 8080                        } else {
 8081                            movement::previous_word_start_or_newline(map, selection.head())
 8082                        };
 8083                        selection.set_head(cursor, SelectionGoal::None);
 8084                    }
 8085                });
 8086            });
 8087            this.insert("", cx);
 8088        });
 8089    }
 8090
 8091    pub fn delete_to_previous_subword_start(
 8092        &mut self,
 8093        _: &DeleteToPreviousSubwordStart,
 8094        cx: &mut ViewContext<Self>,
 8095    ) {
 8096        self.transact(cx, |this, cx| {
 8097            this.select_autoclose_pair(cx);
 8098            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8099                let line_mode = s.line_mode;
 8100                s.move_with(|map, selection| {
 8101                    if selection.is_empty() && !line_mode {
 8102                        let cursor = movement::previous_subword_start(map, selection.head());
 8103                        selection.set_head(cursor, SelectionGoal::None);
 8104                    }
 8105                });
 8106            });
 8107            this.insert("", cx);
 8108        });
 8109    }
 8110
 8111    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8112        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8113            s.move_cursors_with(|map, head, _| {
 8114                (movement::next_word_end(map, head), SelectionGoal::None)
 8115            });
 8116        })
 8117    }
 8118
 8119    pub fn move_to_next_subword_end(
 8120        &mut self,
 8121        _: &MoveToNextSubwordEnd,
 8122        cx: &mut ViewContext<Self>,
 8123    ) {
 8124        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8125            s.move_cursors_with(|map, head, _| {
 8126                (movement::next_subword_end(map, head), SelectionGoal::None)
 8127            });
 8128        })
 8129    }
 8130
 8131    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8132        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8133            s.move_heads_with(|map, head, _| {
 8134                (movement::next_word_end(map, head), SelectionGoal::None)
 8135            });
 8136        })
 8137    }
 8138
 8139    pub fn select_to_next_subword_end(
 8140        &mut self,
 8141        _: &SelectToNextSubwordEnd,
 8142        cx: &mut ViewContext<Self>,
 8143    ) {
 8144        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8145            s.move_heads_with(|map, head, _| {
 8146                (movement::next_subword_end(map, head), SelectionGoal::None)
 8147            });
 8148        })
 8149    }
 8150
 8151    pub fn delete_to_next_word_end(
 8152        &mut self,
 8153        action: &DeleteToNextWordEnd,
 8154        cx: &mut ViewContext<Self>,
 8155    ) {
 8156        self.transact(cx, |this, cx| {
 8157            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8158                let line_mode = s.line_mode;
 8159                s.move_with(|map, selection| {
 8160                    if selection.is_empty() && !line_mode {
 8161                        let cursor = if action.ignore_newlines {
 8162                            movement::next_word_end(map, selection.head())
 8163                        } else {
 8164                            movement::next_word_end_or_newline(map, selection.head())
 8165                        };
 8166                        selection.set_head(cursor, SelectionGoal::None);
 8167                    }
 8168                });
 8169            });
 8170            this.insert("", cx);
 8171        });
 8172    }
 8173
 8174    pub fn delete_to_next_subword_end(
 8175        &mut self,
 8176        _: &DeleteToNextSubwordEnd,
 8177        cx: &mut ViewContext<Self>,
 8178    ) {
 8179        self.transact(cx, |this, cx| {
 8180            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8181                s.move_with(|map, selection| {
 8182                    if selection.is_empty() {
 8183                        let cursor = movement::next_subword_end(map, selection.head());
 8184                        selection.set_head(cursor, SelectionGoal::None);
 8185                    }
 8186                });
 8187            });
 8188            this.insert("", cx);
 8189        });
 8190    }
 8191
 8192    pub fn move_to_beginning_of_line(
 8193        &mut self,
 8194        action: &MoveToBeginningOfLine,
 8195        cx: &mut ViewContext<Self>,
 8196    ) {
 8197        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8198            s.move_cursors_with(|map, head, _| {
 8199                (
 8200                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8201                    SelectionGoal::None,
 8202                )
 8203            });
 8204        })
 8205    }
 8206
 8207    pub fn select_to_beginning_of_line(
 8208        &mut self,
 8209        action: &SelectToBeginningOfLine,
 8210        cx: &mut ViewContext<Self>,
 8211    ) {
 8212        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8213            s.move_heads_with(|map, head, _| {
 8214                (
 8215                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8216                    SelectionGoal::None,
 8217                )
 8218            });
 8219        });
 8220    }
 8221
 8222    pub fn delete_to_beginning_of_line(
 8223        &mut self,
 8224        _: &DeleteToBeginningOfLine,
 8225        cx: &mut ViewContext<Self>,
 8226    ) {
 8227        self.transact(cx, |this, cx| {
 8228            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8229                s.move_with(|_, selection| {
 8230                    selection.reversed = true;
 8231                });
 8232            });
 8233
 8234            this.select_to_beginning_of_line(
 8235                &SelectToBeginningOfLine {
 8236                    stop_at_soft_wraps: false,
 8237                },
 8238                cx,
 8239            );
 8240            this.backspace(&Backspace, cx);
 8241        });
 8242    }
 8243
 8244    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8245        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8246            s.move_cursors_with(|map, head, _| {
 8247                (
 8248                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8249                    SelectionGoal::None,
 8250                )
 8251            });
 8252        })
 8253    }
 8254
 8255    pub fn select_to_end_of_line(
 8256        &mut self,
 8257        action: &SelectToEndOfLine,
 8258        cx: &mut ViewContext<Self>,
 8259    ) {
 8260        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8261            s.move_heads_with(|map, head, _| {
 8262                (
 8263                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8264                    SelectionGoal::None,
 8265                )
 8266            });
 8267        })
 8268    }
 8269
 8270    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8271        self.transact(cx, |this, cx| {
 8272            this.select_to_end_of_line(
 8273                &SelectToEndOfLine {
 8274                    stop_at_soft_wraps: false,
 8275                },
 8276                cx,
 8277            );
 8278            this.delete(&Delete, cx);
 8279        });
 8280    }
 8281
 8282    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8283        self.transact(cx, |this, cx| {
 8284            this.select_to_end_of_line(
 8285                &SelectToEndOfLine {
 8286                    stop_at_soft_wraps: false,
 8287                },
 8288                cx,
 8289            );
 8290            this.cut(&Cut, cx);
 8291        });
 8292    }
 8293
 8294    pub fn move_to_start_of_paragraph(
 8295        &mut self,
 8296        _: &MoveToStartOfParagraph,
 8297        cx: &mut ViewContext<Self>,
 8298    ) {
 8299        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8300            cx.propagate();
 8301            return;
 8302        }
 8303
 8304        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8305            s.move_with(|map, selection| {
 8306                selection.collapse_to(
 8307                    movement::start_of_paragraph(map, selection.head(), 1),
 8308                    SelectionGoal::None,
 8309                )
 8310            });
 8311        })
 8312    }
 8313
 8314    pub fn move_to_end_of_paragraph(
 8315        &mut self,
 8316        _: &MoveToEndOfParagraph,
 8317        cx: &mut ViewContext<Self>,
 8318    ) {
 8319        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8320            cx.propagate();
 8321            return;
 8322        }
 8323
 8324        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8325            s.move_with(|map, selection| {
 8326                selection.collapse_to(
 8327                    movement::end_of_paragraph(map, selection.head(), 1),
 8328                    SelectionGoal::None,
 8329                )
 8330            });
 8331        })
 8332    }
 8333
 8334    pub fn select_to_start_of_paragraph(
 8335        &mut self,
 8336        _: &SelectToStartOfParagraph,
 8337        cx: &mut ViewContext<Self>,
 8338    ) {
 8339        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8340            cx.propagate();
 8341            return;
 8342        }
 8343
 8344        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8345            s.move_heads_with(|map, head, _| {
 8346                (
 8347                    movement::start_of_paragraph(map, head, 1),
 8348                    SelectionGoal::None,
 8349                )
 8350            });
 8351        })
 8352    }
 8353
 8354    pub fn select_to_end_of_paragraph(
 8355        &mut self,
 8356        _: &SelectToEndOfParagraph,
 8357        cx: &mut ViewContext<Self>,
 8358    ) {
 8359        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8360            cx.propagate();
 8361            return;
 8362        }
 8363
 8364        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8365            s.move_heads_with(|map, head, _| {
 8366                (
 8367                    movement::end_of_paragraph(map, head, 1),
 8368                    SelectionGoal::None,
 8369                )
 8370            });
 8371        })
 8372    }
 8373
 8374    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8375        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8376            cx.propagate();
 8377            return;
 8378        }
 8379
 8380        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8381            s.select_ranges(vec![0..0]);
 8382        });
 8383    }
 8384
 8385    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8386        let mut selection = self.selections.last::<Point>(cx);
 8387        selection.set_head(Point::zero(), SelectionGoal::None);
 8388
 8389        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8390            s.select(vec![selection]);
 8391        });
 8392    }
 8393
 8394    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8395        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8396            cx.propagate();
 8397            return;
 8398        }
 8399
 8400        let cursor = self.buffer.read(cx).read(cx).len();
 8401        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8402            s.select_ranges(vec![cursor..cursor])
 8403        });
 8404    }
 8405
 8406    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8407        self.nav_history = nav_history;
 8408    }
 8409
 8410    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8411        self.nav_history.as_ref()
 8412    }
 8413
 8414    fn push_to_nav_history(
 8415        &mut self,
 8416        cursor_anchor: Anchor,
 8417        new_position: Option<Point>,
 8418        cx: &mut ViewContext<Self>,
 8419    ) {
 8420        if let Some(nav_history) = self.nav_history.as_mut() {
 8421            let buffer = self.buffer.read(cx).read(cx);
 8422            let cursor_position = cursor_anchor.to_point(&buffer);
 8423            let scroll_state = self.scroll_manager.anchor();
 8424            let scroll_top_row = scroll_state.top_row(&buffer);
 8425            drop(buffer);
 8426
 8427            if let Some(new_position) = new_position {
 8428                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8429                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8430                    return;
 8431                }
 8432            }
 8433
 8434            nav_history.push(
 8435                Some(NavigationData {
 8436                    cursor_anchor,
 8437                    cursor_position,
 8438                    scroll_anchor: scroll_state,
 8439                    scroll_top_row,
 8440                }),
 8441                cx,
 8442            );
 8443        }
 8444    }
 8445
 8446    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8447        let buffer = self.buffer.read(cx).snapshot(cx);
 8448        let mut selection = self.selections.first::<usize>(cx);
 8449        selection.set_head(buffer.len(), SelectionGoal::None);
 8450        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8451            s.select(vec![selection]);
 8452        });
 8453    }
 8454
 8455    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8456        let end = self.buffer.read(cx).read(cx).len();
 8457        self.change_selections(None, cx, |s| {
 8458            s.select_ranges(vec![0..end]);
 8459        });
 8460    }
 8461
 8462    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8463        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8464        let mut selections = self.selections.all::<Point>(cx);
 8465        let max_point = display_map.buffer_snapshot.max_point();
 8466        for selection in &mut selections {
 8467            let rows = selection.spanned_rows(true, &display_map);
 8468            selection.start = Point::new(rows.start.0, 0);
 8469            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8470            selection.reversed = false;
 8471        }
 8472        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8473            s.select(selections);
 8474        });
 8475    }
 8476
 8477    pub fn split_selection_into_lines(
 8478        &mut self,
 8479        _: &SplitSelectionIntoLines,
 8480        cx: &mut ViewContext<Self>,
 8481    ) {
 8482        let mut to_unfold = Vec::new();
 8483        let mut new_selection_ranges = Vec::new();
 8484        {
 8485            let selections = self.selections.all::<Point>(cx);
 8486            let buffer = self.buffer.read(cx).read(cx);
 8487            for selection in selections {
 8488                for row in selection.start.row..selection.end.row {
 8489                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8490                    new_selection_ranges.push(cursor..cursor);
 8491                }
 8492                new_selection_ranges.push(selection.end..selection.end);
 8493                to_unfold.push(selection.start..selection.end);
 8494            }
 8495        }
 8496        self.unfold_ranges(&to_unfold, true, true, cx);
 8497        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8498            s.select_ranges(new_selection_ranges);
 8499        });
 8500    }
 8501
 8502    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8503        self.add_selection(true, cx);
 8504    }
 8505
 8506    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8507        self.add_selection(false, cx);
 8508    }
 8509
 8510    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8511        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8512        let mut selections = self.selections.all::<Point>(cx);
 8513        let text_layout_details = self.text_layout_details(cx);
 8514        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8515            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8516            let range = oldest_selection.display_range(&display_map).sorted();
 8517
 8518            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8519            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8520            let positions = start_x.min(end_x)..start_x.max(end_x);
 8521
 8522            selections.clear();
 8523            let mut stack = Vec::new();
 8524            for row in range.start.row().0..=range.end.row().0 {
 8525                if let Some(selection) = self.selections.build_columnar_selection(
 8526                    &display_map,
 8527                    DisplayRow(row),
 8528                    &positions,
 8529                    oldest_selection.reversed,
 8530                    &text_layout_details,
 8531                ) {
 8532                    stack.push(selection.id);
 8533                    selections.push(selection);
 8534                }
 8535            }
 8536
 8537            if above {
 8538                stack.reverse();
 8539            }
 8540
 8541            AddSelectionsState { above, stack }
 8542        });
 8543
 8544        let last_added_selection = *state.stack.last().unwrap();
 8545        let mut new_selections = Vec::new();
 8546        if above == state.above {
 8547            let end_row = if above {
 8548                DisplayRow(0)
 8549            } else {
 8550                display_map.max_point().row()
 8551            };
 8552
 8553            'outer: for selection in selections {
 8554                if selection.id == last_added_selection {
 8555                    let range = selection.display_range(&display_map).sorted();
 8556                    debug_assert_eq!(range.start.row(), range.end.row());
 8557                    let mut row = range.start.row();
 8558                    let positions =
 8559                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8560                            px(start)..px(end)
 8561                        } else {
 8562                            let start_x =
 8563                                display_map.x_for_display_point(range.start, &text_layout_details);
 8564                            let end_x =
 8565                                display_map.x_for_display_point(range.end, &text_layout_details);
 8566                            start_x.min(end_x)..start_x.max(end_x)
 8567                        };
 8568
 8569                    while row != end_row {
 8570                        if above {
 8571                            row.0 -= 1;
 8572                        } else {
 8573                            row.0 += 1;
 8574                        }
 8575
 8576                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8577                            &display_map,
 8578                            row,
 8579                            &positions,
 8580                            selection.reversed,
 8581                            &text_layout_details,
 8582                        ) {
 8583                            state.stack.push(new_selection.id);
 8584                            if above {
 8585                                new_selections.push(new_selection);
 8586                                new_selections.push(selection);
 8587                            } else {
 8588                                new_selections.push(selection);
 8589                                new_selections.push(new_selection);
 8590                            }
 8591
 8592                            continue 'outer;
 8593                        }
 8594                    }
 8595                }
 8596
 8597                new_selections.push(selection);
 8598            }
 8599        } else {
 8600            new_selections = selections;
 8601            new_selections.retain(|s| s.id != last_added_selection);
 8602            state.stack.pop();
 8603        }
 8604
 8605        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8606            s.select(new_selections);
 8607        });
 8608        if state.stack.len() > 1 {
 8609            self.add_selections_state = Some(state);
 8610        }
 8611    }
 8612
 8613    pub fn select_next_match_internal(
 8614        &mut self,
 8615        display_map: &DisplaySnapshot,
 8616        replace_newest: bool,
 8617        autoscroll: Option<Autoscroll>,
 8618        cx: &mut ViewContext<Self>,
 8619    ) -> Result<()> {
 8620        fn select_next_match_ranges(
 8621            this: &mut Editor,
 8622            range: Range<usize>,
 8623            replace_newest: bool,
 8624            auto_scroll: Option<Autoscroll>,
 8625            cx: &mut ViewContext<Editor>,
 8626        ) {
 8627            this.unfold_ranges(&[range.clone()], false, true, cx);
 8628            this.change_selections(auto_scroll, cx, |s| {
 8629                if replace_newest {
 8630                    s.delete(s.newest_anchor().id);
 8631                }
 8632                s.insert_range(range.clone());
 8633            });
 8634        }
 8635
 8636        let buffer = &display_map.buffer_snapshot;
 8637        let mut selections = self.selections.all::<usize>(cx);
 8638        if let Some(mut select_next_state) = self.select_next_state.take() {
 8639            let query = &select_next_state.query;
 8640            if !select_next_state.done {
 8641                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8642                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8643                let mut next_selected_range = None;
 8644
 8645                let bytes_after_last_selection =
 8646                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8647                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8648                let query_matches = query
 8649                    .stream_find_iter(bytes_after_last_selection)
 8650                    .map(|result| (last_selection.end, result))
 8651                    .chain(
 8652                        query
 8653                            .stream_find_iter(bytes_before_first_selection)
 8654                            .map(|result| (0, result)),
 8655                    );
 8656
 8657                for (start_offset, query_match) in query_matches {
 8658                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8659                    let offset_range =
 8660                        start_offset + query_match.start()..start_offset + query_match.end();
 8661                    let display_range = offset_range.start.to_display_point(display_map)
 8662                        ..offset_range.end.to_display_point(display_map);
 8663
 8664                    if !select_next_state.wordwise
 8665                        || (!movement::is_inside_word(display_map, display_range.start)
 8666                            && !movement::is_inside_word(display_map, display_range.end))
 8667                    {
 8668                        // TODO: This is n^2, because we might check all the selections
 8669                        if !selections
 8670                            .iter()
 8671                            .any(|selection| selection.range().overlaps(&offset_range))
 8672                        {
 8673                            next_selected_range = Some(offset_range);
 8674                            break;
 8675                        }
 8676                    }
 8677                }
 8678
 8679                if let Some(next_selected_range) = next_selected_range {
 8680                    select_next_match_ranges(
 8681                        self,
 8682                        next_selected_range,
 8683                        replace_newest,
 8684                        autoscroll,
 8685                        cx,
 8686                    );
 8687                } else {
 8688                    select_next_state.done = true;
 8689                }
 8690            }
 8691
 8692            self.select_next_state = Some(select_next_state);
 8693        } else {
 8694            let mut only_carets = true;
 8695            let mut same_text_selected = true;
 8696            let mut selected_text = None;
 8697
 8698            let mut selections_iter = selections.iter().peekable();
 8699            while let Some(selection) = selections_iter.next() {
 8700                if selection.start != selection.end {
 8701                    only_carets = false;
 8702                }
 8703
 8704                if same_text_selected {
 8705                    if selected_text.is_none() {
 8706                        selected_text =
 8707                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8708                    }
 8709
 8710                    if let Some(next_selection) = selections_iter.peek() {
 8711                        if next_selection.range().len() == selection.range().len() {
 8712                            let next_selected_text = buffer
 8713                                .text_for_range(next_selection.range())
 8714                                .collect::<String>();
 8715                            if Some(next_selected_text) != selected_text {
 8716                                same_text_selected = false;
 8717                                selected_text = None;
 8718                            }
 8719                        } else {
 8720                            same_text_selected = false;
 8721                            selected_text = None;
 8722                        }
 8723                    }
 8724                }
 8725            }
 8726
 8727            if only_carets {
 8728                for selection in &mut selections {
 8729                    let word_range = movement::surrounding_word(
 8730                        display_map,
 8731                        selection.start.to_display_point(display_map),
 8732                    );
 8733                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8734                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8735                    selection.goal = SelectionGoal::None;
 8736                    selection.reversed = false;
 8737                    select_next_match_ranges(
 8738                        self,
 8739                        selection.start..selection.end,
 8740                        replace_newest,
 8741                        autoscroll,
 8742                        cx,
 8743                    );
 8744                }
 8745
 8746                if selections.len() == 1 {
 8747                    let selection = selections
 8748                        .last()
 8749                        .expect("ensured that there's only one selection");
 8750                    let query = buffer
 8751                        .text_for_range(selection.start..selection.end)
 8752                        .collect::<String>();
 8753                    let is_empty = query.is_empty();
 8754                    let select_state = SelectNextState {
 8755                        query: AhoCorasick::new(&[query])?,
 8756                        wordwise: true,
 8757                        done: is_empty,
 8758                    };
 8759                    self.select_next_state = Some(select_state);
 8760                } else {
 8761                    self.select_next_state = None;
 8762                }
 8763            } else if let Some(selected_text) = selected_text {
 8764                self.select_next_state = Some(SelectNextState {
 8765                    query: AhoCorasick::new(&[selected_text])?,
 8766                    wordwise: false,
 8767                    done: false,
 8768                });
 8769                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8770            }
 8771        }
 8772        Ok(())
 8773    }
 8774
 8775    pub fn select_all_matches(
 8776        &mut self,
 8777        _action: &SelectAllMatches,
 8778        cx: &mut ViewContext<Self>,
 8779    ) -> Result<()> {
 8780        self.push_to_selection_history();
 8781        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8782
 8783        self.select_next_match_internal(&display_map, false, None, cx)?;
 8784        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8785            return Ok(());
 8786        };
 8787        if select_next_state.done {
 8788            return Ok(());
 8789        }
 8790
 8791        let mut new_selections = self.selections.all::<usize>(cx);
 8792
 8793        let buffer = &display_map.buffer_snapshot;
 8794        let query_matches = select_next_state
 8795            .query
 8796            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8797
 8798        for query_match in query_matches {
 8799            let query_match = query_match.unwrap(); // can only fail due to I/O
 8800            let offset_range = query_match.start()..query_match.end();
 8801            let display_range = offset_range.start.to_display_point(&display_map)
 8802                ..offset_range.end.to_display_point(&display_map);
 8803
 8804            if !select_next_state.wordwise
 8805                || (!movement::is_inside_word(&display_map, display_range.start)
 8806                    && !movement::is_inside_word(&display_map, display_range.end))
 8807            {
 8808                self.selections.change_with(cx, |selections| {
 8809                    new_selections.push(Selection {
 8810                        id: selections.new_selection_id(),
 8811                        start: offset_range.start,
 8812                        end: offset_range.end,
 8813                        reversed: false,
 8814                        goal: SelectionGoal::None,
 8815                    });
 8816                });
 8817            }
 8818        }
 8819
 8820        new_selections.sort_by_key(|selection| selection.start);
 8821        let mut ix = 0;
 8822        while ix + 1 < new_selections.len() {
 8823            let current_selection = &new_selections[ix];
 8824            let next_selection = &new_selections[ix + 1];
 8825            if current_selection.range().overlaps(&next_selection.range()) {
 8826                if current_selection.id < next_selection.id {
 8827                    new_selections.remove(ix + 1);
 8828                } else {
 8829                    new_selections.remove(ix);
 8830                }
 8831            } else {
 8832                ix += 1;
 8833            }
 8834        }
 8835
 8836        select_next_state.done = true;
 8837        self.unfold_ranges(
 8838            &new_selections
 8839                .iter()
 8840                .map(|selection| selection.range())
 8841                .collect::<Vec<_>>(),
 8842            false,
 8843            false,
 8844            cx,
 8845        );
 8846        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8847            selections.select(new_selections)
 8848        });
 8849
 8850        Ok(())
 8851    }
 8852
 8853    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8854        self.push_to_selection_history();
 8855        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8856        self.select_next_match_internal(
 8857            &display_map,
 8858            action.replace_newest,
 8859            Some(Autoscroll::newest()),
 8860            cx,
 8861        )?;
 8862        Ok(())
 8863    }
 8864
 8865    pub fn select_previous(
 8866        &mut self,
 8867        action: &SelectPrevious,
 8868        cx: &mut ViewContext<Self>,
 8869    ) -> Result<()> {
 8870        self.push_to_selection_history();
 8871        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8872        let buffer = &display_map.buffer_snapshot;
 8873        let mut selections = self.selections.all::<usize>(cx);
 8874        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8875            let query = &select_prev_state.query;
 8876            if !select_prev_state.done {
 8877                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8878                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8879                let mut next_selected_range = None;
 8880                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8881                let bytes_before_last_selection =
 8882                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8883                let bytes_after_first_selection =
 8884                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8885                let query_matches = query
 8886                    .stream_find_iter(bytes_before_last_selection)
 8887                    .map(|result| (last_selection.start, result))
 8888                    .chain(
 8889                        query
 8890                            .stream_find_iter(bytes_after_first_selection)
 8891                            .map(|result| (buffer.len(), result)),
 8892                    );
 8893                for (end_offset, query_match) in query_matches {
 8894                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8895                    let offset_range =
 8896                        end_offset - query_match.end()..end_offset - query_match.start();
 8897                    let display_range = offset_range.start.to_display_point(&display_map)
 8898                        ..offset_range.end.to_display_point(&display_map);
 8899
 8900                    if !select_prev_state.wordwise
 8901                        || (!movement::is_inside_word(&display_map, display_range.start)
 8902                            && !movement::is_inside_word(&display_map, display_range.end))
 8903                    {
 8904                        next_selected_range = Some(offset_range);
 8905                        break;
 8906                    }
 8907                }
 8908
 8909                if let Some(next_selected_range) = next_selected_range {
 8910                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8911                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8912                        if action.replace_newest {
 8913                            s.delete(s.newest_anchor().id);
 8914                        }
 8915                        s.insert_range(next_selected_range);
 8916                    });
 8917                } else {
 8918                    select_prev_state.done = true;
 8919                }
 8920            }
 8921
 8922            self.select_prev_state = Some(select_prev_state);
 8923        } else {
 8924            let mut only_carets = true;
 8925            let mut same_text_selected = true;
 8926            let mut selected_text = None;
 8927
 8928            let mut selections_iter = selections.iter().peekable();
 8929            while let Some(selection) = selections_iter.next() {
 8930                if selection.start != selection.end {
 8931                    only_carets = false;
 8932                }
 8933
 8934                if same_text_selected {
 8935                    if selected_text.is_none() {
 8936                        selected_text =
 8937                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8938                    }
 8939
 8940                    if let Some(next_selection) = selections_iter.peek() {
 8941                        if next_selection.range().len() == selection.range().len() {
 8942                            let next_selected_text = buffer
 8943                                .text_for_range(next_selection.range())
 8944                                .collect::<String>();
 8945                            if Some(next_selected_text) != selected_text {
 8946                                same_text_selected = false;
 8947                                selected_text = None;
 8948                            }
 8949                        } else {
 8950                            same_text_selected = false;
 8951                            selected_text = None;
 8952                        }
 8953                    }
 8954                }
 8955            }
 8956
 8957            if only_carets {
 8958                for selection in &mut selections {
 8959                    let word_range = movement::surrounding_word(
 8960                        &display_map,
 8961                        selection.start.to_display_point(&display_map),
 8962                    );
 8963                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8964                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8965                    selection.goal = SelectionGoal::None;
 8966                    selection.reversed = false;
 8967                }
 8968                if selections.len() == 1 {
 8969                    let selection = selections
 8970                        .last()
 8971                        .expect("ensured that there's only one selection");
 8972                    let query = buffer
 8973                        .text_for_range(selection.start..selection.end)
 8974                        .collect::<String>();
 8975                    let is_empty = query.is_empty();
 8976                    let select_state = SelectNextState {
 8977                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8978                        wordwise: true,
 8979                        done: is_empty,
 8980                    };
 8981                    self.select_prev_state = Some(select_state);
 8982                } else {
 8983                    self.select_prev_state = None;
 8984                }
 8985
 8986                self.unfold_ranges(
 8987                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8988                    false,
 8989                    true,
 8990                    cx,
 8991                );
 8992                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8993                    s.select(selections);
 8994                });
 8995            } else if let Some(selected_text) = selected_text {
 8996                self.select_prev_state = Some(SelectNextState {
 8997                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8998                    wordwise: false,
 8999                    done: false,
 9000                });
 9001                self.select_previous(action, cx)?;
 9002            }
 9003        }
 9004        Ok(())
 9005    }
 9006
 9007    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 9008        if self.read_only(cx) {
 9009            return;
 9010        }
 9011        let text_layout_details = &self.text_layout_details(cx);
 9012        self.transact(cx, |this, cx| {
 9013            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9014            let mut edits = Vec::new();
 9015            let mut selection_edit_ranges = Vec::new();
 9016            let mut last_toggled_row = None;
 9017            let snapshot = this.buffer.read(cx).read(cx);
 9018            let empty_str: Arc<str> = Arc::default();
 9019            let mut suffixes_inserted = Vec::new();
 9020            let ignore_indent = action.ignore_indent;
 9021
 9022            fn comment_prefix_range(
 9023                snapshot: &MultiBufferSnapshot,
 9024                row: MultiBufferRow,
 9025                comment_prefix: &str,
 9026                comment_prefix_whitespace: &str,
 9027                ignore_indent: bool,
 9028            ) -> Range<Point> {
 9029                let indent_size = if ignore_indent {
 9030                    0
 9031                } else {
 9032                    snapshot.indent_size_for_line(row).len
 9033                };
 9034
 9035                let start = Point::new(row.0, indent_size);
 9036
 9037                let mut line_bytes = snapshot
 9038                    .bytes_in_range(start..snapshot.max_point())
 9039                    .flatten()
 9040                    .copied();
 9041
 9042                // If this line currently begins with the line comment prefix, then record
 9043                // the range containing the prefix.
 9044                if line_bytes
 9045                    .by_ref()
 9046                    .take(comment_prefix.len())
 9047                    .eq(comment_prefix.bytes())
 9048                {
 9049                    // Include any whitespace that matches the comment prefix.
 9050                    let matching_whitespace_len = line_bytes
 9051                        .zip(comment_prefix_whitespace.bytes())
 9052                        .take_while(|(a, b)| a == b)
 9053                        .count() as u32;
 9054                    let end = Point::new(
 9055                        start.row,
 9056                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9057                    );
 9058                    start..end
 9059                } else {
 9060                    start..start
 9061                }
 9062            }
 9063
 9064            fn comment_suffix_range(
 9065                snapshot: &MultiBufferSnapshot,
 9066                row: MultiBufferRow,
 9067                comment_suffix: &str,
 9068                comment_suffix_has_leading_space: bool,
 9069            ) -> Range<Point> {
 9070                let end = Point::new(row.0, snapshot.line_len(row));
 9071                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9072
 9073                let mut line_end_bytes = snapshot
 9074                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9075                    .flatten()
 9076                    .copied();
 9077
 9078                let leading_space_len = if suffix_start_column > 0
 9079                    && line_end_bytes.next() == Some(b' ')
 9080                    && comment_suffix_has_leading_space
 9081                {
 9082                    1
 9083                } else {
 9084                    0
 9085                };
 9086
 9087                // If this line currently begins with the line comment prefix, then record
 9088                // the range containing the prefix.
 9089                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9090                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9091                    start..end
 9092                } else {
 9093                    end..end
 9094                }
 9095            }
 9096
 9097            // TODO: Handle selections that cross excerpts
 9098            for selection in &mut selections {
 9099                let start_column = snapshot
 9100                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9101                    .len;
 9102                let language = if let Some(language) =
 9103                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9104                {
 9105                    language
 9106                } else {
 9107                    continue;
 9108                };
 9109
 9110                selection_edit_ranges.clear();
 9111
 9112                // If multiple selections contain a given row, avoid processing that
 9113                // row more than once.
 9114                let mut start_row = MultiBufferRow(selection.start.row);
 9115                if last_toggled_row == Some(start_row) {
 9116                    start_row = start_row.next_row();
 9117                }
 9118                let end_row =
 9119                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9120                        MultiBufferRow(selection.end.row - 1)
 9121                    } else {
 9122                        MultiBufferRow(selection.end.row)
 9123                    };
 9124                last_toggled_row = Some(end_row);
 9125
 9126                if start_row > end_row {
 9127                    continue;
 9128                }
 9129
 9130                // If the language has line comments, toggle those.
 9131                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9132
 9133                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9134                if ignore_indent {
 9135                    full_comment_prefixes = full_comment_prefixes
 9136                        .into_iter()
 9137                        .map(|s| Arc::from(s.trim_end()))
 9138                        .collect();
 9139                }
 9140
 9141                if !full_comment_prefixes.is_empty() {
 9142                    let first_prefix = full_comment_prefixes
 9143                        .first()
 9144                        .expect("prefixes is non-empty");
 9145                    let prefix_trimmed_lengths = full_comment_prefixes
 9146                        .iter()
 9147                        .map(|p| p.trim_end_matches(' ').len())
 9148                        .collect::<SmallVec<[usize; 4]>>();
 9149
 9150                    let mut all_selection_lines_are_comments = true;
 9151
 9152                    for row in start_row.0..=end_row.0 {
 9153                        let row = MultiBufferRow(row);
 9154                        if start_row < end_row && snapshot.is_line_blank(row) {
 9155                            continue;
 9156                        }
 9157
 9158                        let prefix_range = full_comment_prefixes
 9159                            .iter()
 9160                            .zip(prefix_trimmed_lengths.iter().copied())
 9161                            .map(|(prefix, trimmed_prefix_len)| {
 9162                                comment_prefix_range(
 9163                                    snapshot.deref(),
 9164                                    row,
 9165                                    &prefix[..trimmed_prefix_len],
 9166                                    &prefix[trimmed_prefix_len..],
 9167                                    ignore_indent,
 9168                                )
 9169                            })
 9170                            .max_by_key(|range| range.end.column - range.start.column)
 9171                            .expect("prefixes is non-empty");
 9172
 9173                        if prefix_range.is_empty() {
 9174                            all_selection_lines_are_comments = false;
 9175                        }
 9176
 9177                        selection_edit_ranges.push(prefix_range);
 9178                    }
 9179
 9180                    if all_selection_lines_are_comments {
 9181                        edits.extend(
 9182                            selection_edit_ranges
 9183                                .iter()
 9184                                .cloned()
 9185                                .map(|range| (range, empty_str.clone())),
 9186                        );
 9187                    } else {
 9188                        let min_column = selection_edit_ranges
 9189                            .iter()
 9190                            .map(|range| range.start.column)
 9191                            .min()
 9192                            .unwrap_or(0);
 9193                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9194                            let position = Point::new(range.start.row, min_column);
 9195                            (position..position, first_prefix.clone())
 9196                        }));
 9197                    }
 9198                } else if let Some((full_comment_prefix, comment_suffix)) =
 9199                    language.block_comment_delimiters()
 9200                {
 9201                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9202                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9203                    let prefix_range = comment_prefix_range(
 9204                        snapshot.deref(),
 9205                        start_row,
 9206                        comment_prefix,
 9207                        comment_prefix_whitespace,
 9208                        ignore_indent,
 9209                    );
 9210                    let suffix_range = comment_suffix_range(
 9211                        snapshot.deref(),
 9212                        end_row,
 9213                        comment_suffix.trim_start_matches(' '),
 9214                        comment_suffix.starts_with(' '),
 9215                    );
 9216
 9217                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9218                        edits.push((
 9219                            prefix_range.start..prefix_range.start,
 9220                            full_comment_prefix.clone(),
 9221                        ));
 9222                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9223                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9224                    } else {
 9225                        edits.push((prefix_range, empty_str.clone()));
 9226                        edits.push((suffix_range, empty_str.clone()));
 9227                    }
 9228                } else {
 9229                    continue;
 9230                }
 9231            }
 9232
 9233            drop(snapshot);
 9234            this.buffer.update(cx, |buffer, cx| {
 9235                buffer.edit(edits, None, cx);
 9236            });
 9237
 9238            // Adjust selections so that they end before any comment suffixes that
 9239            // were inserted.
 9240            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9241            let mut selections = this.selections.all::<Point>(cx);
 9242            let snapshot = this.buffer.read(cx).read(cx);
 9243            for selection in &mut selections {
 9244                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9245                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9246                        Ordering::Less => {
 9247                            suffixes_inserted.next();
 9248                            continue;
 9249                        }
 9250                        Ordering::Greater => break,
 9251                        Ordering::Equal => {
 9252                            if selection.end.column == snapshot.line_len(row) {
 9253                                if selection.is_empty() {
 9254                                    selection.start.column -= suffix_len as u32;
 9255                                }
 9256                                selection.end.column -= suffix_len as u32;
 9257                            }
 9258                            break;
 9259                        }
 9260                    }
 9261                }
 9262            }
 9263
 9264            drop(snapshot);
 9265            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9266
 9267            let selections = this.selections.all::<Point>(cx);
 9268            let selections_on_single_row = selections.windows(2).all(|selections| {
 9269                selections[0].start.row == selections[1].start.row
 9270                    && selections[0].end.row == selections[1].end.row
 9271                    && selections[0].start.row == selections[0].end.row
 9272            });
 9273            let selections_selecting = selections
 9274                .iter()
 9275                .any(|selection| selection.start != selection.end);
 9276            let advance_downwards = action.advance_downwards
 9277                && selections_on_single_row
 9278                && !selections_selecting
 9279                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9280
 9281            if advance_downwards {
 9282                let snapshot = this.buffer.read(cx).snapshot(cx);
 9283
 9284                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9285                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9286                        let mut point = display_point.to_point(display_snapshot);
 9287                        point.row += 1;
 9288                        point = snapshot.clip_point(point, Bias::Left);
 9289                        let display_point = point.to_display_point(display_snapshot);
 9290                        let goal = SelectionGoal::HorizontalPosition(
 9291                            display_snapshot
 9292                                .x_for_display_point(display_point, text_layout_details)
 9293                                .into(),
 9294                        );
 9295                        (display_point, goal)
 9296                    })
 9297                });
 9298            }
 9299        });
 9300    }
 9301
 9302    pub fn select_enclosing_symbol(
 9303        &mut self,
 9304        _: &SelectEnclosingSymbol,
 9305        cx: &mut ViewContext<Self>,
 9306    ) {
 9307        let buffer = self.buffer.read(cx).snapshot(cx);
 9308        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9309
 9310        fn update_selection(
 9311            selection: &Selection<usize>,
 9312            buffer_snap: &MultiBufferSnapshot,
 9313        ) -> Option<Selection<usize>> {
 9314            let cursor = selection.head();
 9315            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9316            for symbol in symbols.iter().rev() {
 9317                let start = symbol.range.start.to_offset(buffer_snap);
 9318                let end = symbol.range.end.to_offset(buffer_snap);
 9319                let new_range = start..end;
 9320                if start < selection.start || end > selection.end {
 9321                    return Some(Selection {
 9322                        id: selection.id,
 9323                        start: new_range.start,
 9324                        end: new_range.end,
 9325                        goal: SelectionGoal::None,
 9326                        reversed: selection.reversed,
 9327                    });
 9328                }
 9329            }
 9330            None
 9331        }
 9332
 9333        let mut selected_larger_symbol = false;
 9334        let new_selections = old_selections
 9335            .iter()
 9336            .map(|selection| match update_selection(selection, &buffer) {
 9337                Some(new_selection) => {
 9338                    if new_selection.range() != selection.range() {
 9339                        selected_larger_symbol = true;
 9340                    }
 9341                    new_selection
 9342                }
 9343                None => selection.clone(),
 9344            })
 9345            .collect::<Vec<_>>();
 9346
 9347        if selected_larger_symbol {
 9348            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9349                s.select(new_selections);
 9350            });
 9351        }
 9352    }
 9353
 9354    pub fn select_larger_syntax_node(
 9355        &mut self,
 9356        _: &SelectLargerSyntaxNode,
 9357        cx: &mut ViewContext<Self>,
 9358    ) {
 9359        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9360        let buffer = self.buffer.read(cx).snapshot(cx);
 9361        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9362
 9363        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9364        let mut selected_larger_node = false;
 9365        let new_selections = old_selections
 9366            .iter()
 9367            .map(|selection| {
 9368                let old_range = selection.start..selection.end;
 9369                let mut new_range = old_range.clone();
 9370                while let Some(containing_range) =
 9371                    buffer.range_for_syntax_ancestor(new_range.clone())
 9372                {
 9373                    new_range = containing_range;
 9374                    if !display_map.intersects_fold(new_range.start)
 9375                        && !display_map.intersects_fold(new_range.end)
 9376                    {
 9377                        break;
 9378                    }
 9379                }
 9380
 9381                selected_larger_node |= new_range != old_range;
 9382                Selection {
 9383                    id: selection.id,
 9384                    start: new_range.start,
 9385                    end: new_range.end,
 9386                    goal: SelectionGoal::None,
 9387                    reversed: selection.reversed,
 9388                }
 9389            })
 9390            .collect::<Vec<_>>();
 9391
 9392        if selected_larger_node {
 9393            stack.push(old_selections);
 9394            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9395                s.select(new_selections);
 9396            });
 9397        }
 9398        self.select_larger_syntax_node_stack = stack;
 9399    }
 9400
 9401    pub fn select_smaller_syntax_node(
 9402        &mut self,
 9403        _: &SelectSmallerSyntaxNode,
 9404        cx: &mut ViewContext<Self>,
 9405    ) {
 9406        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9407        if let Some(selections) = stack.pop() {
 9408            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9409                s.select(selections.to_vec());
 9410            });
 9411        }
 9412        self.select_larger_syntax_node_stack = stack;
 9413    }
 9414
 9415    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9416        if !EditorSettings::get_global(cx).gutter.runnables {
 9417            self.clear_tasks();
 9418            return Task::ready(());
 9419        }
 9420        let project = self.project.as_ref().map(Model::downgrade);
 9421        cx.spawn(|this, mut cx| async move {
 9422            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9423            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9424                return;
 9425            };
 9426            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9427                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9428            }) else {
 9429                return;
 9430            };
 9431
 9432            let hide_runnables = project
 9433                .update(&mut cx, |project, cx| {
 9434                    // Do not display any test indicators in non-dev server remote projects.
 9435                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9436                })
 9437                .unwrap_or(true);
 9438            if hide_runnables {
 9439                return;
 9440            }
 9441            let new_rows =
 9442                cx.background_executor()
 9443                    .spawn({
 9444                        let snapshot = display_snapshot.clone();
 9445                        async move {
 9446                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9447                        }
 9448                    })
 9449                    .await;
 9450            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9451
 9452            this.update(&mut cx, |this, _| {
 9453                this.clear_tasks();
 9454                for (key, value) in rows {
 9455                    this.insert_tasks(key, value);
 9456                }
 9457            })
 9458            .ok();
 9459        })
 9460    }
 9461    fn fetch_runnable_ranges(
 9462        snapshot: &DisplaySnapshot,
 9463        range: Range<Anchor>,
 9464    ) -> Vec<language::RunnableRange> {
 9465        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9466    }
 9467
 9468    fn runnable_rows(
 9469        project: Model<Project>,
 9470        snapshot: DisplaySnapshot,
 9471        runnable_ranges: Vec<RunnableRange>,
 9472        mut cx: AsyncWindowContext,
 9473    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9474        runnable_ranges
 9475            .into_iter()
 9476            .filter_map(|mut runnable| {
 9477                let tasks = cx
 9478                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9479                    .ok()?;
 9480                if tasks.is_empty() {
 9481                    return None;
 9482                }
 9483
 9484                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9485
 9486                let row = snapshot
 9487                    .buffer_snapshot
 9488                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9489                    .1
 9490                    .start
 9491                    .row;
 9492
 9493                let context_range =
 9494                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9495                Some((
 9496                    (runnable.buffer_id, row),
 9497                    RunnableTasks {
 9498                        templates: tasks,
 9499                        offset: MultiBufferOffset(runnable.run_range.start),
 9500                        context_range,
 9501                        column: point.column,
 9502                        extra_variables: runnable.extra_captures,
 9503                    },
 9504                ))
 9505            })
 9506            .collect()
 9507    }
 9508
 9509    fn templates_with_tags(
 9510        project: &Model<Project>,
 9511        runnable: &mut Runnable,
 9512        cx: &WindowContext<'_>,
 9513    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9514        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9515            let (worktree_id, file) = project
 9516                .buffer_for_id(runnable.buffer, cx)
 9517                .and_then(|buffer| buffer.read(cx).file())
 9518                .map(|file| (file.worktree_id(cx), file.clone()))
 9519                .unzip();
 9520
 9521            (
 9522                project.task_store().read(cx).task_inventory().cloned(),
 9523                worktree_id,
 9524                file,
 9525            )
 9526        });
 9527
 9528        let tags = mem::take(&mut runnable.tags);
 9529        let mut tags: Vec<_> = tags
 9530            .into_iter()
 9531            .flat_map(|tag| {
 9532                let tag = tag.0.clone();
 9533                inventory
 9534                    .as_ref()
 9535                    .into_iter()
 9536                    .flat_map(|inventory| {
 9537                        inventory.read(cx).list_tasks(
 9538                            file.clone(),
 9539                            Some(runnable.language.clone()),
 9540                            worktree_id,
 9541                            cx,
 9542                        )
 9543                    })
 9544                    .filter(move |(_, template)| {
 9545                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9546                    })
 9547            })
 9548            .sorted_by_key(|(kind, _)| kind.to_owned())
 9549            .collect();
 9550        if let Some((leading_tag_source, _)) = tags.first() {
 9551            // Strongest source wins; if we have worktree tag binding, prefer that to
 9552            // global and language bindings;
 9553            // if we have a global binding, prefer that to language binding.
 9554            let first_mismatch = tags
 9555                .iter()
 9556                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9557            if let Some(index) = first_mismatch {
 9558                tags.truncate(index);
 9559            }
 9560        }
 9561
 9562        tags
 9563    }
 9564
 9565    pub fn move_to_enclosing_bracket(
 9566        &mut self,
 9567        _: &MoveToEnclosingBracket,
 9568        cx: &mut ViewContext<Self>,
 9569    ) {
 9570        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9571            s.move_offsets_with(|snapshot, selection| {
 9572                let Some(enclosing_bracket_ranges) =
 9573                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9574                else {
 9575                    return;
 9576                };
 9577
 9578                let mut best_length = usize::MAX;
 9579                let mut best_inside = false;
 9580                let mut best_in_bracket_range = false;
 9581                let mut best_destination = None;
 9582                for (open, close) in enclosing_bracket_ranges {
 9583                    let close = close.to_inclusive();
 9584                    let length = close.end() - open.start;
 9585                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9586                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9587                        || close.contains(&selection.head());
 9588
 9589                    // If best is next to a bracket and current isn't, skip
 9590                    if !in_bracket_range && best_in_bracket_range {
 9591                        continue;
 9592                    }
 9593
 9594                    // Prefer smaller lengths unless best is inside and current isn't
 9595                    if length > best_length && (best_inside || !inside) {
 9596                        continue;
 9597                    }
 9598
 9599                    best_length = length;
 9600                    best_inside = inside;
 9601                    best_in_bracket_range = in_bracket_range;
 9602                    best_destination = Some(
 9603                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9604                            if inside {
 9605                                open.end
 9606                            } else {
 9607                                open.start
 9608                            }
 9609                        } else if inside {
 9610                            *close.start()
 9611                        } else {
 9612                            *close.end()
 9613                        },
 9614                    );
 9615                }
 9616
 9617                if let Some(destination) = best_destination {
 9618                    selection.collapse_to(destination, SelectionGoal::None);
 9619                }
 9620            })
 9621        });
 9622    }
 9623
 9624    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9625        self.end_selection(cx);
 9626        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9627        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9628            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9629            self.select_next_state = entry.select_next_state;
 9630            self.select_prev_state = entry.select_prev_state;
 9631            self.add_selections_state = entry.add_selections_state;
 9632            self.request_autoscroll(Autoscroll::newest(), cx);
 9633        }
 9634        self.selection_history.mode = SelectionHistoryMode::Normal;
 9635    }
 9636
 9637    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9638        self.end_selection(cx);
 9639        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9640        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9641            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9642            self.select_next_state = entry.select_next_state;
 9643            self.select_prev_state = entry.select_prev_state;
 9644            self.add_selections_state = entry.add_selections_state;
 9645            self.request_autoscroll(Autoscroll::newest(), cx);
 9646        }
 9647        self.selection_history.mode = SelectionHistoryMode::Normal;
 9648    }
 9649
 9650    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9651        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9652    }
 9653
 9654    pub fn expand_excerpts_down(
 9655        &mut self,
 9656        action: &ExpandExcerptsDown,
 9657        cx: &mut ViewContext<Self>,
 9658    ) {
 9659        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9660    }
 9661
 9662    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9663        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9664    }
 9665
 9666    pub fn expand_excerpts_for_direction(
 9667        &mut self,
 9668        lines: u32,
 9669        direction: ExpandExcerptDirection,
 9670        cx: &mut ViewContext<Self>,
 9671    ) {
 9672        let selections = self.selections.disjoint_anchors();
 9673
 9674        let lines = if lines == 0 {
 9675            EditorSettings::get_global(cx).expand_excerpt_lines
 9676        } else {
 9677            lines
 9678        };
 9679
 9680        self.buffer.update(cx, |buffer, cx| {
 9681            buffer.expand_excerpts(
 9682                selections
 9683                    .iter()
 9684                    .map(|selection| selection.head().excerpt_id)
 9685                    .dedup(),
 9686                lines,
 9687                direction,
 9688                cx,
 9689            )
 9690        })
 9691    }
 9692
 9693    pub fn expand_excerpt(
 9694        &mut self,
 9695        excerpt: ExcerptId,
 9696        direction: ExpandExcerptDirection,
 9697        cx: &mut ViewContext<Self>,
 9698    ) {
 9699        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9700        self.buffer.update(cx, |buffer, cx| {
 9701            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9702        })
 9703    }
 9704
 9705    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9706        self.go_to_diagnostic_impl(Direction::Next, cx)
 9707    }
 9708
 9709    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9710        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9711    }
 9712
 9713    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9714        let buffer = self.buffer.read(cx).snapshot(cx);
 9715        let selection = self.selections.newest::<usize>(cx);
 9716
 9717        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9718        if direction == Direction::Next {
 9719            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9720                let (group_id, jump_to) = popover.activation_info();
 9721                if self.activate_diagnostics(group_id, cx) {
 9722                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9723                        let mut new_selection = s.newest_anchor().clone();
 9724                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9725                        s.select_anchors(vec![new_selection.clone()]);
 9726                    });
 9727                }
 9728                return;
 9729            }
 9730        }
 9731
 9732        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9733            active_diagnostics
 9734                .primary_range
 9735                .to_offset(&buffer)
 9736                .to_inclusive()
 9737        });
 9738        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9739            if active_primary_range.contains(&selection.head()) {
 9740                *active_primary_range.start()
 9741            } else {
 9742                selection.head()
 9743            }
 9744        } else {
 9745            selection.head()
 9746        };
 9747        let snapshot = self.snapshot(cx);
 9748        loop {
 9749            let diagnostics = if direction == Direction::Prev {
 9750                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9751            } else {
 9752                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9753            }
 9754            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9755            let group = diagnostics
 9756                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9757                // be sorted in a stable way
 9758                // skip until we are at current active diagnostic, if it exists
 9759                .skip_while(|entry| {
 9760                    (match direction {
 9761                        Direction::Prev => entry.range.start >= search_start,
 9762                        Direction::Next => entry.range.start <= search_start,
 9763                    }) && self
 9764                        .active_diagnostics
 9765                        .as_ref()
 9766                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9767                })
 9768                .find_map(|entry| {
 9769                    if entry.diagnostic.is_primary
 9770                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9771                        && !entry.range.is_empty()
 9772                        // if we match with the active diagnostic, skip it
 9773                        && Some(entry.diagnostic.group_id)
 9774                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9775                    {
 9776                        Some((entry.range, entry.diagnostic.group_id))
 9777                    } else {
 9778                        None
 9779                    }
 9780                });
 9781
 9782            if let Some((primary_range, group_id)) = group {
 9783                if self.activate_diagnostics(group_id, cx) {
 9784                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9785                        s.select(vec![Selection {
 9786                            id: selection.id,
 9787                            start: primary_range.start,
 9788                            end: primary_range.start,
 9789                            reversed: false,
 9790                            goal: SelectionGoal::None,
 9791                        }]);
 9792                    });
 9793                }
 9794                break;
 9795            } else {
 9796                // Cycle around to the start of the buffer, potentially moving back to the start of
 9797                // the currently active diagnostic.
 9798                active_primary_range.take();
 9799                if direction == Direction::Prev {
 9800                    if search_start == buffer.len() {
 9801                        break;
 9802                    } else {
 9803                        search_start = buffer.len();
 9804                    }
 9805                } else if search_start == 0 {
 9806                    break;
 9807                } else {
 9808                    search_start = 0;
 9809                }
 9810            }
 9811        }
 9812    }
 9813
 9814    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9815        let snapshot = self
 9816            .display_map
 9817            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9818        let selection = self.selections.newest::<Point>(cx);
 9819        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9820    }
 9821
 9822    fn go_to_hunk_after_position(
 9823        &mut self,
 9824        snapshot: &DisplaySnapshot,
 9825        position: Point,
 9826        cx: &mut ViewContext<'_, Editor>,
 9827    ) -> Option<MultiBufferDiffHunk> {
 9828        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9829            snapshot,
 9830            position,
 9831            false,
 9832            snapshot
 9833                .buffer_snapshot
 9834                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9835            cx,
 9836        ) {
 9837            return Some(hunk);
 9838        }
 9839
 9840        let wrapped_point = Point::zero();
 9841        self.go_to_next_hunk_in_direction(
 9842            snapshot,
 9843            wrapped_point,
 9844            true,
 9845            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9846                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9847            ),
 9848            cx,
 9849        )
 9850    }
 9851
 9852    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9853        let snapshot = self
 9854            .display_map
 9855            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9856        let selection = self.selections.newest::<Point>(cx);
 9857
 9858        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9859    }
 9860
 9861    fn go_to_hunk_before_position(
 9862        &mut self,
 9863        snapshot: &DisplaySnapshot,
 9864        position: Point,
 9865        cx: &mut ViewContext<'_, Editor>,
 9866    ) -> Option<MultiBufferDiffHunk> {
 9867        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9868            snapshot,
 9869            position,
 9870            false,
 9871            snapshot
 9872                .buffer_snapshot
 9873                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9874            cx,
 9875        ) {
 9876            return Some(hunk);
 9877        }
 9878
 9879        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9880        self.go_to_next_hunk_in_direction(
 9881            snapshot,
 9882            wrapped_point,
 9883            true,
 9884            snapshot
 9885                .buffer_snapshot
 9886                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9887            cx,
 9888        )
 9889    }
 9890
 9891    fn go_to_next_hunk_in_direction(
 9892        &mut self,
 9893        snapshot: &DisplaySnapshot,
 9894        initial_point: Point,
 9895        is_wrapped: bool,
 9896        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9897        cx: &mut ViewContext<Editor>,
 9898    ) -> Option<MultiBufferDiffHunk> {
 9899        let display_point = initial_point.to_display_point(snapshot);
 9900        let mut hunks = hunks
 9901            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9902            .filter(|(display_hunk, _)| {
 9903                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9904            })
 9905            .dedup();
 9906
 9907        if let Some((display_hunk, hunk)) = hunks.next() {
 9908            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9909                let row = display_hunk.start_display_row();
 9910                let point = DisplayPoint::new(row, 0);
 9911                s.select_display_ranges([point..point]);
 9912            });
 9913
 9914            Some(hunk)
 9915        } else {
 9916            None
 9917        }
 9918    }
 9919
 9920    pub fn go_to_definition(
 9921        &mut self,
 9922        _: &GoToDefinition,
 9923        cx: &mut ViewContext<Self>,
 9924    ) -> Task<Result<Navigated>> {
 9925        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9926        cx.spawn(|editor, mut cx| async move {
 9927            if definition.await? == Navigated::Yes {
 9928                return Ok(Navigated::Yes);
 9929            }
 9930            match editor.update(&mut cx, |editor, cx| {
 9931                editor.find_all_references(&FindAllReferences, cx)
 9932            })? {
 9933                Some(references) => references.await,
 9934                None => Ok(Navigated::No),
 9935            }
 9936        })
 9937    }
 9938
 9939    pub fn go_to_declaration(
 9940        &mut self,
 9941        _: &GoToDeclaration,
 9942        cx: &mut ViewContext<Self>,
 9943    ) -> Task<Result<Navigated>> {
 9944        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9945    }
 9946
 9947    pub fn go_to_declaration_split(
 9948        &mut self,
 9949        _: &GoToDeclaration,
 9950        cx: &mut ViewContext<Self>,
 9951    ) -> Task<Result<Navigated>> {
 9952        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9953    }
 9954
 9955    pub fn go_to_implementation(
 9956        &mut self,
 9957        _: &GoToImplementation,
 9958        cx: &mut ViewContext<Self>,
 9959    ) -> Task<Result<Navigated>> {
 9960        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9961    }
 9962
 9963    pub fn go_to_implementation_split(
 9964        &mut self,
 9965        _: &GoToImplementationSplit,
 9966        cx: &mut ViewContext<Self>,
 9967    ) -> Task<Result<Navigated>> {
 9968        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9969    }
 9970
 9971    pub fn go_to_type_definition(
 9972        &mut self,
 9973        _: &GoToTypeDefinition,
 9974        cx: &mut ViewContext<Self>,
 9975    ) -> Task<Result<Navigated>> {
 9976        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9977    }
 9978
 9979    pub fn go_to_definition_split(
 9980        &mut self,
 9981        _: &GoToDefinitionSplit,
 9982        cx: &mut ViewContext<Self>,
 9983    ) -> Task<Result<Navigated>> {
 9984        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9985    }
 9986
 9987    pub fn go_to_type_definition_split(
 9988        &mut self,
 9989        _: &GoToTypeDefinitionSplit,
 9990        cx: &mut ViewContext<Self>,
 9991    ) -> Task<Result<Navigated>> {
 9992        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9993    }
 9994
 9995    fn go_to_definition_of_kind(
 9996        &mut self,
 9997        kind: GotoDefinitionKind,
 9998        split: bool,
 9999        cx: &mut ViewContext<Self>,
10000    ) -> Task<Result<Navigated>> {
10001        let Some(provider) = self.semantics_provider.clone() else {
10002            return Task::ready(Ok(Navigated::No));
10003        };
10004        let head = self.selections.newest::<usize>(cx).head();
10005        let buffer = self.buffer.read(cx);
10006        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10007            text_anchor
10008        } else {
10009            return Task::ready(Ok(Navigated::No));
10010        };
10011
10012        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10013            return Task::ready(Ok(Navigated::No));
10014        };
10015
10016        cx.spawn(|editor, mut cx| async move {
10017            let definitions = definitions.await?;
10018            let navigated = editor
10019                .update(&mut cx, |editor, cx| {
10020                    editor.navigate_to_hover_links(
10021                        Some(kind),
10022                        definitions
10023                            .into_iter()
10024                            .filter(|location| {
10025                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10026                            })
10027                            .map(HoverLink::Text)
10028                            .collect::<Vec<_>>(),
10029                        split,
10030                        cx,
10031                    )
10032                })?
10033                .await?;
10034            anyhow::Ok(navigated)
10035        })
10036    }
10037
10038    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
10039        let position = self.selections.newest_anchor().head();
10040        let Some((buffer, buffer_position)) =
10041            self.buffer.read(cx).text_anchor_for_position(position, cx)
10042        else {
10043            return;
10044        };
10045
10046        cx.spawn(|editor, mut cx| async move {
10047            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10048                editor.update(&mut cx, |_, cx| {
10049                    cx.open_url(&url);
10050                })
10051            } else {
10052                Ok(())
10053            }
10054        })
10055        .detach();
10056    }
10057
10058    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10059        let Some(workspace) = self.workspace() else {
10060            return;
10061        };
10062
10063        let position = self.selections.newest_anchor().head();
10064
10065        let Some((buffer, buffer_position)) =
10066            self.buffer.read(cx).text_anchor_for_position(position, cx)
10067        else {
10068            return;
10069        };
10070
10071        let project = self.project.clone();
10072
10073        cx.spawn(|_, mut cx| async move {
10074            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10075
10076            if let Some((_, path)) = result {
10077                workspace
10078                    .update(&mut cx, |workspace, cx| {
10079                        workspace.open_resolved_path(path, cx)
10080                    })?
10081                    .await?;
10082            }
10083            anyhow::Ok(())
10084        })
10085        .detach();
10086    }
10087
10088    pub(crate) fn navigate_to_hover_links(
10089        &mut self,
10090        kind: Option<GotoDefinitionKind>,
10091        mut definitions: Vec<HoverLink>,
10092        split: bool,
10093        cx: &mut ViewContext<Editor>,
10094    ) -> Task<Result<Navigated>> {
10095        // If there is one definition, just open it directly
10096        if definitions.len() == 1 {
10097            let definition = definitions.pop().unwrap();
10098
10099            enum TargetTaskResult {
10100                Location(Option<Location>),
10101                AlreadyNavigated,
10102            }
10103
10104            let target_task = match definition {
10105                HoverLink::Text(link) => {
10106                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10107                }
10108                HoverLink::InlayHint(lsp_location, server_id) => {
10109                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10110                    cx.background_executor().spawn(async move {
10111                        let location = computation.await?;
10112                        Ok(TargetTaskResult::Location(location))
10113                    })
10114                }
10115                HoverLink::Url(url) => {
10116                    cx.open_url(&url);
10117                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10118                }
10119                HoverLink::File(path) => {
10120                    if let Some(workspace) = self.workspace() {
10121                        cx.spawn(|_, mut cx| async move {
10122                            workspace
10123                                .update(&mut cx, |workspace, cx| {
10124                                    workspace.open_resolved_path(path, cx)
10125                                })?
10126                                .await
10127                                .map(|_| TargetTaskResult::AlreadyNavigated)
10128                        })
10129                    } else {
10130                        Task::ready(Ok(TargetTaskResult::Location(None)))
10131                    }
10132                }
10133            };
10134            cx.spawn(|editor, mut cx| async move {
10135                let target = match target_task.await.context("target resolution task")? {
10136                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10137                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10138                    TargetTaskResult::Location(Some(target)) => target,
10139                };
10140
10141                editor.update(&mut cx, |editor, cx| {
10142                    let Some(workspace) = editor.workspace() else {
10143                        return Navigated::No;
10144                    };
10145                    let pane = workspace.read(cx).active_pane().clone();
10146
10147                    let range = target.range.to_offset(target.buffer.read(cx));
10148                    let range = editor.range_for_match(&range);
10149
10150                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10151                        let buffer = target.buffer.read(cx);
10152                        let range = check_multiline_range(buffer, range);
10153                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10154                            s.select_ranges([range]);
10155                        });
10156                    } else {
10157                        cx.window_context().defer(move |cx| {
10158                            let target_editor: View<Self> =
10159                                workspace.update(cx, |workspace, cx| {
10160                                    let pane = if split {
10161                                        workspace.adjacent_pane(cx)
10162                                    } else {
10163                                        workspace.active_pane().clone()
10164                                    };
10165
10166                                    workspace.open_project_item(
10167                                        pane,
10168                                        target.buffer.clone(),
10169                                        true,
10170                                        true,
10171                                        cx,
10172                                    )
10173                                });
10174                            target_editor.update(cx, |target_editor, cx| {
10175                                // When selecting a definition in a different buffer, disable the nav history
10176                                // to avoid creating a history entry at the previous cursor location.
10177                                pane.update(cx, |pane, _| pane.disable_history());
10178                                let buffer = target.buffer.read(cx);
10179                                let range = check_multiline_range(buffer, range);
10180                                target_editor.change_selections(
10181                                    Some(Autoscroll::focused()),
10182                                    cx,
10183                                    |s| {
10184                                        s.select_ranges([range]);
10185                                    },
10186                                );
10187                                pane.update(cx, |pane, _| pane.enable_history());
10188                            });
10189                        });
10190                    }
10191                    Navigated::Yes
10192                })
10193            })
10194        } else if !definitions.is_empty() {
10195            cx.spawn(|editor, mut cx| async move {
10196                let (title, location_tasks, workspace) = editor
10197                    .update(&mut cx, |editor, cx| {
10198                        let tab_kind = match kind {
10199                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10200                            _ => "Definitions",
10201                        };
10202                        let title = definitions
10203                            .iter()
10204                            .find_map(|definition| match definition {
10205                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10206                                    let buffer = origin.buffer.read(cx);
10207                                    format!(
10208                                        "{} for {}",
10209                                        tab_kind,
10210                                        buffer
10211                                            .text_for_range(origin.range.clone())
10212                                            .collect::<String>()
10213                                    )
10214                                }),
10215                                HoverLink::InlayHint(_, _) => None,
10216                                HoverLink::Url(_) => None,
10217                                HoverLink::File(_) => None,
10218                            })
10219                            .unwrap_or(tab_kind.to_string());
10220                        let location_tasks = definitions
10221                            .into_iter()
10222                            .map(|definition| match definition {
10223                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10224                                HoverLink::InlayHint(lsp_location, server_id) => {
10225                                    editor.compute_target_location(lsp_location, server_id, cx)
10226                                }
10227                                HoverLink::Url(_) => Task::ready(Ok(None)),
10228                                HoverLink::File(_) => Task::ready(Ok(None)),
10229                            })
10230                            .collect::<Vec<_>>();
10231                        (title, location_tasks, editor.workspace().clone())
10232                    })
10233                    .context("location tasks preparation")?;
10234
10235                let locations = future::join_all(location_tasks)
10236                    .await
10237                    .into_iter()
10238                    .filter_map(|location| location.transpose())
10239                    .collect::<Result<_>>()
10240                    .context("location tasks")?;
10241
10242                let Some(workspace) = workspace else {
10243                    return Ok(Navigated::No);
10244                };
10245                let opened = workspace
10246                    .update(&mut cx, |workspace, cx| {
10247                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10248                    })
10249                    .ok();
10250
10251                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10252            })
10253        } else {
10254            Task::ready(Ok(Navigated::No))
10255        }
10256    }
10257
10258    fn compute_target_location(
10259        &self,
10260        lsp_location: lsp::Location,
10261        server_id: LanguageServerId,
10262        cx: &mut ViewContext<Self>,
10263    ) -> Task<anyhow::Result<Option<Location>>> {
10264        let Some(project) = self.project.clone() else {
10265            return Task::Ready(Some(Ok(None)));
10266        };
10267
10268        cx.spawn(move |editor, mut cx| async move {
10269            let location_task = editor.update(&mut cx, |_, cx| {
10270                project.update(cx, |project, cx| {
10271                    let language_server_name = project
10272                        .language_server_statuses(cx)
10273                        .find(|(id, _)| server_id == *id)
10274                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10275                    language_server_name.map(|language_server_name| {
10276                        project.open_local_buffer_via_lsp(
10277                            lsp_location.uri.clone(),
10278                            server_id,
10279                            language_server_name,
10280                            cx,
10281                        )
10282                    })
10283                })
10284            })?;
10285            let location = match location_task {
10286                Some(task) => Some({
10287                    let target_buffer_handle = task.await.context("open local buffer")?;
10288                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10289                        let target_start = target_buffer
10290                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10291                        let target_end = target_buffer
10292                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10293                        target_buffer.anchor_after(target_start)
10294                            ..target_buffer.anchor_before(target_end)
10295                    })?;
10296                    Location {
10297                        buffer: target_buffer_handle,
10298                        range,
10299                    }
10300                }),
10301                None => None,
10302            };
10303            Ok(location)
10304        })
10305    }
10306
10307    pub fn find_all_references(
10308        &mut self,
10309        _: &FindAllReferences,
10310        cx: &mut ViewContext<Self>,
10311    ) -> Option<Task<Result<Navigated>>> {
10312        let selection = self.selections.newest::<usize>(cx);
10313        let multi_buffer = self.buffer.read(cx);
10314        let head = selection.head();
10315
10316        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10317        let head_anchor = multi_buffer_snapshot.anchor_at(
10318            head,
10319            if head < selection.tail() {
10320                Bias::Right
10321            } else {
10322                Bias::Left
10323            },
10324        );
10325
10326        match self
10327            .find_all_references_task_sources
10328            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10329        {
10330            Ok(_) => {
10331                log::info!(
10332                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10333                );
10334                return None;
10335            }
10336            Err(i) => {
10337                self.find_all_references_task_sources.insert(i, head_anchor);
10338            }
10339        }
10340
10341        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10342        let workspace = self.workspace()?;
10343        let project = workspace.read(cx).project().clone();
10344        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10345        Some(cx.spawn(|editor, mut cx| async move {
10346            let _cleanup = defer({
10347                let mut cx = cx.clone();
10348                move || {
10349                    let _ = editor.update(&mut cx, |editor, _| {
10350                        if let Ok(i) =
10351                            editor
10352                                .find_all_references_task_sources
10353                                .binary_search_by(|anchor| {
10354                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10355                                })
10356                        {
10357                            editor.find_all_references_task_sources.remove(i);
10358                        }
10359                    });
10360                }
10361            });
10362
10363            let locations = references.await?;
10364            if locations.is_empty() {
10365                return anyhow::Ok(Navigated::No);
10366            }
10367
10368            workspace.update(&mut cx, |workspace, cx| {
10369                let title = locations
10370                    .first()
10371                    .as_ref()
10372                    .map(|location| {
10373                        let buffer = location.buffer.read(cx);
10374                        format!(
10375                            "References to `{}`",
10376                            buffer
10377                                .text_for_range(location.range.clone())
10378                                .collect::<String>()
10379                        )
10380                    })
10381                    .unwrap();
10382                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10383                Navigated::Yes
10384            })
10385        }))
10386    }
10387
10388    /// Opens a multibuffer with the given project locations in it
10389    pub fn open_locations_in_multibuffer(
10390        workspace: &mut Workspace,
10391        mut locations: Vec<Location>,
10392        title: String,
10393        split: bool,
10394        cx: &mut ViewContext<Workspace>,
10395    ) {
10396        // If there are multiple definitions, open them in a multibuffer
10397        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10398        let mut locations = locations.into_iter().peekable();
10399        let mut ranges_to_highlight = Vec::new();
10400        let capability = workspace.project().read(cx).capability();
10401
10402        let excerpt_buffer = cx.new_model(|cx| {
10403            let mut multibuffer = MultiBuffer::new(capability);
10404            while let Some(location) = locations.next() {
10405                let buffer = location.buffer.read(cx);
10406                let mut ranges_for_buffer = Vec::new();
10407                let range = location.range.to_offset(buffer);
10408                ranges_for_buffer.push(range.clone());
10409
10410                while let Some(next_location) = locations.peek() {
10411                    if next_location.buffer == location.buffer {
10412                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10413                        locations.next();
10414                    } else {
10415                        break;
10416                    }
10417                }
10418
10419                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10420                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10421                    location.buffer.clone(),
10422                    ranges_for_buffer,
10423                    DEFAULT_MULTIBUFFER_CONTEXT,
10424                    cx,
10425                ))
10426            }
10427
10428            multibuffer.with_title(title)
10429        });
10430
10431        let editor = cx.new_view(|cx| {
10432            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10433        });
10434        editor.update(cx, |editor, cx| {
10435            if let Some(first_range) = ranges_to_highlight.first() {
10436                editor.change_selections(None, cx, |selections| {
10437                    selections.clear_disjoint();
10438                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10439                });
10440            }
10441            editor.highlight_background::<Self>(
10442                &ranges_to_highlight,
10443                |theme| theme.editor_highlighted_line_background,
10444                cx,
10445            );
10446        });
10447
10448        let item = Box::new(editor);
10449        let item_id = item.item_id();
10450
10451        if split {
10452            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10453        } else {
10454            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10455                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10456                    pane.close_current_preview_item(cx)
10457                } else {
10458                    None
10459                }
10460            });
10461            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10462        }
10463        workspace.active_pane().update(cx, |pane, cx| {
10464            pane.set_preview_item_id(Some(item_id), cx);
10465        });
10466    }
10467
10468    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10469        use language::ToOffset as _;
10470
10471        let provider = self.semantics_provider.clone()?;
10472        let selection = self.selections.newest_anchor().clone();
10473        let (cursor_buffer, cursor_buffer_position) = self
10474            .buffer
10475            .read(cx)
10476            .text_anchor_for_position(selection.head(), cx)?;
10477        let (tail_buffer, cursor_buffer_position_end) = self
10478            .buffer
10479            .read(cx)
10480            .text_anchor_for_position(selection.tail(), cx)?;
10481        if tail_buffer != cursor_buffer {
10482            return None;
10483        }
10484
10485        let snapshot = cursor_buffer.read(cx).snapshot();
10486        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10487        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10488        let prepare_rename = provider
10489            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10490            .unwrap_or_else(|| Task::ready(Ok(None)));
10491        drop(snapshot);
10492
10493        Some(cx.spawn(|this, mut cx| async move {
10494            let rename_range = if let Some(range) = prepare_rename.await? {
10495                Some(range)
10496            } else {
10497                this.update(&mut cx, |this, cx| {
10498                    let buffer = this.buffer.read(cx).snapshot(cx);
10499                    let mut buffer_highlights = this
10500                        .document_highlights_for_position(selection.head(), &buffer)
10501                        .filter(|highlight| {
10502                            highlight.start.excerpt_id == selection.head().excerpt_id
10503                                && highlight.end.excerpt_id == selection.head().excerpt_id
10504                        });
10505                    buffer_highlights
10506                        .next()
10507                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10508                })?
10509            };
10510            if let Some(rename_range) = rename_range {
10511                this.update(&mut cx, |this, cx| {
10512                    let snapshot = cursor_buffer.read(cx).snapshot();
10513                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10514                    let cursor_offset_in_rename_range =
10515                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10516                    let cursor_offset_in_rename_range_end =
10517                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10518
10519                    this.take_rename(false, cx);
10520                    let buffer = this.buffer.read(cx).read(cx);
10521                    let cursor_offset = selection.head().to_offset(&buffer);
10522                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10523                    let rename_end = rename_start + rename_buffer_range.len();
10524                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10525                    let mut old_highlight_id = None;
10526                    let old_name: Arc<str> = buffer
10527                        .chunks(rename_start..rename_end, true)
10528                        .map(|chunk| {
10529                            if old_highlight_id.is_none() {
10530                                old_highlight_id = chunk.syntax_highlight_id;
10531                            }
10532                            chunk.text
10533                        })
10534                        .collect::<String>()
10535                        .into();
10536
10537                    drop(buffer);
10538
10539                    // Position the selection in the rename editor so that it matches the current selection.
10540                    this.show_local_selections = false;
10541                    let rename_editor = cx.new_view(|cx| {
10542                        let mut editor = Editor::single_line(cx);
10543                        editor.buffer.update(cx, |buffer, cx| {
10544                            buffer.edit([(0..0, old_name.clone())], None, cx)
10545                        });
10546                        let rename_selection_range = match cursor_offset_in_rename_range
10547                            .cmp(&cursor_offset_in_rename_range_end)
10548                        {
10549                            Ordering::Equal => {
10550                                editor.select_all(&SelectAll, cx);
10551                                return editor;
10552                            }
10553                            Ordering::Less => {
10554                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10555                            }
10556                            Ordering::Greater => {
10557                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10558                            }
10559                        };
10560                        if rename_selection_range.end > old_name.len() {
10561                            editor.select_all(&SelectAll, cx);
10562                        } else {
10563                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10564                                s.select_ranges([rename_selection_range]);
10565                            });
10566                        }
10567                        editor
10568                    });
10569                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10570                        if e == &EditorEvent::Focused {
10571                            cx.emit(EditorEvent::FocusedIn)
10572                        }
10573                    })
10574                    .detach();
10575
10576                    let write_highlights =
10577                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10578                    let read_highlights =
10579                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10580                    let ranges = write_highlights
10581                        .iter()
10582                        .flat_map(|(_, ranges)| ranges.iter())
10583                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10584                        .cloned()
10585                        .collect();
10586
10587                    this.highlight_text::<Rename>(
10588                        ranges,
10589                        HighlightStyle {
10590                            fade_out: Some(0.6),
10591                            ..Default::default()
10592                        },
10593                        cx,
10594                    );
10595                    let rename_focus_handle = rename_editor.focus_handle(cx);
10596                    cx.focus(&rename_focus_handle);
10597                    let block_id = this.insert_blocks(
10598                        [BlockProperties {
10599                            style: BlockStyle::Flex,
10600                            placement: BlockPlacement::Below(range.start),
10601                            height: 1,
10602                            render: Arc::new({
10603                                let rename_editor = rename_editor.clone();
10604                                move |cx: &mut BlockContext| {
10605                                    let mut text_style = cx.editor_style.text.clone();
10606                                    if let Some(highlight_style) = old_highlight_id
10607                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10608                                    {
10609                                        text_style = text_style.highlight(highlight_style);
10610                                    }
10611                                    div()
10612                                        .block_mouse_down()
10613                                        .pl(cx.anchor_x)
10614                                        .child(EditorElement::new(
10615                                            &rename_editor,
10616                                            EditorStyle {
10617                                                background: cx.theme().system().transparent,
10618                                                local_player: cx.editor_style.local_player,
10619                                                text: text_style,
10620                                                scrollbar_width: cx.editor_style.scrollbar_width,
10621                                                syntax: cx.editor_style.syntax.clone(),
10622                                                status: cx.editor_style.status.clone(),
10623                                                inlay_hints_style: HighlightStyle {
10624                                                    font_weight: Some(FontWeight::BOLD),
10625                                                    ..make_inlay_hints_style(cx)
10626                                                },
10627                                                suggestions_style: HighlightStyle {
10628                                                    color: Some(cx.theme().status().predictive),
10629                                                    ..HighlightStyle::default()
10630                                                },
10631                                                ..EditorStyle::default()
10632                                            },
10633                                        ))
10634                                        .into_any_element()
10635                                }
10636                            }),
10637                            priority: 0,
10638                        }],
10639                        Some(Autoscroll::fit()),
10640                        cx,
10641                    )[0];
10642                    this.pending_rename = Some(RenameState {
10643                        range,
10644                        old_name,
10645                        editor: rename_editor,
10646                        block_id,
10647                    });
10648                })?;
10649            }
10650
10651            Ok(())
10652        }))
10653    }
10654
10655    pub fn confirm_rename(
10656        &mut self,
10657        _: &ConfirmRename,
10658        cx: &mut ViewContext<Self>,
10659    ) -> Option<Task<Result<()>>> {
10660        let rename = self.take_rename(false, cx)?;
10661        let workspace = self.workspace()?.downgrade();
10662        let (buffer, start) = self
10663            .buffer
10664            .read(cx)
10665            .text_anchor_for_position(rename.range.start, cx)?;
10666        let (end_buffer, _) = self
10667            .buffer
10668            .read(cx)
10669            .text_anchor_for_position(rename.range.end, cx)?;
10670        if buffer != end_buffer {
10671            return None;
10672        }
10673
10674        let old_name = rename.old_name;
10675        let new_name = rename.editor.read(cx).text(cx);
10676
10677        let rename = self.semantics_provider.as_ref()?.perform_rename(
10678            &buffer,
10679            start,
10680            new_name.clone(),
10681            cx,
10682        )?;
10683
10684        Some(cx.spawn(|editor, mut cx| async move {
10685            let project_transaction = rename.await?;
10686            Self::open_project_transaction(
10687                &editor,
10688                workspace,
10689                project_transaction,
10690                format!("Rename: {}{}", old_name, new_name),
10691                cx.clone(),
10692            )
10693            .await?;
10694
10695            editor.update(&mut cx, |editor, cx| {
10696                editor.refresh_document_highlights(cx);
10697            })?;
10698            Ok(())
10699        }))
10700    }
10701
10702    fn take_rename(
10703        &mut self,
10704        moving_cursor: bool,
10705        cx: &mut ViewContext<Self>,
10706    ) -> Option<RenameState> {
10707        let rename = self.pending_rename.take()?;
10708        if rename.editor.focus_handle(cx).is_focused(cx) {
10709            cx.focus(&self.focus_handle);
10710        }
10711
10712        self.remove_blocks(
10713            [rename.block_id].into_iter().collect(),
10714            Some(Autoscroll::fit()),
10715            cx,
10716        );
10717        self.clear_highlights::<Rename>(cx);
10718        self.show_local_selections = true;
10719
10720        if moving_cursor {
10721            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10722                editor.selections.newest::<usize>(cx).head()
10723            });
10724
10725            // Update the selection to match the position of the selection inside
10726            // the rename editor.
10727            let snapshot = self.buffer.read(cx).read(cx);
10728            let rename_range = rename.range.to_offset(&snapshot);
10729            let cursor_in_editor = snapshot
10730                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10731                .min(rename_range.end);
10732            drop(snapshot);
10733
10734            self.change_selections(None, cx, |s| {
10735                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10736            });
10737        } else {
10738            self.refresh_document_highlights(cx);
10739        }
10740
10741        Some(rename)
10742    }
10743
10744    pub fn pending_rename(&self) -> Option<&RenameState> {
10745        self.pending_rename.as_ref()
10746    }
10747
10748    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10749        let project = match &self.project {
10750            Some(project) => project.clone(),
10751            None => return None,
10752        };
10753
10754        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10755    }
10756
10757    fn format_selections(
10758        &mut self,
10759        _: &FormatSelections,
10760        cx: &mut ViewContext<Self>,
10761    ) -> Option<Task<Result<()>>> {
10762        let project = match &self.project {
10763            Some(project) => project.clone(),
10764            None => return None,
10765        };
10766
10767        let selections = self
10768            .selections
10769            .all_adjusted(cx)
10770            .into_iter()
10771            .filter(|s| !s.is_empty())
10772            .collect_vec();
10773
10774        Some(self.perform_format(
10775            project,
10776            FormatTrigger::Manual,
10777            FormatTarget::Ranges(selections),
10778            cx,
10779        ))
10780    }
10781
10782    fn perform_format(
10783        &mut self,
10784        project: Model<Project>,
10785        trigger: FormatTrigger,
10786        target: FormatTarget,
10787        cx: &mut ViewContext<Self>,
10788    ) -> Task<Result<()>> {
10789        let buffer = self.buffer().clone();
10790        let mut buffers = buffer.read(cx).all_buffers();
10791        if trigger == FormatTrigger::Save {
10792            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10793        }
10794
10795        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10796        let format = project.update(cx, |project, cx| {
10797            project.format(buffers, true, trigger, target, cx)
10798        });
10799
10800        cx.spawn(|_, mut cx| async move {
10801            let transaction = futures::select_biased! {
10802                () = timeout => {
10803                    log::warn!("timed out waiting for formatting");
10804                    None
10805                }
10806                transaction = format.log_err().fuse() => transaction,
10807            };
10808
10809            buffer
10810                .update(&mut cx, |buffer, cx| {
10811                    if let Some(transaction) = transaction {
10812                        if !buffer.is_singleton() {
10813                            buffer.push_transaction(&transaction.0, cx);
10814                        }
10815                    }
10816
10817                    cx.notify();
10818                })
10819                .ok();
10820
10821            Ok(())
10822        })
10823    }
10824
10825    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10826        if let Some(project) = self.project.clone() {
10827            self.buffer.update(cx, |multi_buffer, cx| {
10828                project.update(cx, |project, cx| {
10829                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10830                });
10831            })
10832        }
10833    }
10834
10835    fn cancel_language_server_work(
10836        &mut self,
10837        _: &actions::CancelLanguageServerWork,
10838        cx: &mut ViewContext<Self>,
10839    ) {
10840        if let Some(project) = self.project.clone() {
10841            self.buffer.update(cx, |multi_buffer, cx| {
10842                project.update(cx, |project, cx| {
10843                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10844                });
10845            })
10846        }
10847    }
10848
10849    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10850        cx.show_character_palette();
10851    }
10852
10853    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10854        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10855            let buffer = self.buffer.read(cx).snapshot(cx);
10856            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10857            let is_valid = buffer
10858                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10859                .any(|entry| {
10860                    entry.diagnostic.is_primary
10861                        && !entry.range.is_empty()
10862                        && entry.range.start == primary_range_start
10863                        && entry.diagnostic.message == active_diagnostics.primary_message
10864                });
10865
10866            if is_valid != active_diagnostics.is_valid {
10867                active_diagnostics.is_valid = is_valid;
10868                let mut new_styles = HashMap::default();
10869                for (block_id, diagnostic) in &active_diagnostics.blocks {
10870                    new_styles.insert(
10871                        *block_id,
10872                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10873                    );
10874                }
10875                self.display_map.update(cx, |display_map, _cx| {
10876                    display_map.replace_blocks(new_styles)
10877                });
10878            }
10879        }
10880    }
10881
10882    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10883        self.dismiss_diagnostics(cx);
10884        let snapshot = self.snapshot(cx);
10885        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10886            let buffer = self.buffer.read(cx).snapshot(cx);
10887
10888            let mut primary_range = None;
10889            let mut primary_message = None;
10890            let mut group_end = Point::zero();
10891            let diagnostic_group = buffer
10892                .diagnostic_group::<MultiBufferPoint>(group_id)
10893                .filter_map(|entry| {
10894                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10895                        && (entry.range.start.row == entry.range.end.row
10896                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10897                    {
10898                        return None;
10899                    }
10900                    if entry.range.end > group_end {
10901                        group_end = entry.range.end;
10902                    }
10903                    if entry.diagnostic.is_primary {
10904                        primary_range = Some(entry.range.clone());
10905                        primary_message = Some(entry.diagnostic.message.clone());
10906                    }
10907                    Some(entry)
10908                })
10909                .collect::<Vec<_>>();
10910            let primary_range = primary_range?;
10911            let primary_message = primary_message?;
10912            let primary_range =
10913                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10914
10915            let blocks = display_map
10916                .insert_blocks(
10917                    diagnostic_group.iter().map(|entry| {
10918                        let diagnostic = entry.diagnostic.clone();
10919                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10920                        BlockProperties {
10921                            style: BlockStyle::Fixed,
10922                            placement: BlockPlacement::Below(
10923                                buffer.anchor_after(entry.range.start),
10924                            ),
10925                            height: message_height,
10926                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10927                            priority: 0,
10928                        }
10929                    }),
10930                    cx,
10931                )
10932                .into_iter()
10933                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10934                .collect();
10935
10936            Some(ActiveDiagnosticGroup {
10937                primary_range,
10938                primary_message,
10939                group_id,
10940                blocks,
10941                is_valid: true,
10942            })
10943        });
10944        self.active_diagnostics.is_some()
10945    }
10946
10947    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10948        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10949            self.display_map.update(cx, |display_map, cx| {
10950                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10951            });
10952            cx.notify();
10953        }
10954    }
10955
10956    pub fn set_selections_from_remote(
10957        &mut self,
10958        selections: Vec<Selection<Anchor>>,
10959        pending_selection: Option<Selection<Anchor>>,
10960        cx: &mut ViewContext<Self>,
10961    ) {
10962        let old_cursor_position = self.selections.newest_anchor().head();
10963        self.selections.change_with(cx, |s| {
10964            s.select_anchors(selections);
10965            if let Some(pending_selection) = pending_selection {
10966                s.set_pending(pending_selection, SelectMode::Character);
10967            } else {
10968                s.clear_pending();
10969            }
10970        });
10971        self.selections_did_change(false, &old_cursor_position, true, cx);
10972    }
10973
10974    fn push_to_selection_history(&mut self) {
10975        self.selection_history.push(SelectionHistoryEntry {
10976            selections: self.selections.disjoint_anchors(),
10977            select_next_state: self.select_next_state.clone(),
10978            select_prev_state: self.select_prev_state.clone(),
10979            add_selections_state: self.add_selections_state.clone(),
10980        });
10981    }
10982
10983    pub fn transact(
10984        &mut self,
10985        cx: &mut ViewContext<Self>,
10986        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10987    ) -> Option<TransactionId> {
10988        self.start_transaction_at(Instant::now(), cx);
10989        update(self, cx);
10990        self.end_transaction_at(Instant::now(), cx)
10991    }
10992
10993    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10994        self.end_selection(cx);
10995        if let Some(tx_id) = self
10996            .buffer
10997            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10998        {
10999            self.selection_history
11000                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11001            cx.emit(EditorEvent::TransactionBegun {
11002                transaction_id: tx_id,
11003            })
11004        }
11005    }
11006
11007    fn end_transaction_at(
11008        &mut self,
11009        now: Instant,
11010        cx: &mut ViewContext<Self>,
11011    ) -> Option<TransactionId> {
11012        if let Some(transaction_id) = self
11013            .buffer
11014            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11015        {
11016            if let Some((_, end_selections)) =
11017                self.selection_history.transaction_mut(transaction_id)
11018            {
11019                *end_selections = Some(self.selections.disjoint_anchors());
11020            } else {
11021                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11022            }
11023
11024            cx.emit(EditorEvent::Edited { transaction_id });
11025            Some(transaction_id)
11026        } else {
11027            None
11028        }
11029    }
11030
11031    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
11032        let selection = self.selections.newest::<Point>(cx);
11033
11034        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11035        let range = if selection.is_empty() {
11036            let point = selection.head().to_display_point(&display_map);
11037            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11038            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11039                .to_point(&display_map);
11040            start..end
11041        } else {
11042            selection.range()
11043        };
11044        if display_map.folds_in_range(range).next().is_some() {
11045            self.unfold_lines(&Default::default(), cx)
11046        } else {
11047            self.fold(&Default::default(), cx)
11048        }
11049    }
11050
11051    pub fn toggle_fold_recursive(
11052        &mut self,
11053        _: &actions::ToggleFoldRecursive,
11054        cx: &mut ViewContext<Self>,
11055    ) {
11056        let selection = self.selections.newest::<Point>(cx);
11057
11058        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11059        let range = if selection.is_empty() {
11060            let point = selection.head().to_display_point(&display_map);
11061            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11062            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11063                .to_point(&display_map);
11064            start..end
11065        } else {
11066            selection.range()
11067        };
11068        if display_map.folds_in_range(range).next().is_some() {
11069            self.unfold_recursive(&Default::default(), cx)
11070        } else {
11071            self.fold_recursive(&Default::default(), cx)
11072        }
11073    }
11074
11075    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11076        let mut to_fold = Vec::new();
11077        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11078        let selections = self.selections.all_adjusted(cx);
11079
11080        for selection in selections {
11081            let range = selection.range().sorted();
11082            let buffer_start_row = range.start.row;
11083
11084            if range.start.row != range.end.row {
11085                let mut found = false;
11086                let mut row = range.start.row;
11087                while row <= range.end.row {
11088                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11089                        found = true;
11090                        row = crease.range().end.row + 1;
11091                        to_fold.push(crease);
11092                    } else {
11093                        row += 1
11094                    }
11095                }
11096                if found {
11097                    continue;
11098                }
11099            }
11100
11101            for row in (0..=range.start.row).rev() {
11102                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11103                    if crease.range().end.row >= buffer_start_row {
11104                        to_fold.push(crease);
11105                        if row <= range.start.row {
11106                            break;
11107                        }
11108                    }
11109                }
11110            }
11111        }
11112
11113        self.fold_creases(to_fold, true, cx);
11114    }
11115
11116    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11117        let fold_at_level = fold_at.level;
11118        let snapshot = self.buffer.read(cx).snapshot(cx);
11119        let mut to_fold = Vec::new();
11120        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11121
11122        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11123            while start_row < end_row {
11124                match self
11125                    .snapshot(cx)
11126                    .crease_for_buffer_row(MultiBufferRow(start_row))
11127                {
11128                    Some(crease) => {
11129                        let nested_start_row = crease.range().start.row + 1;
11130                        let nested_end_row = crease.range().end.row;
11131
11132                        if current_level < fold_at_level {
11133                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11134                        } else if current_level == fold_at_level {
11135                            to_fold.push(crease);
11136                        }
11137
11138                        start_row = nested_end_row + 1;
11139                    }
11140                    None => start_row += 1,
11141                }
11142            }
11143        }
11144
11145        self.fold_creases(to_fold, true, cx);
11146    }
11147
11148    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11149        let mut fold_ranges = Vec::new();
11150        let snapshot = self.buffer.read(cx).snapshot(cx);
11151
11152        for row in 0..snapshot.max_buffer_row().0 {
11153            if let Some(foldable_range) =
11154                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11155            {
11156                fold_ranges.push(foldable_range);
11157            }
11158        }
11159
11160        self.fold_creases(fold_ranges, true, cx);
11161    }
11162
11163    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11164        let mut to_fold = Vec::new();
11165        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11166        let selections = self.selections.all_adjusted(cx);
11167
11168        for selection in selections {
11169            let range = selection.range().sorted();
11170            let buffer_start_row = range.start.row;
11171
11172            if range.start.row != range.end.row {
11173                let mut found = false;
11174                for row in range.start.row..=range.end.row {
11175                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11176                        found = true;
11177                        to_fold.push(crease);
11178                    }
11179                }
11180                if found {
11181                    continue;
11182                }
11183            }
11184
11185            for row in (0..=range.start.row).rev() {
11186                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11187                    if crease.range().end.row >= buffer_start_row {
11188                        to_fold.push(crease);
11189                    } else {
11190                        break;
11191                    }
11192                }
11193            }
11194        }
11195
11196        self.fold_creases(to_fold, true, cx);
11197    }
11198
11199    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11200        let buffer_row = fold_at.buffer_row;
11201        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11202
11203        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11204            let autoscroll = self
11205                .selections
11206                .all::<Point>(cx)
11207                .iter()
11208                .any(|selection| crease.range().overlaps(&selection.range()));
11209
11210            self.fold_creases(vec![crease], autoscroll, cx);
11211        }
11212    }
11213
11214    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11215        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11216        let buffer = &display_map.buffer_snapshot;
11217        let selections = self.selections.all::<Point>(cx);
11218        let ranges = selections
11219            .iter()
11220            .map(|s| {
11221                let range = s.display_range(&display_map).sorted();
11222                let mut start = range.start.to_point(&display_map);
11223                let mut end = range.end.to_point(&display_map);
11224                start.column = 0;
11225                end.column = buffer.line_len(MultiBufferRow(end.row));
11226                start..end
11227            })
11228            .collect::<Vec<_>>();
11229
11230        self.unfold_ranges(&ranges, true, true, cx);
11231    }
11232
11233    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11234        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11235        let selections = self.selections.all::<Point>(cx);
11236        let ranges = selections
11237            .iter()
11238            .map(|s| {
11239                let mut range = s.display_range(&display_map).sorted();
11240                *range.start.column_mut() = 0;
11241                *range.end.column_mut() = display_map.line_len(range.end.row());
11242                let start = range.start.to_point(&display_map);
11243                let end = range.end.to_point(&display_map);
11244                start..end
11245            })
11246            .collect::<Vec<_>>();
11247
11248        self.unfold_ranges(&ranges, true, true, cx);
11249    }
11250
11251    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11252        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11253
11254        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11255            ..Point::new(
11256                unfold_at.buffer_row.0,
11257                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11258            );
11259
11260        let autoscroll = self
11261            .selections
11262            .all::<Point>(cx)
11263            .iter()
11264            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11265
11266        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11267    }
11268
11269    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11270        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11271        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11272    }
11273
11274    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11275        let selections = self.selections.all::<Point>(cx);
11276        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11277        let line_mode = self.selections.line_mode;
11278        let ranges = selections
11279            .into_iter()
11280            .map(|s| {
11281                if line_mode {
11282                    let start = Point::new(s.start.row, 0);
11283                    let end = Point::new(
11284                        s.end.row,
11285                        display_map
11286                            .buffer_snapshot
11287                            .line_len(MultiBufferRow(s.end.row)),
11288                    );
11289                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11290                } else {
11291                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11292                }
11293            })
11294            .collect::<Vec<_>>();
11295        self.fold_creases(ranges, true, cx);
11296    }
11297
11298    pub fn fold_creases<T: ToOffset + Clone>(
11299        &mut self,
11300        creases: Vec<Crease<T>>,
11301        auto_scroll: bool,
11302        cx: &mut ViewContext<Self>,
11303    ) {
11304        if creases.is_empty() {
11305            return;
11306        }
11307
11308        let mut buffers_affected = HashMap::default();
11309        let multi_buffer = self.buffer().read(cx);
11310        for crease in &creases {
11311            if let Some((_, buffer, _)) =
11312                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11313            {
11314                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11315            };
11316        }
11317
11318        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11319
11320        if auto_scroll {
11321            self.request_autoscroll(Autoscroll::fit(), cx);
11322        }
11323
11324        for buffer in buffers_affected.into_values() {
11325            self.sync_expanded_diff_hunks(buffer, cx);
11326        }
11327
11328        cx.notify();
11329
11330        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11331            // Clear diagnostics block when folding a range that contains it.
11332            let snapshot = self.snapshot(cx);
11333            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11334                drop(snapshot);
11335                self.active_diagnostics = Some(active_diagnostics);
11336                self.dismiss_diagnostics(cx);
11337            } else {
11338                self.active_diagnostics = Some(active_diagnostics);
11339            }
11340        }
11341
11342        self.scrollbar_marker_state.dirty = true;
11343    }
11344
11345    /// Removes any folds whose ranges intersect any of the given ranges.
11346    pub fn unfold_ranges<T: ToOffset + Clone>(
11347        &mut self,
11348        ranges: &[Range<T>],
11349        inclusive: bool,
11350        auto_scroll: bool,
11351        cx: &mut ViewContext<Self>,
11352    ) {
11353        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11354            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11355        });
11356    }
11357
11358    /// Removes any folds with the given ranges.
11359    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11360        &mut self,
11361        ranges: &[Range<T>],
11362        type_id: TypeId,
11363        auto_scroll: bool,
11364        cx: &mut ViewContext<Self>,
11365    ) {
11366        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11367            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11368        });
11369    }
11370
11371    fn remove_folds_with<T: ToOffset + Clone>(
11372        &mut self,
11373        ranges: &[Range<T>],
11374        auto_scroll: bool,
11375        cx: &mut ViewContext<Self>,
11376        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11377    ) {
11378        if ranges.is_empty() {
11379            return;
11380        }
11381
11382        let mut buffers_affected = HashMap::default();
11383        let multi_buffer = self.buffer().read(cx);
11384        for range in ranges {
11385            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11386                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11387            };
11388        }
11389
11390        self.display_map.update(cx, update);
11391
11392        if auto_scroll {
11393            self.request_autoscroll(Autoscroll::fit(), cx);
11394        }
11395
11396        for buffer in buffers_affected.into_values() {
11397            self.sync_expanded_diff_hunks(buffer, cx);
11398        }
11399
11400        cx.notify();
11401        self.scrollbar_marker_state.dirty = true;
11402        self.active_indent_guides_state.dirty = true;
11403    }
11404
11405    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11406        self.display_map.read(cx).fold_placeholder.clone()
11407    }
11408
11409    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11410        if hovered != self.gutter_hovered {
11411            self.gutter_hovered = hovered;
11412            cx.notify();
11413        }
11414    }
11415
11416    pub fn insert_blocks(
11417        &mut self,
11418        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11419        autoscroll: Option<Autoscroll>,
11420        cx: &mut ViewContext<Self>,
11421    ) -> Vec<CustomBlockId> {
11422        let blocks = self
11423            .display_map
11424            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11425        if let Some(autoscroll) = autoscroll {
11426            self.request_autoscroll(autoscroll, cx);
11427        }
11428        cx.notify();
11429        blocks
11430    }
11431
11432    pub fn resize_blocks(
11433        &mut self,
11434        heights: HashMap<CustomBlockId, u32>,
11435        autoscroll: Option<Autoscroll>,
11436        cx: &mut ViewContext<Self>,
11437    ) {
11438        self.display_map
11439            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11440        if let Some(autoscroll) = autoscroll {
11441            self.request_autoscroll(autoscroll, cx);
11442        }
11443        cx.notify();
11444    }
11445
11446    pub fn replace_blocks(
11447        &mut self,
11448        renderers: HashMap<CustomBlockId, RenderBlock>,
11449        autoscroll: Option<Autoscroll>,
11450        cx: &mut ViewContext<Self>,
11451    ) {
11452        self.display_map
11453            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11454        if let Some(autoscroll) = autoscroll {
11455            self.request_autoscroll(autoscroll, cx);
11456        }
11457        cx.notify();
11458    }
11459
11460    pub fn remove_blocks(
11461        &mut self,
11462        block_ids: HashSet<CustomBlockId>,
11463        autoscroll: Option<Autoscroll>,
11464        cx: &mut ViewContext<Self>,
11465    ) {
11466        self.display_map.update(cx, |display_map, cx| {
11467            display_map.remove_blocks(block_ids, cx)
11468        });
11469        if let Some(autoscroll) = autoscroll {
11470            self.request_autoscroll(autoscroll, cx);
11471        }
11472        cx.notify();
11473    }
11474
11475    pub fn row_for_block(
11476        &self,
11477        block_id: CustomBlockId,
11478        cx: &mut ViewContext<Self>,
11479    ) -> Option<DisplayRow> {
11480        self.display_map
11481            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11482    }
11483
11484    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11485        self.focused_block = Some(focused_block);
11486    }
11487
11488    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11489        self.focused_block.take()
11490    }
11491
11492    pub fn insert_creases(
11493        &mut self,
11494        creases: impl IntoIterator<Item = Crease<Anchor>>,
11495        cx: &mut ViewContext<Self>,
11496    ) -> Vec<CreaseId> {
11497        self.display_map
11498            .update(cx, |map, cx| map.insert_creases(creases, cx))
11499    }
11500
11501    pub fn remove_creases(
11502        &mut self,
11503        ids: impl IntoIterator<Item = CreaseId>,
11504        cx: &mut ViewContext<Self>,
11505    ) {
11506        self.display_map
11507            .update(cx, |map, cx| map.remove_creases(ids, cx));
11508    }
11509
11510    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11511        self.display_map
11512            .update(cx, |map, cx| map.snapshot(cx))
11513            .longest_row()
11514    }
11515
11516    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11517        self.display_map
11518            .update(cx, |map, cx| map.snapshot(cx))
11519            .max_point()
11520    }
11521
11522    pub fn text(&self, cx: &AppContext) -> String {
11523        self.buffer.read(cx).read(cx).text()
11524    }
11525
11526    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11527        let text = self.text(cx);
11528        let text = text.trim();
11529
11530        if text.is_empty() {
11531            return None;
11532        }
11533
11534        Some(text.to_string())
11535    }
11536
11537    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11538        self.transact(cx, |this, cx| {
11539            this.buffer
11540                .read(cx)
11541                .as_singleton()
11542                .expect("you can only call set_text on editors for singleton buffers")
11543                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11544        });
11545    }
11546
11547    pub fn display_text(&self, cx: &mut AppContext) -> String {
11548        self.display_map
11549            .update(cx, |map, cx| map.snapshot(cx))
11550            .text()
11551    }
11552
11553    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11554        let mut wrap_guides = smallvec::smallvec![];
11555
11556        if self.show_wrap_guides == Some(false) {
11557            return wrap_guides;
11558        }
11559
11560        let settings = self.buffer.read(cx).settings_at(0, cx);
11561        if settings.show_wrap_guides {
11562            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11563                wrap_guides.push((soft_wrap as usize, true));
11564            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11565                wrap_guides.push((soft_wrap as usize, true));
11566            }
11567            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11568        }
11569
11570        wrap_guides
11571    }
11572
11573    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11574        let settings = self.buffer.read(cx).settings_at(0, cx);
11575        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11576        match mode {
11577            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11578                SoftWrap::None
11579            }
11580            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11581            language_settings::SoftWrap::PreferredLineLength => {
11582                SoftWrap::Column(settings.preferred_line_length)
11583            }
11584            language_settings::SoftWrap::Bounded => {
11585                SoftWrap::Bounded(settings.preferred_line_length)
11586            }
11587        }
11588    }
11589
11590    pub fn set_soft_wrap_mode(
11591        &mut self,
11592        mode: language_settings::SoftWrap,
11593        cx: &mut ViewContext<Self>,
11594    ) {
11595        self.soft_wrap_mode_override = Some(mode);
11596        cx.notify();
11597    }
11598
11599    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11600        self.text_style_refinement = Some(style);
11601    }
11602
11603    /// called by the Element so we know what style we were most recently rendered with.
11604    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11605        let rem_size = cx.rem_size();
11606        self.display_map.update(cx, |map, cx| {
11607            map.set_font(
11608                style.text.font(),
11609                style.text.font_size.to_pixels(rem_size),
11610                cx,
11611            )
11612        });
11613        self.style = Some(style);
11614    }
11615
11616    pub fn style(&self) -> Option<&EditorStyle> {
11617        self.style.as_ref()
11618    }
11619
11620    // Called by the element. This method is not designed to be called outside of the editor
11621    // element's layout code because it does not notify when rewrapping is computed synchronously.
11622    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11623        self.display_map
11624            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11625    }
11626
11627    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11628        if self.soft_wrap_mode_override.is_some() {
11629            self.soft_wrap_mode_override.take();
11630        } else {
11631            let soft_wrap = match self.soft_wrap_mode(cx) {
11632                SoftWrap::GitDiff => return,
11633                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11634                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11635                    language_settings::SoftWrap::None
11636                }
11637            };
11638            self.soft_wrap_mode_override = Some(soft_wrap);
11639        }
11640        cx.notify();
11641    }
11642
11643    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11644        let Some(workspace) = self.workspace() else {
11645            return;
11646        };
11647        let fs = workspace.read(cx).app_state().fs.clone();
11648        let current_show = TabBarSettings::get_global(cx).show;
11649        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11650            setting.show = Some(!current_show);
11651        });
11652    }
11653
11654    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11655        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11656            self.buffer
11657                .read(cx)
11658                .settings_at(0, cx)
11659                .indent_guides
11660                .enabled
11661        });
11662        self.show_indent_guides = Some(!currently_enabled);
11663        cx.notify();
11664    }
11665
11666    fn should_show_indent_guides(&self) -> Option<bool> {
11667        self.show_indent_guides
11668    }
11669
11670    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11671        let mut editor_settings = EditorSettings::get_global(cx).clone();
11672        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11673        EditorSettings::override_global(editor_settings, cx);
11674    }
11675
11676    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11677        self.use_relative_line_numbers
11678            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11679    }
11680
11681    pub fn toggle_relative_line_numbers(
11682        &mut self,
11683        _: &ToggleRelativeLineNumbers,
11684        cx: &mut ViewContext<Self>,
11685    ) {
11686        let is_relative = self.should_use_relative_line_numbers(cx);
11687        self.set_relative_line_number(Some(!is_relative), cx)
11688    }
11689
11690    pub fn set_relative_line_number(
11691        &mut self,
11692        is_relative: Option<bool>,
11693        cx: &mut ViewContext<Self>,
11694    ) {
11695        self.use_relative_line_numbers = is_relative;
11696        cx.notify();
11697    }
11698
11699    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11700        self.show_gutter = show_gutter;
11701        cx.notify();
11702    }
11703
11704    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11705        self.show_line_numbers = Some(show_line_numbers);
11706        cx.notify();
11707    }
11708
11709    pub fn set_show_git_diff_gutter(
11710        &mut self,
11711        show_git_diff_gutter: bool,
11712        cx: &mut ViewContext<Self>,
11713    ) {
11714        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11715        cx.notify();
11716    }
11717
11718    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11719        self.show_code_actions = Some(show_code_actions);
11720        cx.notify();
11721    }
11722
11723    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11724        self.show_runnables = Some(show_runnables);
11725        cx.notify();
11726    }
11727
11728    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11729        if self.display_map.read(cx).masked != masked {
11730            self.display_map.update(cx, |map, _| map.masked = masked);
11731        }
11732        cx.notify()
11733    }
11734
11735    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11736        self.show_wrap_guides = Some(show_wrap_guides);
11737        cx.notify();
11738    }
11739
11740    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11741        self.show_indent_guides = Some(show_indent_guides);
11742        cx.notify();
11743    }
11744
11745    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11746        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11747            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11748                if let Some(dir) = file.abs_path(cx).parent() {
11749                    return Some(dir.to_owned());
11750                }
11751            }
11752
11753            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11754                return Some(project_path.path.to_path_buf());
11755            }
11756        }
11757
11758        None
11759    }
11760
11761    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11762        self.active_excerpt(cx)?
11763            .1
11764            .read(cx)
11765            .file()
11766            .and_then(|f| f.as_local())
11767    }
11768
11769    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11770        if let Some(target) = self.target_file(cx) {
11771            cx.reveal_path(&target.abs_path(cx));
11772        }
11773    }
11774
11775    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11776        if let Some(file) = self.target_file(cx) {
11777            if let Some(path) = file.abs_path(cx).to_str() {
11778                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11779            }
11780        }
11781    }
11782
11783    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11784        if let Some(file) = self.target_file(cx) {
11785            if let Some(path) = file.path().to_str() {
11786                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11787            }
11788        }
11789    }
11790
11791    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11792        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11793
11794        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11795            self.start_git_blame(true, cx);
11796        }
11797
11798        cx.notify();
11799    }
11800
11801    pub fn toggle_git_blame_inline(
11802        &mut self,
11803        _: &ToggleGitBlameInline,
11804        cx: &mut ViewContext<Self>,
11805    ) {
11806        self.toggle_git_blame_inline_internal(true, cx);
11807        cx.notify();
11808    }
11809
11810    pub fn git_blame_inline_enabled(&self) -> bool {
11811        self.git_blame_inline_enabled
11812    }
11813
11814    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11815        self.show_selection_menu = self
11816            .show_selection_menu
11817            .map(|show_selections_menu| !show_selections_menu)
11818            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11819
11820        cx.notify();
11821    }
11822
11823    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11824        self.show_selection_menu
11825            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11826    }
11827
11828    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11829        if let Some(project) = self.project.as_ref() {
11830            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11831                return;
11832            };
11833
11834            if buffer.read(cx).file().is_none() {
11835                return;
11836            }
11837
11838            let focused = self.focus_handle(cx).contains_focused(cx);
11839
11840            let project = project.clone();
11841            let blame =
11842                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11843            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11844            self.blame = Some(blame);
11845        }
11846    }
11847
11848    fn toggle_git_blame_inline_internal(
11849        &mut self,
11850        user_triggered: bool,
11851        cx: &mut ViewContext<Self>,
11852    ) {
11853        if self.git_blame_inline_enabled {
11854            self.git_blame_inline_enabled = false;
11855            self.show_git_blame_inline = false;
11856            self.show_git_blame_inline_delay_task.take();
11857        } else {
11858            self.git_blame_inline_enabled = true;
11859            self.start_git_blame_inline(user_triggered, cx);
11860        }
11861
11862        cx.notify();
11863    }
11864
11865    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11866        self.start_git_blame(user_triggered, cx);
11867
11868        if ProjectSettings::get_global(cx)
11869            .git
11870            .inline_blame_delay()
11871            .is_some()
11872        {
11873            self.start_inline_blame_timer(cx);
11874        } else {
11875            self.show_git_blame_inline = true
11876        }
11877    }
11878
11879    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11880        self.blame.as_ref()
11881    }
11882
11883    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11884        self.show_git_blame_gutter && self.has_blame_entries(cx)
11885    }
11886
11887    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11888        self.show_git_blame_inline
11889            && self.focus_handle.is_focused(cx)
11890            && !self.newest_selection_head_on_empty_line(cx)
11891            && self.has_blame_entries(cx)
11892    }
11893
11894    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11895        self.blame()
11896            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11897    }
11898
11899    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11900        let cursor_anchor = self.selections.newest_anchor().head();
11901
11902        let snapshot = self.buffer.read(cx).snapshot(cx);
11903        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11904
11905        snapshot.line_len(buffer_row) == 0
11906    }
11907
11908    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11909        let buffer_and_selection = maybe!({
11910            let selection = self.selections.newest::<Point>(cx);
11911            let selection_range = selection.range();
11912
11913            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11914                (buffer, selection_range.start.row..selection_range.end.row)
11915            } else {
11916                let buffer_ranges = self
11917                    .buffer()
11918                    .read(cx)
11919                    .range_to_buffer_ranges(selection_range, cx);
11920
11921                let (buffer, range, _) = if selection.reversed {
11922                    buffer_ranges.first()
11923                } else {
11924                    buffer_ranges.last()
11925                }?;
11926
11927                let snapshot = buffer.read(cx).snapshot();
11928                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11929                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11930                (buffer.clone(), selection)
11931            };
11932
11933            Some((buffer, selection))
11934        });
11935
11936        let Some((buffer, selection)) = buffer_and_selection else {
11937            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11938        };
11939
11940        let Some(project) = self.project.as_ref() else {
11941            return Task::ready(Err(anyhow!("editor does not have project")));
11942        };
11943
11944        project.update(cx, |project, cx| {
11945            project.get_permalink_to_line(&buffer, selection, cx)
11946        })
11947    }
11948
11949    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11950        let permalink_task = self.get_permalink_to_line(cx);
11951        let workspace = self.workspace();
11952
11953        cx.spawn(|_, mut cx| async move {
11954            match permalink_task.await {
11955                Ok(permalink) => {
11956                    cx.update(|cx| {
11957                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11958                    })
11959                    .ok();
11960                }
11961                Err(err) => {
11962                    let message = format!("Failed to copy permalink: {err}");
11963
11964                    Err::<(), anyhow::Error>(err).log_err();
11965
11966                    if let Some(workspace) = workspace {
11967                        workspace
11968                            .update(&mut cx, |workspace, cx| {
11969                                struct CopyPermalinkToLine;
11970
11971                                workspace.show_toast(
11972                                    Toast::new(
11973                                        NotificationId::unique::<CopyPermalinkToLine>(),
11974                                        message,
11975                                    ),
11976                                    cx,
11977                                )
11978                            })
11979                            .ok();
11980                    }
11981                }
11982            }
11983        })
11984        .detach();
11985    }
11986
11987    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11988        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11989        if let Some(file) = self.target_file(cx) {
11990            if let Some(path) = file.path().to_str() {
11991                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11992            }
11993        }
11994    }
11995
11996    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11997        let permalink_task = self.get_permalink_to_line(cx);
11998        let workspace = self.workspace();
11999
12000        cx.spawn(|_, mut cx| async move {
12001            match permalink_task.await {
12002                Ok(permalink) => {
12003                    cx.update(|cx| {
12004                        cx.open_url(permalink.as_ref());
12005                    })
12006                    .ok();
12007                }
12008                Err(err) => {
12009                    let message = format!("Failed to open permalink: {err}");
12010
12011                    Err::<(), anyhow::Error>(err).log_err();
12012
12013                    if let Some(workspace) = workspace {
12014                        workspace
12015                            .update(&mut cx, |workspace, cx| {
12016                                struct OpenPermalinkToLine;
12017
12018                                workspace.show_toast(
12019                                    Toast::new(
12020                                        NotificationId::unique::<OpenPermalinkToLine>(),
12021                                        message,
12022                                    ),
12023                                    cx,
12024                                )
12025                            })
12026                            .ok();
12027                    }
12028                }
12029            }
12030        })
12031        .detach();
12032    }
12033
12034    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12035    /// last highlight added will be used.
12036    ///
12037    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12038    pub fn highlight_rows<T: 'static>(
12039        &mut self,
12040        range: Range<Anchor>,
12041        color: Hsla,
12042        should_autoscroll: bool,
12043        cx: &mut ViewContext<Self>,
12044    ) {
12045        let snapshot = self.buffer().read(cx).snapshot(cx);
12046        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12047        let ix = row_highlights.binary_search_by(|highlight| {
12048            Ordering::Equal
12049                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12050                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12051        });
12052
12053        if let Err(mut ix) = ix {
12054            let index = post_inc(&mut self.highlight_order);
12055
12056            // If this range intersects with the preceding highlight, then merge it with
12057            // the preceding highlight. Otherwise insert a new highlight.
12058            let mut merged = false;
12059            if ix > 0 {
12060                let prev_highlight = &mut row_highlights[ix - 1];
12061                if prev_highlight
12062                    .range
12063                    .end
12064                    .cmp(&range.start, &snapshot)
12065                    .is_ge()
12066                {
12067                    ix -= 1;
12068                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12069                        prev_highlight.range.end = range.end;
12070                    }
12071                    merged = true;
12072                    prev_highlight.index = index;
12073                    prev_highlight.color = color;
12074                    prev_highlight.should_autoscroll = should_autoscroll;
12075                }
12076            }
12077
12078            if !merged {
12079                row_highlights.insert(
12080                    ix,
12081                    RowHighlight {
12082                        range: range.clone(),
12083                        index,
12084                        color,
12085                        should_autoscroll,
12086                    },
12087                );
12088            }
12089
12090            // If any of the following highlights intersect with this one, merge them.
12091            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12092                let highlight = &row_highlights[ix];
12093                if next_highlight
12094                    .range
12095                    .start
12096                    .cmp(&highlight.range.end, &snapshot)
12097                    .is_le()
12098                {
12099                    if next_highlight
12100                        .range
12101                        .end
12102                        .cmp(&highlight.range.end, &snapshot)
12103                        .is_gt()
12104                    {
12105                        row_highlights[ix].range.end = next_highlight.range.end;
12106                    }
12107                    row_highlights.remove(ix + 1);
12108                } else {
12109                    break;
12110                }
12111            }
12112        }
12113    }
12114
12115    /// Remove any highlighted row ranges of the given type that intersect the
12116    /// given ranges.
12117    pub fn remove_highlighted_rows<T: 'static>(
12118        &mut self,
12119        ranges_to_remove: Vec<Range<Anchor>>,
12120        cx: &mut ViewContext<Self>,
12121    ) {
12122        let snapshot = self.buffer().read(cx).snapshot(cx);
12123        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12124        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12125        row_highlights.retain(|highlight| {
12126            while let Some(range_to_remove) = ranges_to_remove.peek() {
12127                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12128                    Ordering::Less | Ordering::Equal => {
12129                        ranges_to_remove.next();
12130                    }
12131                    Ordering::Greater => {
12132                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12133                            Ordering::Less | Ordering::Equal => {
12134                                return false;
12135                            }
12136                            Ordering::Greater => break,
12137                        }
12138                    }
12139                }
12140            }
12141
12142            true
12143        })
12144    }
12145
12146    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12147    pub fn clear_row_highlights<T: 'static>(&mut self) {
12148        self.highlighted_rows.remove(&TypeId::of::<T>());
12149    }
12150
12151    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12152    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12153        self.highlighted_rows
12154            .get(&TypeId::of::<T>())
12155            .map_or(&[] as &[_], |vec| vec.as_slice())
12156            .iter()
12157            .map(|highlight| (highlight.range.clone(), highlight.color))
12158    }
12159
12160    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12161    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12162    /// Allows to ignore certain kinds of highlights.
12163    pub fn highlighted_display_rows(
12164        &mut self,
12165        cx: &mut WindowContext,
12166    ) -> BTreeMap<DisplayRow, Hsla> {
12167        let snapshot = self.snapshot(cx);
12168        let mut used_highlight_orders = HashMap::default();
12169        self.highlighted_rows
12170            .iter()
12171            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12172            .fold(
12173                BTreeMap::<DisplayRow, Hsla>::new(),
12174                |mut unique_rows, highlight| {
12175                    let start = highlight.range.start.to_display_point(&snapshot);
12176                    let end = highlight.range.end.to_display_point(&snapshot);
12177                    let start_row = start.row().0;
12178                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12179                        && end.column() == 0
12180                    {
12181                        end.row().0.saturating_sub(1)
12182                    } else {
12183                        end.row().0
12184                    };
12185                    for row in start_row..=end_row {
12186                        let used_index =
12187                            used_highlight_orders.entry(row).or_insert(highlight.index);
12188                        if highlight.index >= *used_index {
12189                            *used_index = highlight.index;
12190                            unique_rows.insert(DisplayRow(row), highlight.color);
12191                        }
12192                    }
12193                    unique_rows
12194                },
12195            )
12196    }
12197
12198    pub fn highlighted_display_row_for_autoscroll(
12199        &self,
12200        snapshot: &DisplaySnapshot,
12201    ) -> Option<DisplayRow> {
12202        self.highlighted_rows
12203            .values()
12204            .flat_map(|highlighted_rows| highlighted_rows.iter())
12205            .filter_map(|highlight| {
12206                if highlight.should_autoscroll {
12207                    Some(highlight.range.start.to_display_point(snapshot).row())
12208                } else {
12209                    None
12210                }
12211            })
12212            .min()
12213    }
12214
12215    pub fn set_search_within_ranges(
12216        &mut self,
12217        ranges: &[Range<Anchor>],
12218        cx: &mut ViewContext<Self>,
12219    ) {
12220        self.highlight_background::<SearchWithinRange>(
12221            ranges,
12222            |colors| colors.editor_document_highlight_read_background,
12223            cx,
12224        )
12225    }
12226
12227    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12228        self.breadcrumb_header = Some(new_header);
12229    }
12230
12231    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12232        self.clear_background_highlights::<SearchWithinRange>(cx);
12233    }
12234
12235    pub fn highlight_background<T: 'static>(
12236        &mut self,
12237        ranges: &[Range<Anchor>],
12238        color_fetcher: fn(&ThemeColors) -> Hsla,
12239        cx: &mut ViewContext<Self>,
12240    ) {
12241        self.background_highlights
12242            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12243        self.scrollbar_marker_state.dirty = true;
12244        cx.notify();
12245    }
12246
12247    pub fn clear_background_highlights<T: 'static>(
12248        &mut self,
12249        cx: &mut ViewContext<Self>,
12250    ) -> Option<BackgroundHighlight> {
12251        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12252        if !text_highlights.1.is_empty() {
12253            self.scrollbar_marker_state.dirty = true;
12254            cx.notify();
12255        }
12256        Some(text_highlights)
12257    }
12258
12259    pub fn highlight_gutter<T: 'static>(
12260        &mut self,
12261        ranges: &[Range<Anchor>],
12262        color_fetcher: fn(&AppContext) -> Hsla,
12263        cx: &mut ViewContext<Self>,
12264    ) {
12265        self.gutter_highlights
12266            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12267        cx.notify();
12268    }
12269
12270    pub fn clear_gutter_highlights<T: 'static>(
12271        &mut self,
12272        cx: &mut ViewContext<Self>,
12273    ) -> Option<GutterHighlight> {
12274        cx.notify();
12275        self.gutter_highlights.remove(&TypeId::of::<T>())
12276    }
12277
12278    #[cfg(feature = "test-support")]
12279    pub fn all_text_background_highlights(
12280        &mut self,
12281        cx: &mut ViewContext<Self>,
12282    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12283        let snapshot = self.snapshot(cx);
12284        let buffer = &snapshot.buffer_snapshot;
12285        let start = buffer.anchor_before(0);
12286        let end = buffer.anchor_after(buffer.len());
12287        let theme = cx.theme().colors();
12288        self.background_highlights_in_range(start..end, &snapshot, theme)
12289    }
12290
12291    #[cfg(feature = "test-support")]
12292    pub fn search_background_highlights(
12293        &mut self,
12294        cx: &mut ViewContext<Self>,
12295    ) -> Vec<Range<Point>> {
12296        let snapshot = self.buffer().read(cx).snapshot(cx);
12297
12298        let highlights = self
12299            .background_highlights
12300            .get(&TypeId::of::<items::BufferSearchHighlights>());
12301
12302        if let Some((_color, ranges)) = highlights {
12303            ranges
12304                .iter()
12305                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12306                .collect_vec()
12307        } else {
12308            vec![]
12309        }
12310    }
12311
12312    fn document_highlights_for_position<'a>(
12313        &'a self,
12314        position: Anchor,
12315        buffer: &'a MultiBufferSnapshot,
12316    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12317        let read_highlights = self
12318            .background_highlights
12319            .get(&TypeId::of::<DocumentHighlightRead>())
12320            .map(|h| &h.1);
12321        let write_highlights = self
12322            .background_highlights
12323            .get(&TypeId::of::<DocumentHighlightWrite>())
12324            .map(|h| &h.1);
12325        let left_position = position.bias_left(buffer);
12326        let right_position = position.bias_right(buffer);
12327        read_highlights
12328            .into_iter()
12329            .chain(write_highlights)
12330            .flat_map(move |ranges| {
12331                let start_ix = match ranges.binary_search_by(|probe| {
12332                    let cmp = probe.end.cmp(&left_position, buffer);
12333                    if cmp.is_ge() {
12334                        Ordering::Greater
12335                    } else {
12336                        Ordering::Less
12337                    }
12338                }) {
12339                    Ok(i) | Err(i) => i,
12340                };
12341
12342                ranges[start_ix..]
12343                    .iter()
12344                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12345            })
12346    }
12347
12348    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12349        self.background_highlights
12350            .get(&TypeId::of::<T>())
12351            .map_or(false, |(_, highlights)| !highlights.is_empty())
12352    }
12353
12354    pub fn background_highlights_in_range(
12355        &self,
12356        search_range: Range<Anchor>,
12357        display_snapshot: &DisplaySnapshot,
12358        theme: &ThemeColors,
12359    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12360        let mut results = Vec::new();
12361        for (color_fetcher, ranges) in self.background_highlights.values() {
12362            let color = color_fetcher(theme);
12363            let start_ix = match ranges.binary_search_by(|probe| {
12364                let cmp = probe
12365                    .end
12366                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12367                if cmp.is_gt() {
12368                    Ordering::Greater
12369                } else {
12370                    Ordering::Less
12371                }
12372            }) {
12373                Ok(i) | Err(i) => i,
12374            };
12375            for range in &ranges[start_ix..] {
12376                if range
12377                    .start
12378                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12379                    .is_ge()
12380                {
12381                    break;
12382                }
12383
12384                let start = range.start.to_display_point(display_snapshot);
12385                let end = range.end.to_display_point(display_snapshot);
12386                results.push((start..end, color))
12387            }
12388        }
12389        results
12390    }
12391
12392    pub fn background_highlight_row_ranges<T: 'static>(
12393        &self,
12394        search_range: Range<Anchor>,
12395        display_snapshot: &DisplaySnapshot,
12396        count: usize,
12397    ) -> Vec<RangeInclusive<DisplayPoint>> {
12398        let mut results = Vec::new();
12399        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12400            return vec![];
12401        };
12402
12403        let start_ix = match ranges.binary_search_by(|probe| {
12404            let cmp = probe
12405                .end
12406                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12407            if cmp.is_gt() {
12408                Ordering::Greater
12409            } else {
12410                Ordering::Less
12411            }
12412        }) {
12413            Ok(i) | Err(i) => i,
12414        };
12415        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12416            if let (Some(start_display), Some(end_display)) = (start, end) {
12417                results.push(
12418                    start_display.to_display_point(display_snapshot)
12419                        ..=end_display.to_display_point(display_snapshot),
12420                );
12421            }
12422        };
12423        let mut start_row: Option<Point> = None;
12424        let mut end_row: Option<Point> = None;
12425        if ranges.len() > count {
12426            return Vec::new();
12427        }
12428        for range in &ranges[start_ix..] {
12429            if range
12430                .start
12431                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12432                .is_ge()
12433            {
12434                break;
12435            }
12436            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12437            if let Some(current_row) = &end_row {
12438                if end.row == current_row.row {
12439                    continue;
12440                }
12441            }
12442            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12443            if start_row.is_none() {
12444                assert_eq!(end_row, None);
12445                start_row = Some(start);
12446                end_row = Some(end);
12447                continue;
12448            }
12449            if let Some(current_end) = end_row.as_mut() {
12450                if start.row > current_end.row + 1 {
12451                    push_region(start_row, end_row);
12452                    start_row = Some(start);
12453                    end_row = Some(end);
12454                } else {
12455                    // Merge two hunks.
12456                    *current_end = end;
12457                }
12458            } else {
12459                unreachable!();
12460            }
12461        }
12462        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12463        push_region(start_row, end_row);
12464        results
12465    }
12466
12467    pub fn gutter_highlights_in_range(
12468        &self,
12469        search_range: Range<Anchor>,
12470        display_snapshot: &DisplaySnapshot,
12471        cx: &AppContext,
12472    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12473        let mut results = Vec::new();
12474        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12475            let color = color_fetcher(cx);
12476            let start_ix = match ranges.binary_search_by(|probe| {
12477                let cmp = probe
12478                    .end
12479                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12480                if cmp.is_gt() {
12481                    Ordering::Greater
12482                } else {
12483                    Ordering::Less
12484                }
12485            }) {
12486                Ok(i) | Err(i) => i,
12487            };
12488            for range in &ranges[start_ix..] {
12489                if range
12490                    .start
12491                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12492                    .is_ge()
12493                {
12494                    break;
12495                }
12496
12497                let start = range.start.to_display_point(display_snapshot);
12498                let end = range.end.to_display_point(display_snapshot);
12499                results.push((start..end, color))
12500            }
12501        }
12502        results
12503    }
12504
12505    /// Get the text ranges corresponding to the redaction query
12506    pub fn redacted_ranges(
12507        &self,
12508        search_range: Range<Anchor>,
12509        display_snapshot: &DisplaySnapshot,
12510        cx: &WindowContext,
12511    ) -> Vec<Range<DisplayPoint>> {
12512        display_snapshot
12513            .buffer_snapshot
12514            .redacted_ranges(search_range, |file| {
12515                if let Some(file) = file {
12516                    file.is_private()
12517                        && EditorSettings::get(
12518                            Some(SettingsLocation {
12519                                worktree_id: file.worktree_id(cx),
12520                                path: file.path().as_ref(),
12521                            }),
12522                            cx,
12523                        )
12524                        .redact_private_values
12525                } else {
12526                    false
12527                }
12528            })
12529            .map(|range| {
12530                range.start.to_display_point(display_snapshot)
12531                    ..range.end.to_display_point(display_snapshot)
12532            })
12533            .collect()
12534    }
12535
12536    pub fn highlight_text<T: 'static>(
12537        &mut self,
12538        ranges: Vec<Range<Anchor>>,
12539        style: HighlightStyle,
12540        cx: &mut ViewContext<Self>,
12541    ) {
12542        self.display_map.update(cx, |map, _| {
12543            map.highlight_text(TypeId::of::<T>(), ranges, style)
12544        });
12545        cx.notify();
12546    }
12547
12548    pub(crate) fn highlight_inlays<T: 'static>(
12549        &mut self,
12550        highlights: Vec<InlayHighlight>,
12551        style: HighlightStyle,
12552        cx: &mut ViewContext<Self>,
12553    ) {
12554        self.display_map.update(cx, |map, _| {
12555            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12556        });
12557        cx.notify();
12558    }
12559
12560    pub fn text_highlights<'a, T: 'static>(
12561        &'a self,
12562        cx: &'a AppContext,
12563    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12564        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12565    }
12566
12567    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12568        let cleared = self
12569            .display_map
12570            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12571        if cleared {
12572            cx.notify();
12573        }
12574    }
12575
12576    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12577        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12578            && self.focus_handle.is_focused(cx)
12579    }
12580
12581    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12582        self.show_cursor_when_unfocused = is_enabled;
12583        cx.notify();
12584    }
12585
12586    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12587        cx.notify();
12588    }
12589
12590    fn on_buffer_event(
12591        &mut self,
12592        multibuffer: Model<MultiBuffer>,
12593        event: &multi_buffer::Event,
12594        cx: &mut ViewContext<Self>,
12595    ) {
12596        match event {
12597            multi_buffer::Event::Edited {
12598                singleton_buffer_edited,
12599            } => {
12600                self.scrollbar_marker_state.dirty = true;
12601                self.active_indent_guides_state.dirty = true;
12602                self.refresh_active_diagnostics(cx);
12603                self.refresh_code_actions(cx);
12604                if self.has_active_inline_completion(cx) {
12605                    self.update_visible_inline_completion(cx);
12606                }
12607                cx.emit(EditorEvent::BufferEdited);
12608                cx.emit(SearchEvent::MatchesInvalidated);
12609                if *singleton_buffer_edited {
12610                    if let Some(project) = &self.project {
12611                        let project = project.read(cx);
12612                        #[allow(clippy::mutable_key_type)]
12613                        let languages_affected = multibuffer
12614                            .read(cx)
12615                            .all_buffers()
12616                            .into_iter()
12617                            .filter_map(|buffer| {
12618                                let buffer = buffer.read(cx);
12619                                let language = buffer.language()?;
12620                                if project.is_local()
12621                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12622                                {
12623                                    None
12624                                } else {
12625                                    Some(language)
12626                                }
12627                            })
12628                            .cloned()
12629                            .collect::<HashSet<_>>();
12630                        if !languages_affected.is_empty() {
12631                            self.refresh_inlay_hints(
12632                                InlayHintRefreshReason::BufferEdited(languages_affected),
12633                                cx,
12634                            );
12635                        }
12636                    }
12637                }
12638
12639                let Some(project) = &self.project else { return };
12640                let (telemetry, is_via_ssh) = {
12641                    let project = project.read(cx);
12642                    let telemetry = project.client().telemetry().clone();
12643                    let is_via_ssh = project.is_via_ssh();
12644                    (telemetry, is_via_ssh)
12645                };
12646                refresh_linked_ranges(self, cx);
12647                telemetry.log_edit_event("editor", is_via_ssh);
12648            }
12649            multi_buffer::Event::ExcerptsAdded {
12650                buffer,
12651                predecessor,
12652                excerpts,
12653            } => {
12654                self.tasks_update_task = Some(self.refresh_runnables(cx));
12655                cx.emit(EditorEvent::ExcerptsAdded {
12656                    buffer: buffer.clone(),
12657                    predecessor: *predecessor,
12658                    excerpts: excerpts.clone(),
12659                });
12660                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12661            }
12662            multi_buffer::Event::ExcerptsRemoved { ids } => {
12663                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12664                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12665            }
12666            multi_buffer::Event::ExcerptsEdited { ids } => {
12667                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12668            }
12669            multi_buffer::Event::ExcerptsExpanded { ids } => {
12670                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12671            }
12672            multi_buffer::Event::Reparsed(buffer_id) => {
12673                self.tasks_update_task = Some(self.refresh_runnables(cx));
12674
12675                cx.emit(EditorEvent::Reparsed(*buffer_id));
12676            }
12677            multi_buffer::Event::LanguageChanged(buffer_id) => {
12678                linked_editing_ranges::refresh_linked_ranges(self, cx);
12679                cx.emit(EditorEvent::Reparsed(*buffer_id));
12680                cx.notify();
12681            }
12682            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12683            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12684            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12685                cx.emit(EditorEvent::TitleChanged)
12686            }
12687            multi_buffer::Event::DiffBaseChanged => {
12688                self.scrollbar_marker_state.dirty = true;
12689                cx.emit(EditorEvent::DiffBaseChanged);
12690                cx.notify();
12691            }
12692            multi_buffer::Event::DiffUpdated { buffer } => {
12693                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12694                cx.notify();
12695            }
12696            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12697            multi_buffer::Event::DiagnosticsUpdated => {
12698                self.refresh_active_diagnostics(cx);
12699                self.scrollbar_marker_state.dirty = true;
12700                cx.notify();
12701            }
12702            _ => {}
12703        };
12704    }
12705
12706    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12707        cx.notify();
12708    }
12709
12710    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12711        self.tasks_update_task = Some(self.refresh_runnables(cx));
12712        self.refresh_inline_completion(true, false, cx);
12713        self.refresh_inlay_hints(
12714            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12715                self.selections.newest_anchor().head(),
12716                &self.buffer.read(cx).snapshot(cx),
12717                cx,
12718            )),
12719            cx,
12720        );
12721
12722        let old_cursor_shape = self.cursor_shape;
12723
12724        {
12725            let editor_settings = EditorSettings::get_global(cx);
12726            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12727            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12728            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12729        }
12730
12731        if old_cursor_shape != self.cursor_shape {
12732            cx.emit(EditorEvent::CursorShapeChanged);
12733        }
12734
12735        let project_settings = ProjectSettings::get_global(cx);
12736        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12737
12738        if self.mode == EditorMode::Full {
12739            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12740            if self.git_blame_inline_enabled != inline_blame_enabled {
12741                self.toggle_git_blame_inline_internal(false, cx);
12742            }
12743        }
12744
12745        cx.notify();
12746    }
12747
12748    pub fn set_searchable(&mut self, searchable: bool) {
12749        self.searchable = searchable;
12750    }
12751
12752    pub fn searchable(&self) -> bool {
12753        self.searchable
12754    }
12755
12756    fn open_proposed_changes_editor(
12757        &mut self,
12758        _: &OpenProposedChangesEditor,
12759        cx: &mut ViewContext<Self>,
12760    ) {
12761        let Some(workspace) = self.workspace() else {
12762            cx.propagate();
12763            return;
12764        };
12765
12766        let selections = self.selections.all::<usize>(cx);
12767        let buffer = self.buffer.read(cx);
12768        let mut new_selections_by_buffer = HashMap::default();
12769        for selection in selections {
12770            for (buffer, range, _) in
12771                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12772            {
12773                let mut range = range.to_point(buffer.read(cx));
12774                range.start.column = 0;
12775                range.end.column = buffer.read(cx).line_len(range.end.row);
12776                new_selections_by_buffer
12777                    .entry(buffer)
12778                    .or_insert(Vec::new())
12779                    .push(range)
12780            }
12781        }
12782
12783        let proposed_changes_buffers = new_selections_by_buffer
12784            .into_iter()
12785            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12786            .collect::<Vec<_>>();
12787        let proposed_changes_editor = cx.new_view(|cx| {
12788            ProposedChangesEditor::new(
12789                "Proposed changes",
12790                proposed_changes_buffers,
12791                self.project.clone(),
12792                cx,
12793            )
12794        });
12795
12796        cx.window_context().defer(move |cx| {
12797            workspace.update(cx, |workspace, cx| {
12798                workspace.active_pane().update(cx, |pane, cx| {
12799                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12800                });
12801            });
12802        });
12803    }
12804
12805    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12806        self.open_excerpts_common(None, true, cx)
12807    }
12808
12809    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12810        self.open_excerpts_common(None, false, cx)
12811    }
12812
12813    fn open_excerpts_common(
12814        &mut self,
12815        jump_data: Option<JumpData>,
12816        split: bool,
12817        cx: &mut ViewContext<Self>,
12818    ) {
12819        let Some(workspace) = self.workspace() else {
12820            cx.propagate();
12821            return;
12822        };
12823
12824        if self.buffer.read(cx).is_singleton() {
12825            cx.propagate();
12826            return;
12827        }
12828
12829        let mut new_selections_by_buffer = HashMap::default();
12830        match &jump_data {
12831            Some(jump_data) => {
12832                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12833                if let Some(buffer) = multi_buffer_snapshot
12834                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12835                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12836                {
12837                    let buffer_snapshot = buffer.read(cx).snapshot();
12838                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12839                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12840                    } else {
12841                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12842                    };
12843                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12844                    new_selections_by_buffer.insert(
12845                        buffer,
12846                        (
12847                            vec![jump_to_offset..jump_to_offset],
12848                            Some(jump_data.line_offset_from_top),
12849                        ),
12850                    );
12851                }
12852            }
12853            None => {
12854                let selections = self.selections.all::<usize>(cx);
12855                let buffer = self.buffer.read(cx);
12856                for selection in selections {
12857                    for (mut buffer_handle, mut range, _) in
12858                        buffer.range_to_buffer_ranges(selection.range(), cx)
12859                    {
12860                        // When editing branch buffers, jump to the corresponding location
12861                        // in their base buffer.
12862                        let buffer = buffer_handle.read(cx);
12863                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12864                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12865                            buffer_handle = base_buffer;
12866                        }
12867
12868                        if selection.reversed {
12869                            mem::swap(&mut range.start, &mut range.end);
12870                        }
12871                        new_selections_by_buffer
12872                            .entry(buffer_handle)
12873                            .or_insert((Vec::new(), None))
12874                            .0
12875                            .push(range)
12876                    }
12877                }
12878            }
12879        }
12880
12881        if new_selections_by_buffer.is_empty() {
12882            return;
12883        }
12884
12885        // We defer the pane interaction because we ourselves are a workspace item
12886        // and activating a new item causes the pane to call a method on us reentrantly,
12887        // which panics if we're on the stack.
12888        cx.window_context().defer(move |cx| {
12889            workspace.update(cx, |workspace, cx| {
12890                let pane = if split {
12891                    workspace.adjacent_pane(cx)
12892                } else {
12893                    workspace.active_pane().clone()
12894                };
12895
12896                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12897                    let editor = buffer
12898                        .read(cx)
12899                        .file()
12900                        .is_none()
12901                        .then(|| {
12902                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12903                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12904                            // Instead, we try to activate the existing editor in the pane first.
12905                            let (editor, pane_item_index) =
12906                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12907                                    let editor = item.downcast::<Editor>()?;
12908                                    let singleton_buffer =
12909                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12910                                    if singleton_buffer == buffer {
12911                                        Some((editor, i))
12912                                    } else {
12913                                        None
12914                                    }
12915                                })?;
12916                            pane.update(cx, |pane, cx| {
12917                                pane.activate_item(pane_item_index, true, true, cx)
12918                            });
12919                            Some(editor)
12920                        })
12921                        .flatten()
12922                        .unwrap_or_else(|| {
12923                            workspace.open_project_item::<Self>(
12924                                pane.clone(),
12925                                buffer,
12926                                true,
12927                                true,
12928                                cx,
12929                            )
12930                        });
12931
12932                    editor.update(cx, |editor, cx| {
12933                        let autoscroll = match scroll_offset {
12934                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12935                            None => Autoscroll::newest(),
12936                        };
12937                        let nav_history = editor.nav_history.take();
12938                        editor.change_selections(Some(autoscroll), cx, |s| {
12939                            s.select_ranges(ranges);
12940                        });
12941                        editor.nav_history = nav_history;
12942                    });
12943                }
12944            })
12945        });
12946    }
12947
12948    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12949        let snapshot = self.buffer.read(cx).read(cx);
12950        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12951        Some(
12952            ranges
12953                .iter()
12954                .map(move |range| {
12955                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12956                })
12957                .collect(),
12958        )
12959    }
12960
12961    fn selection_replacement_ranges(
12962        &self,
12963        range: Range<OffsetUtf16>,
12964        cx: &mut AppContext,
12965    ) -> Vec<Range<OffsetUtf16>> {
12966        let selections = self.selections.all::<OffsetUtf16>(cx);
12967        let newest_selection = selections
12968            .iter()
12969            .max_by_key(|selection| selection.id)
12970            .unwrap();
12971        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12972        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12973        let snapshot = self.buffer.read(cx).read(cx);
12974        selections
12975            .into_iter()
12976            .map(|mut selection| {
12977                selection.start.0 =
12978                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12979                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12980                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12981                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12982            })
12983            .collect()
12984    }
12985
12986    fn report_editor_event(
12987        &self,
12988        operation: &'static str,
12989        file_extension: Option<String>,
12990        cx: &AppContext,
12991    ) {
12992        if cfg!(any(test, feature = "test-support")) {
12993            return;
12994        }
12995
12996        let Some(project) = &self.project else { return };
12997
12998        // If None, we are in a file without an extension
12999        let file = self
13000            .buffer
13001            .read(cx)
13002            .as_singleton()
13003            .and_then(|b| b.read(cx).file());
13004        let file_extension = file_extension.or(file
13005            .as_ref()
13006            .and_then(|file| Path::new(file.file_name(cx)).extension())
13007            .and_then(|e| e.to_str())
13008            .map(|a| a.to_string()));
13009
13010        let vim_mode = cx
13011            .global::<SettingsStore>()
13012            .raw_user_settings()
13013            .get("vim_mode")
13014            == Some(&serde_json::Value::Bool(true));
13015
13016        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13017            == language::language_settings::InlineCompletionProvider::Copilot;
13018        let copilot_enabled_for_language = self
13019            .buffer
13020            .read(cx)
13021            .settings_at(0, cx)
13022            .show_inline_completions;
13023
13024        let project = project.read(cx);
13025        let telemetry = project.client().telemetry().clone();
13026        telemetry.report_editor_event(
13027            file_extension,
13028            vim_mode,
13029            operation,
13030            copilot_enabled,
13031            copilot_enabled_for_language,
13032            project.is_via_ssh(),
13033        )
13034    }
13035
13036    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13037    /// with each line being an array of {text, highlight} objects.
13038    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13039        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13040            return;
13041        };
13042
13043        #[derive(Serialize)]
13044        struct Chunk<'a> {
13045            text: String,
13046            highlight: Option<&'a str>,
13047        }
13048
13049        let snapshot = buffer.read(cx).snapshot();
13050        let range = self
13051            .selected_text_range(false, cx)
13052            .and_then(|selection| {
13053                if selection.range.is_empty() {
13054                    None
13055                } else {
13056                    Some(selection.range)
13057                }
13058            })
13059            .unwrap_or_else(|| 0..snapshot.len());
13060
13061        let chunks = snapshot.chunks(range, true);
13062        let mut lines = Vec::new();
13063        let mut line: VecDeque<Chunk> = VecDeque::new();
13064
13065        let Some(style) = self.style.as_ref() else {
13066            return;
13067        };
13068
13069        for chunk in chunks {
13070            let highlight = chunk
13071                .syntax_highlight_id
13072                .and_then(|id| id.name(&style.syntax));
13073            let mut chunk_lines = chunk.text.split('\n').peekable();
13074            while let Some(text) = chunk_lines.next() {
13075                let mut merged_with_last_token = false;
13076                if let Some(last_token) = line.back_mut() {
13077                    if last_token.highlight == highlight {
13078                        last_token.text.push_str(text);
13079                        merged_with_last_token = true;
13080                    }
13081                }
13082
13083                if !merged_with_last_token {
13084                    line.push_back(Chunk {
13085                        text: text.into(),
13086                        highlight,
13087                    });
13088                }
13089
13090                if chunk_lines.peek().is_some() {
13091                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13092                        line.pop_front();
13093                    }
13094                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13095                        line.pop_back();
13096                    }
13097
13098                    lines.push(mem::take(&mut line));
13099                }
13100            }
13101        }
13102
13103        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13104            return;
13105        };
13106        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13107    }
13108
13109    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13110        &self.inlay_hint_cache
13111    }
13112
13113    pub fn replay_insert_event(
13114        &mut self,
13115        text: &str,
13116        relative_utf16_range: Option<Range<isize>>,
13117        cx: &mut ViewContext<Self>,
13118    ) {
13119        if !self.input_enabled {
13120            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13121            return;
13122        }
13123        if let Some(relative_utf16_range) = relative_utf16_range {
13124            let selections = self.selections.all::<OffsetUtf16>(cx);
13125            self.change_selections(None, cx, |s| {
13126                let new_ranges = selections.into_iter().map(|range| {
13127                    let start = OffsetUtf16(
13128                        range
13129                            .head()
13130                            .0
13131                            .saturating_add_signed(relative_utf16_range.start),
13132                    );
13133                    let end = OffsetUtf16(
13134                        range
13135                            .head()
13136                            .0
13137                            .saturating_add_signed(relative_utf16_range.end),
13138                    );
13139                    start..end
13140                });
13141                s.select_ranges(new_ranges);
13142            });
13143        }
13144
13145        self.handle_input(text, cx);
13146    }
13147
13148    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13149        let Some(provider) = self.semantics_provider.as_ref() else {
13150            return false;
13151        };
13152
13153        let mut supports = false;
13154        self.buffer().read(cx).for_each_buffer(|buffer| {
13155            supports |= provider.supports_inlay_hints(buffer, cx);
13156        });
13157        supports
13158    }
13159
13160    pub fn focus(&self, cx: &mut WindowContext) {
13161        cx.focus(&self.focus_handle)
13162    }
13163
13164    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13165        self.focus_handle.is_focused(cx)
13166    }
13167
13168    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13169        cx.emit(EditorEvent::Focused);
13170
13171        if let Some(descendant) = self
13172            .last_focused_descendant
13173            .take()
13174            .and_then(|descendant| descendant.upgrade())
13175        {
13176            cx.focus(&descendant);
13177        } else {
13178            if let Some(blame) = self.blame.as_ref() {
13179                blame.update(cx, GitBlame::focus)
13180            }
13181
13182            self.blink_manager.update(cx, BlinkManager::enable);
13183            self.show_cursor_names(cx);
13184            self.buffer.update(cx, |buffer, cx| {
13185                buffer.finalize_last_transaction(cx);
13186                if self.leader_peer_id.is_none() {
13187                    buffer.set_active_selections(
13188                        &self.selections.disjoint_anchors(),
13189                        self.selections.line_mode,
13190                        self.cursor_shape,
13191                        cx,
13192                    );
13193                }
13194            });
13195        }
13196    }
13197
13198    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13199        cx.emit(EditorEvent::FocusedIn)
13200    }
13201
13202    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13203        if event.blurred != self.focus_handle {
13204            self.last_focused_descendant = Some(event.blurred);
13205        }
13206    }
13207
13208    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13209        self.blink_manager.update(cx, BlinkManager::disable);
13210        self.buffer
13211            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13212
13213        if let Some(blame) = self.blame.as_ref() {
13214            blame.update(cx, GitBlame::blur)
13215        }
13216        if !self.hover_state.focused(cx) {
13217            hide_hover(self, cx);
13218        }
13219
13220        self.hide_context_menu(cx);
13221        cx.emit(EditorEvent::Blurred);
13222        cx.notify();
13223    }
13224
13225    pub fn register_action<A: Action>(
13226        &mut self,
13227        listener: impl Fn(&A, &mut WindowContext) + 'static,
13228    ) -> Subscription {
13229        let id = self.next_editor_action_id.post_inc();
13230        let listener = Arc::new(listener);
13231        self.editor_actions.borrow_mut().insert(
13232            id,
13233            Box::new(move |cx| {
13234                let cx = cx.window_context();
13235                let listener = listener.clone();
13236                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13237                    let action = action.downcast_ref().unwrap();
13238                    if phase == DispatchPhase::Bubble {
13239                        listener(action, cx)
13240                    }
13241                })
13242            }),
13243        );
13244
13245        let editor_actions = self.editor_actions.clone();
13246        Subscription::new(move || {
13247            editor_actions.borrow_mut().remove(&id);
13248        })
13249    }
13250
13251    pub fn file_header_size(&self) -> u32 {
13252        FILE_HEADER_HEIGHT
13253    }
13254
13255    pub fn revert(
13256        &mut self,
13257        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13258        cx: &mut ViewContext<Self>,
13259    ) {
13260        self.buffer().update(cx, |multi_buffer, cx| {
13261            for (buffer_id, changes) in revert_changes {
13262                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13263                    buffer.update(cx, |buffer, cx| {
13264                        buffer.edit(
13265                            changes.into_iter().map(|(range, text)| {
13266                                (range, text.to_string().map(Arc::<str>::from))
13267                            }),
13268                            None,
13269                            cx,
13270                        );
13271                    });
13272                }
13273            }
13274        });
13275        self.change_selections(None, cx, |selections| selections.refresh());
13276    }
13277
13278    pub fn to_pixel_point(
13279        &mut self,
13280        source: multi_buffer::Anchor,
13281        editor_snapshot: &EditorSnapshot,
13282        cx: &mut ViewContext<Self>,
13283    ) -> Option<gpui::Point<Pixels>> {
13284        let source_point = source.to_display_point(editor_snapshot);
13285        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13286    }
13287
13288    pub fn display_to_pixel_point(
13289        &mut self,
13290        source: DisplayPoint,
13291        editor_snapshot: &EditorSnapshot,
13292        cx: &mut ViewContext<Self>,
13293    ) -> Option<gpui::Point<Pixels>> {
13294        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13295        let text_layout_details = self.text_layout_details(cx);
13296        let scroll_top = text_layout_details
13297            .scroll_anchor
13298            .scroll_position(editor_snapshot)
13299            .y;
13300
13301        if source.row().as_f32() < scroll_top.floor() {
13302            return None;
13303        }
13304        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13305        let source_y = line_height * (source.row().as_f32() - scroll_top);
13306        Some(gpui::Point::new(source_x, source_y))
13307    }
13308
13309    pub fn has_active_completions_menu(&self) -> bool {
13310        self.context_menu.read().as_ref().map_or(false, |menu| {
13311            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13312        })
13313    }
13314
13315    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13316        self.addons
13317            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13318    }
13319
13320    pub fn unregister_addon<T: Addon>(&mut self) {
13321        self.addons.remove(&std::any::TypeId::of::<T>());
13322    }
13323
13324    pub fn addon<T: Addon>(&self) -> Option<&T> {
13325        let type_id = std::any::TypeId::of::<T>();
13326        self.addons
13327            .get(&type_id)
13328            .and_then(|item| item.to_any().downcast_ref::<T>())
13329    }
13330}
13331
13332fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13333    let tab_size = tab_size.get() as usize;
13334    let mut width = offset;
13335
13336    for ch in text.chars() {
13337        width += if ch == '\t' {
13338            tab_size - (width % tab_size)
13339        } else {
13340            1
13341        };
13342    }
13343
13344    width - offset
13345}
13346
13347#[cfg(test)]
13348mod tests {
13349    use super::*;
13350
13351    #[test]
13352    fn test_string_size_with_expanded_tabs() {
13353        let nz = |val| NonZeroU32::new(val).unwrap();
13354        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13355        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13356        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13357        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13358        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13359        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13360        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13361        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13362    }
13363}
13364
13365/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13366struct WordBreakingTokenizer<'a> {
13367    input: &'a str,
13368}
13369
13370impl<'a> WordBreakingTokenizer<'a> {
13371    fn new(input: &'a str) -> Self {
13372        Self { input }
13373    }
13374}
13375
13376fn is_char_ideographic(ch: char) -> bool {
13377    use unicode_script::Script::*;
13378    use unicode_script::UnicodeScript;
13379    matches!(ch.script(), Han | Tangut | Yi)
13380}
13381
13382fn is_grapheme_ideographic(text: &str) -> bool {
13383    text.chars().any(is_char_ideographic)
13384}
13385
13386fn is_grapheme_whitespace(text: &str) -> bool {
13387    text.chars().any(|x| x.is_whitespace())
13388}
13389
13390fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13391    text.chars().next().map_or(false, |ch| {
13392        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13393    })
13394}
13395
13396#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13397struct WordBreakToken<'a> {
13398    token: &'a str,
13399    grapheme_len: usize,
13400    is_whitespace: bool,
13401}
13402
13403impl<'a> Iterator for WordBreakingTokenizer<'a> {
13404    /// Yields a span, the count of graphemes in the token, and whether it was
13405    /// whitespace. Note that it also breaks at word boundaries.
13406    type Item = WordBreakToken<'a>;
13407
13408    fn next(&mut self) -> Option<Self::Item> {
13409        use unicode_segmentation::UnicodeSegmentation;
13410        if self.input.is_empty() {
13411            return None;
13412        }
13413
13414        let mut iter = self.input.graphemes(true).peekable();
13415        let mut offset = 0;
13416        let mut graphemes = 0;
13417        if let Some(first_grapheme) = iter.next() {
13418            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13419            offset += first_grapheme.len();
13420            graphemes += 1;
13421            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13422                if let Some(grapheme) = iter.peek().copied() {
13423                    if should_stay_with_preceding_ideograph(grapheme) {
13424                        offset += grapheme.len();
13425                        graphemes += 1;
13426                    }
13427                }
13428            } else {
13429                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13430                let mut next_word_bound = words.peek().copied();
13431                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13432                    next_word_bound = words.next();
13433                }
13434                while let Some(grapheme) = iter.peek().copied() {
13435                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13436                        break;
13437                    };
13438                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13439                        break;
13440                    };
13441                    offset += grapheme.len();
13442                    graphemes += 1;
13443                    iter.next();
13444                }
13445            }
13446            let token = &self.input[..offset];
13447            self.input = &self.input[offset..];
13448            if is_whitespace {
13449                Some(WordBreakToken {
13450                    token: " ",
13451                    grapheme_len: 1,
13452                    is_whitespace: true,
13453                })
13454            } else {
13455                Some(WordBreakToken {
13456                    token,
13457                    grapheme_len: graphemes,
13458                    is_whitespace: false,
13459                })
13460            }
13461        } else {
13462            None
13463        }
13464    }
13465}
13466
13467#[test]
13468fn test_word_breaking_tokenizer() {
13469    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13470        ("", &[]),
13471        ("  ", &[(" ", 1, true)]),
13472        ("Ʒ", &[("Ʒ", 1, false)]),
13473        ("Ǽ", &[("Ǽ", 1, false)]),
13474        ("", &[("", 1, false)]),
13475        ("⋑⋑", &[("⋑⋑", 2, false)]),
13476        (
13477            "原理,进而",
13478            &[
13479                ("", 1, false),
13480                ("理,", 2, false),
13481                ("", 1, false),
13482                ("", 1, false),
13483            ],
13484        ),
13485        (
13486            "hello world",
13487            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13488        ),
13489        (
13490            "hello, world",
13491            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13492        ),
13493        (
13494            "  hello world",
13495            &[
13496                (" ", 1, true),
13497                ("hello", 5, false),
13498                (" ", 1, true),
13499                ("world", 5, false),
13500            ],
13501        ),
13502        (
13503            "这是什么 \n 钢笔",
13504            &[
13505                ("", 1, false),
13506                ("", 1, false),
13507                ("", 1, false),
13508                ("", 1, false),
13509                (" ", 1, true),
13510                ("", 1, false),
13511                ("", 1, false),
13512            ],
13513        ),
13514        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13515    ];
13516
13517    for (input, result) in tests {
13518        assert_eq!(
13519            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13520            result
13521                .iter()
13522                .copied()
13523                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13524                    token,
13525                    grapheme_len,
13526                    is_whitespace,
13527                })
13528                .collect::<Vec<_>>()
13529        );
13530    }
13531}
13532
13533fn wrap_with_prefix(
13534    line_prefix: String,
13535    unwrapped_text: String,
13536    wrap_column: usize,
13537    tab_size: NonZeroU32,
13538) -> String {
13539    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13540    let mut wrapped_text = String::new();
13541    let mut current_line = line_prefix.clone();
13542
13543    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13544    let mut current_line_len = line_prefix_len;
13545    for WordBreakToken {
13546        token,
13547        grapheme_len,
13548        is_whitespace,
13549    } in tokenizer
13550    {
13551        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13552            wrapped_text.push_str(current_line.trim_end());
13553            wrapped_text.push('\n');
13554            current_line.truncate(line_prefix.len());
13555            current_line_len = line_prefix_len;
13556            if !is_whitespace {
13557                current_line.push_str(token);
13558                current_line_len += grapheme_len;
13559            }
13560        } else if !is_whitespace {
13561            current_line.push_str(token);
13562            current_line_len += grapheme_len;
13563        } else if current_line_len != line_prefix_len {
13564            current_line.push(' ');
13565            current_line_len += 1;
13566        }
13567    }
13568
13569    if !current_line.is_empty() {
13570        wrapped_text.push_str(&current_line);
13571    }
13572    wrapped_text
13573}
13574
13575#[test]
13576fn test_wrap_with_prefix() {
13577    assert_eq!(
13578        wrap_with_prefix(
13579            "# ".to_string(),
13580            "abcdefg".to_string(),
13581            4,
13582            NonZeroU32::new(4).unwrap()
13583        ),
13584        "# abcdefg"
13585    );
13586    assert_eq!(
13587        wrap_with_prefix(
13588            "".to_string(),
13589            "\thello world".to_string(),
13590            8,
13591            NonZeroU32::new(4).unwrap()
13592        ),
13593        "hello\nworld"
13594    );
13595    assert_eq!(
13596        wrap_with_prefix(
13597            "// ".to_string(),
13598            "xx \nyy zz aa bb cc".to_string(),
13599            12,
13600            NonZeroU32::new(4).unwrap()
13601        ),
13602        "// xx yy zz\n// aa bb cc"
13603    );
13604    assert_eq!(
13605        wrap_with_prefix(
13606            String::new(),
13607            "这是什么 \n 钢笔".to_string(),
13608            3,
13609            NonZeroU32::new(4).unwrap()
13610        ),
13611        "这是什\n么 钢\n"
13612    );
13613}
13614
13615fn hunks_for_selections(
13616    multi_buffer_snapshot: &MultiBufferSnapshot,
13617    selections: &[Selection<Anchor>],
13618) -> Vec<MultiBufferDiffHunk> {
13619    let buffer_rows_for_selections = selections.iter().map(|selection| {
13620        let head = selection.head();
13621        let tail = selection.tail();
13622        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13623        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13624        if start > end {
13625            end..start
13626        } else {
13627            start..end
13628        }
13629    });
13630
13631    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13632}
13633
13634pub fn hunks_for_rows(
13635    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13636    multi_buffer_snapshot: &MultiBufferSnapshot,
13637) -> Vec<MultiBufferDiffHunk> {
13638    let mut hunks = Vec::new();
13639    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13640        HashMap::default();
13641    for selected_multi_buffer_rows in rows {
13642        let query_rows =
13643            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13644        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13645            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13646            // when the caret is just above or just below the deleted hunk.
13647            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13648            let related_to_selection = if allow_adjacent {
13649                hunk.row_range.overlaps(&query_rows)
13650                    || hunk.row_range.start == query_rows.end
13651                    || hunk.row_range.end == query_rows.start
13652            } else {
13653                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13654                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13655                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13656                    || selected_multi_buffer_rows.end == hunk.row_range.start
13657            };
13658            if related_to_selection {
13659                if !processed_buffer_rows
13660                    .entry(hunk.buffer_id)
13661                    .or_default()
13662                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13663                {
13664                    continue;
13665                }
13666                hunks.push(hunk);
13667            }
13668        }
13669    }
13670
13671    hunks
13672}
13673
13674pub trait CollaborationHub {
13675    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13676    fn user_participant_indices<'a>(
13677        &self,
13678        cx: &'a AppContext,
13679    ) -> &'a HashMap<u64, ParticipantIndex>;
13680    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13681}
13682
13683impl CollaborationHub for Model<Project> {
13684    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13685        self.read(cx).collaborators()
13686    }
13687
13688    fn user_participant_indices<'a>(
13689        &self,
13690        cx: &'a AppContext,
13691    ) -> &'a HashMap<u64, ParticipantIndex> {
13692        self.read(cx).user_store().read(cx).participant_indices()
13693    }
13694
13695    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13696        let this = self.read(cx);
13697        let user_ids = this.collaborators().values().map(|c| c.user_id);
13698        this.user_store().read_with(cx, |user_store, cx| {
13699            user_store.participant_names(user_ids, cx)
13700        })
13701    }
13702}
13703
13704pub trait SemanticsProvider {
13705    fn hover(
13706        &self,
13707        buffer: &Model<Buffer>,
13708        position: text::Anchor,
13709        cx: &mut AppContext,
13710    ) -> Option<Task<Vec<project::Hover>>>;
13711
13712    fn inlay_hints(
13713        &self,
13714        buffer_handle: Model<Buffer>,
13715        range: Range<text::Anchor>,
13716        cx: &mut AppContext,
13717    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13718
13719    fn resolve_inlay_hint(
13720        &self,
13721        hint: InlayHint,
13722        buffer_handle: Model<Buffer>,
13723        server_id: LanguageServerId,
13724        cx: &mut AppContext,
13725    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13726
13727    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13728
13729    fn document_highlights(
13730        &self,
13731        buffer: &Model<Buffer>,
13732        position: text::Anchor,
13733        cx: &mut AppContext,
13734    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13735
13736    fn definitions(
13737        &self,
13738        buffer: &Model<Buffer>,
13739        position: text::Anchor,
13740        kind: GotoDefinitionKind,
13741        cx: &mut AppContext,
13742    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13743
13744    fn range_for_rename(
13745        &self,
13746        buffer: &Model<Buffer>,
13747        position: text::Anchor,
13748        cx: &mut AppContext,
13749    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13750
13751    fn perform_rename(
13752        &self,
13753        buffer: &Model<Buffer>,
13754        position: text::Anchor,
13755        new_name: String,
13756        cx: &mut AppContext,
13757    ) -> Option<Task<Result<ProjectTransaction>>>;
13758}
13759
13760pub trait CompletionProvider {
13761    fn completions(
13762        &self,
13763        buffer: &Model<Buffer>,
13764        buffer_position: text::Anchor,
13765        trigger: CompletionContext,
13766        cx: &mut ViewContext<Editor>,
13767    ) -> Task<Result<Vec<Completion>>>;
13768
13769    fn resolve_completions(
13770        &self,
13771        buffer: Model<Buffer>,
13772        completion_indices: Vec<usize>,
13773        completions: Arc<RwLock<Box<[Completion]>>>,
13774        cx: &mut ViewContext<Editor>,
13775    ) -> Task<Result<bool>>;
13776
13777    fn apply_additional_edits_for_completion(
13778        &self,
13779        buffer: Model<Buffer>,
13780        completion: Completion,
13781        push_to_history: bool,
13782        cx: &mut ViewContext<Editor>,
13783    ) -> Task<Result<Option<language::Transaction>>>;
13784
13785    fn is_completion_trigger(
13786        &self,
13787        buffer: &Model<Buffer>,
13788        position: language::Anchor,
13789        text: &str,
13790        trigger_in_words: bool,
13791        cx: &mut ViewContext<Editor>,
13792    ) -> bool;
13793
13794    fn sort_completions(&self) -> bool {
13795        true
13796    }
13797}
13798
13799pub trait CodeActionProvider {
13800    fn code_actions(
13801        &self,
13802        buffer: &Model<Buffer>,
13803        range: Range<text::Anchor>,
13804        cx: &mut WindowContext,
13805    ) -> Task<Result<Vec<CodeAction>>>;
13806
13807    fn apply_code_action(
13808        &self,
13809        buffer_handle: Model<Buffer>,
13810        action: CodeAction,
13811        excerpt_id: ExcerptId,
13812        push_to_history: bool,
13813        cx: &mut WindowContext,
13814    ) -> Task<Result<ProjectTransaction>>;
13815}
13816
13817impl CodeActionProvider for Model<Project> {
13818    fn code_actions(
13819        &self,
13820        buffer: &Model<Buffer>,
13821        range: Range<text::Anchor>,
13822        cx: &mut WindowContext,
13823    ) -> Task<Result<Vec<CodeAction>>> {
13824        self.update(cx, |project, cx| {
13825            project.code_actions(buffer, range, None, cx)
13826        })
13827    }
13828
13829    fn apply_code_action(
13830        &self,
13831        buffer_handle: Model<Buffer>,
13832        action: CodeAction,
13833        _excerpt_id: ExcerptId,
13834        push_to_history: bool,
13835        cx: &mut WindowContext,
13836    ) -> Task<Result<ProjectTransaction>> {
13837        self.update(cx, |project, cx| {
13838            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13839        })
13840    }
13841}
13842
13843fn snippet_completions(
13844    project: &Project,
13845    buffer: &Model<Buffer>,
13846    buffer_position: text::Anchor,
13847    cx: &mut AppContext,
13848) -> Vec<Completion> {
13849    let language = buffer.read(cx).language_at(buffer_position);
13850    let language_name = language.as_ref().map(|language| language.lsp_id());
13851    let snippet_store = project.snippets().read(cx);
13852    let snippets = snippet_store.snippets_for(language_name, cx);
13853
13854    if snippets.is_empty() {
13855        return vec![];
13856    }
13857    let snapshot = buffer.read(cx).text_snapshot();
13858    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13859
13860    let scope = language.map(|language| language.default_scope());
13861    let classifier = CharClassifier::new(scope).for_completion(true);
13862    let mut last_word = chars
13863        .take_while(|c| classifier.is_word(*c))
13864        .collect::<String>();
13865    last_word = last_word.chars().rev().collect();
13866    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13867    let to_lsp = |point: &text::Anchor| {
13868        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13869        point_to_lsp(end)
13870    };
13871    let lsp_end = to_lsp(&buffer_position);
13872    snippets
13873        .into_iter()
13874        .filter_map(|snippet| {
13875            let matching_prefix = snippet
13876                .prefix
13877                .iter()
13878                .find(|prefix| prefix.starts_with(&last_word))?;
13879            let start = as_offset - last_word.len();
13880            let start = snapshot.anchor_before(start);
13881            let range = start..buffer_position;
13882            let lsp_start = to_lsp(&start);
13883            let lsp_range = lsp::Range {
13884                start: lsp_start,
13885                end: lsp_end,
13886            };
13887            Some(Completion {
13888                old_range: range,
13889                new_text: snippet.body.clone(),
13890                label: CodeLabel {
13891                    text: matching_prefix.clone(),
13892                    runs: vec![],
13893                    filter_range: 0..matching_prefix.len(),
13894                },
13895                server_id: LanguageServerId(usize::MAX),
13896                documentation: snippet.description.clone().map(Documentation::SingleLine),
13897                lsp_completion: lsp::CompletionItem {
13898                    label: snippet.prefix.first().unwrap().clone(),
13899                    kind: Some(CompletionItemKind::SNIPPET),
13900                    label_details: snippet.description.as_ref().map(|description| {
13901                        lsp::CompletionItemLabelDetails {
13902                            detail: Some(description.clone()),
13903                            description: None,
13904                        }
13905                    }),
13906                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13907                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13908                        lsp::InsertReplaceEdit {
13909                            new_text: snippet.body.clone(),
13910                            insert: lsp_range,
13911                            replace: lsp_range,
13912                        },
13913                    )),
13914                    filter_text: Some(snippet.body.clone()),
13915                    sort_text: Some(char::MAX.to_string()),
13916                    ..Default::default()
13917                },
13918                confirm: None,
13919            })
13920        })
13921        .collect()
13922}
13923
13924impl CompletionProvider for Model<Project> {
13925    fn completions(
13926        &self,
13927        buffer: &Model<Buffer>,
13928        buffer_position: text::Anchor,
13929        options: CompletionContext,
13930        cx: &mut ViewContext<Editor>,
13931    ) -> Task<Result<Vec<Completion>>> {
13932        self.update(cx, |project, cx| {
13933            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13934            let project_completions = project.completions(buffer, buffer_position, options, cx);
13935            cx.background_executor().spawn(async move {
13936                let mut completions = project_completions.await?;
13937                //let snippets = snippets.into_iter().;
13938                completions.extend(snippets);
13939                Ok(completions)
13940            })
13941        })
13942    }
13943
13944    fn resolve_completions(
13945        &self,
13946        buffer: Model<Buffer>,
13947        completion_indices: Vec<usize>,
13948        completions: Arc<RwLock<Box<[Completion]>>>,
13949        cx: &mut ViewContext<Editor>,
13950    ) -> Task<Result<bool>> {
13951        self.update(cx, |project, cx| {
13952            project.resolve_completions(buffer, completion_indices, completions, cx)
13953        })
13954    }
13955
13956    fn apply_additional_edits_for_completion(
13957        &self,
13958        buffer: Model<Buffer>,
13959        completion: Completion,
13960        push_to_history: bool,
13961        cx: &mut ViewContext<Editor>,
13962    ) -> Task<Result<Option<language::Transaction>>> {
13963        self.update(cx, |project, cx| {
13964            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13965        })
13966    }
13967
13968    fn is_completion_trigger(
13969        &self,
13970        buffer: &Model<Buffer>,
13971        position: language::Anchor,
13972        text: &str,
13973        trigger_in_words: bool,
13974        cx: &mut ViewContext<Editor>,
13975    ) -> bool {
13976        if !EditorSettings::get_global(cx).show_completions_on_input {
13977            return false;
13978        }
13979
13980        let mut chars = text.chars();
13981        let char = if let Some(char) = chars.next() {
13982            char
13983        } else {
13984            return false;
13985        };
13986        if chars.next().is_some() {
13987            return false;
13988        }
13989
13990        let buffer = buffer.read(cx);
13991        let classifier = buffer
13992            .snapshot()
13993            .char_classifier_at(position)
13994            .for_completion(true);
13995        if trigger_in_words && classifier.is_word(char) {
13996            return true;
13997        }
13998
13999        buffer.completion_triggers().contains(text)
14000    }
14001}
14002
14003impl SemanticsProvider for Model<Project> {
14004    fn hover(
14005        &self,
14006        buffer: &Model<Buffer>,
14007        position: text::Anchor,
14008        cx: &mut AppContext,
14009    ) -> Option<Task<Vec<project::Hover>>> {
14010        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14011    }
14012
14013    fn document_highlights(
14014        &self,
14015        buffer: &Model<Buffer>,
14016        position: text::Anchor,
14017        cx: &mut AppContext,
14018    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14019        Some(self.update(cx, |project, cx| {
14020            project.document_highlights(buffer, position, cx)
14021        }))
14022    }
14023
14024    fn definitions(
14025        &self,
14026        buffer: &Model<Buffer>,
14027        position: text::Anchor,
14028        kind: GotoDefinitionKind,
14029        cx: &mut AppContext,
14030    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14031        Some(self.update(cx, |project, cx| match kind {
14032            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14033            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14034            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14035            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14036        }))
14037    }
14038
14039    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14040        // TODO: make this work for remote projects
14041        self.read(cx)
14042            .language_servers_for_buffer(buffer.read(cx), cx)
14043            .any(
14044                |(_, server)| match server.capabilities().inlay_hint_provider {
14045                    Some(lsp::OneOf::Left(enabled)) => enabled,
14046                    Some(lsp::OneOf::Right(_)) => true,
14047                    None => false,
14048                },
14049            )
14050    }
14051
14052    fn inlay_hints(
14053        &self,
14054        buffer_handle: Model<Buffer>,
14055        range: Range<text::Anchor>,
14056        cx: &mut AppContext,
14057    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14058        Some(self.update(cx, |project, cx| {
14059            project.inlay_hints(buffer_handle, range, cx)
14060        }))
14061    }
14062
14063    fn resolve_inlay_hint(
14064        &self,
14065        hint: InlayHint,
14066        buffer_handle: Model<Buffer>,
14067        server_id: LanguageServerId,
14068        cx: &mut AppContext,
14069    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14070        Some(self.update(cx, |project, cx| {
14071            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14072        }))
14073    }
14074
14075    fn range_for_rename(
14076        &self,
14077        buffer: &Model<Buffer>,
14078        position: text::Anchor,
14079        cx: &mut AppContext,
14080    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14081        Some(self.update(cx, |project, cx| {
14082            project.prepare_rename(buffer.clone(), position, cx)
14083        }))
14084    }
14085
14086    fn perform_rename(
14087        &self,
14088        buffer: &Model<Buffer>,
14089        position: text::Anchor,
14090        new_name: String,
14091        cx: &mut AppContext,
14092    ) -> Option<Task<Result<ProjectTransaction>>> {
14093        Some(self.update(cx, |project, cx| {
14094            project.perform_rename(buffer.clone(), position, new_name, cx)
14095        }))
14096    }
14097}
14098
14099fn inlay_hint_settings(
14100    location: Anchor,
14101    snapshot: &MultiBufferSnapshot,
14102    cx: &mut ViewContext<'_, Editor>,
14103) -> InlayHintSettings {
14104    let file = snapshot.file_at(location);
14105    let language = snapshot.language_at(location).map(|l| l.name());
14106    language_settings(language, file, cx).inlay_hints
14107}
14108
14109fn consume_contiguous_rows(
14110    contiguous_row_selections: &mut Vec<Selection<Point>>,
14111    selection: &Selection<Point>,
14112    display_map: &DisplaySnapshot,
14113    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14114) -> (MultiBufferRow, MultiBufferRow) {
14115    contiguous_row_selections.push(selection.clone());
14116    let start_row = MultiBufferRow(selection.start.row);
14117    let mut end_row = ending_row(selection, display_map);
14118
14119    while let Some(next_selection) = selections.peek() {
14120        if next_selection.start.row <= end_row.0 {
14121            end_row = ending_row(next_selection, display_map);
14122            contiguous_row_selections.push(selections.next().unwrap().clone());
14123        } else {
14124            break;
14125        }
14126    }
14127    (start_row, end_row)
14128}
14129
14130fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14131    if next_selection.end.column > 0 || next_selection.is_empty() {
14132        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14133    } else {
14134        MultiBufferRow(next_selection.end.row)
14135    }
14136}
14137
14138impl EditorSnapshot {
14139    pub fn remote_selections_in_range<'a>(
14140        &'a self,
14141        range: &'a Range<Anchor>,
14142        collaboration_hub: &dyn CollaborationHub,
14143        cx: &'a AppContext,
14144    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14145        let participant_names = collaboration_hub.user_names(cx);
14146        let participant_indices = collaboration_hub.user_participant_indices(cx);
14147        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14148        let collaborators_by_replica_id = collaborators_by_peer_id
14149            .iter()
14150            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14151            .collect::<HashMap<_, _>>();
14152        self.buffer_snapshot
14153            .selections_in_range(range, false)
14154            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14155                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14156                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14157                let user_name = participant_names.get(&collaborator.user_id).cloned();
14158                Some(RemoteSelection {
14159                    replica_id,
14160                    selection,
14161                    cursor_shape,
14162                    line_mode,
14163                    participant_index,
14164                    peer_id: collaborator.peer_id,
14165                    user_name,
14166                })
14167            })
14168    }
14169
14170    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14171        self.display_snapshot.buffer_snapshot.language_at(position)
14172    }
14173
14174    pub fn is_focused(&self) -> bool {
14175        self.is_focused
14176    }
14177
14178    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14179        self.placeholder_text.as_ref()
14180    }
14181
14182    pub fn scroll_position(&self) -> gpui::Point<f32> {
14183        self.scroll_anchor.scroll_position(&self.display_snapshot)
14184    }
14185
14186    fn gutter_dimensions(
14187        &self,
14188        font_id: FontId,
14189        font_size: Pixels,
14190        em_width: Pixels,
14191        em_advance: Pixels,
14192        max_line_number_width: Pixels,
14193        cx: &AppContext,
14194    ) -> GutterDimensions {
14195        if !self.show_gutter {
14196            return GutterDimensions::default();
14197        }
14198        let descent = cx.text_system().descent(font_id, font_size);
14199
14200        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14201            matches!(
14202                ProjectSettings::get_global(cx).git.git_gutter,
14203                Some(GitGutterSetting::TrackedFiles)
14204            )
14205        });
14206        let gutter_settings = EditorSettings::get_global(cx).gutter;
14207        let show_line_numbers = self
14208            .show_line_numbers
14209            .unwrap_or(gutter_settings.line_numbers);
14210        let line_gutter_width = if show_line_numbers {
14211            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14212            let min_width_for_number_on_gutter = em_advance * 4.0;
14213            max_line_number_width.max(min_width_for_number_on_gutter)
14214        } else {
14215            0.0.into()
14216        };
14217
14218        let show_code_actions = self
14219            .show_code_actions
14220            .unwrap_or(gutter_settings.code_actions);
14221
14222        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14223
14224        let git_blame_entries_width =
14225            self.git_blame_gutter_max_author_length
14226                .map(|max_author_length| {
14227                    // Length of the author name, but also space for the commit hash,
14228                    // the spacing and the timestamp.
14229                    let max_char_count = max_author_length
14230                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14231                        + 7 // length of commit sha
14232                        + 14 // length of max relative timestamp ("60 minutes ago")
14233                        + 4; // gaps and margins
14234
14235                    em_advance * max_char_count
14236                });
14237
14238        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14239        left_padding += if show_code_actions || show_runnables {
14240            em_width * 3.0
14241        } else if show_git_gutter && show_line_numbers {
14242            em_width * 2.0
14243        } else if show_git_gutter || show_line_numbers {
14244            em_width
14245        } else {
14246            px(0.)
14247        };
14248
14249        let right_padding = if gutter_settings.folds && show_line_numbers {
14250            em_width * 4.0
14251        } else if gutter_settings.folds {
14252            em_width * 3.0
14253        } else if show_line_numbers {
14254            em_width
14255        } else {
14256            px(0.)
14257        };
14258
14259        GutterDimensions {
14260            left_padding,
14261            right_padding,
14262            width: line_gutter_width + left_padding + right_padding,
14263            margin: -descent,
14264            git_blame_entries_width,
14265        }
14266    }
14267
14268    pub fn render_crease_toggle(
14269        &self,
14270        buffer_row: MultiBufferRow,
14271        row_contains_cursor: bool,
14272        editor: View<Editor>,
14273        cx: &mut WindowContext,
14274    ) -> Option<AnyElement> {
14275        let folded = self.is_line_folded(buffer_row);
14276        let mut is_foldable = false;
14277
14278        if let Some(crease) = self
14279            .crease_snapshot
14280            .query_row(buffer_row, &self.buffer_snapshot)
14281        {
14282            is_foldable = true;
14283            match crease {
14284                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14285                    if let Some(render_toggle) = render_toggle {
14286                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14287                            if folded {
14288                                editor.update(cx, |editor, cx| {
14289                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14290                                });
14291                            } else {
14292                                editor.update(cx, |editor, cx| {
14293                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14294                                });
14295                            }
14296                        });
14297                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14298                    }
14299                }
14300            }
14301        }
14302
14303        is_foldable |= self.starts_indent(buffer_row);
14304
14305        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14306            Some(
14307                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14308                    .selected(folded)
14309                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14310                        if folded {
14311                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14312                        } else {
14313                            this.fold_at(&FoldAt { buffer_row }, cx);
14314                        }
14315                    }))
14316                    .into_any_element(),
14317            )
14318        } else {
14319            None
14320        }
14321    }
14322
14323    pub fn render_crease_trailer(
14324        &self,
14325        buffer_row: MultiBufferRow,
14326        cx: &mut WindowContext,
14327    ) -> Option<AnyElement> {
14328        let folded = self.is_line_folded(buffer_row);
14329        if let Crease::Inline { render_trailer, .. } = self
14330            .crease_snapshot
14331            .query_row(buffer_row, &self.buffer_snapshot)?
14332        {
14333            let render_trailer = render_trailer.as_ref()?;
14334            Some(render_trailer(buffer_row, folded, cx))
14335        } else {
14336            None
14337        }
14338    }
14339}
14340
14341impl Deref for EditorSnapshot {
14342    type Target = DisplaySnapshot;
14343
14344    fn deref(&self) -> &Self::Target {
14345        &self.display_snapshot
14346    }
14347}
14348
14349#[derive(Clone, Debug, PartialEq, Eq)]
14350pub enum EditorEvent {
14351    InputIgnored {
14352        text: Arc<str>,
14353    },
14354    InputHandled {
14355        utf16_range_to_replace: Option<Range<isize>>,
14356        text: Arc<str>,
14357    },
14358    ExcerptsAdded {
14359        buffer: Model<Buffer>,
14360        predecessor: ExcerptId,
14361        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14362    },
14363    ExcerptsRemoved {
14364        ids: Vec<ExcerptId>,
14365    },
14366    ExcerptsEdited {
14367        ids: Vec<ExcerptId>,
14368    },
14369    ExcerptsExpanded {
14370        ids: Vec<ExcerptId>,
14371    },
14372    BufferEdited,
14373    Edited {
14374        transaction_id: clock::Lamport,
14375    },
14376    Reparsed(BufferId),
14377    Focused,
14378    FocusedIn,
14379    Blurred,
14380    DirtyChanged,
14381    Saved,
14382    TitleChanged,
14383    DiffBaseChanged,
14384    SelectionsChanged {
14385        local: bool,
14386    },
14387    ScrollPositionChanged {
14388        local: bool,
14389        autoscroll: bool,
14390    },
14391    Closed,
14392    TransactionUndone {
14393        transaction_id: clock::Lamport,
14394    },
14395    TransactionBegun {
14396        transaction_id: clock::Lamport,
14397    },
14398    Reloaded,
14399    CursorShapeChanged,
14400}
14401
14402impl EventEmitter<EditorEvent> for Editor {}
14403
14404impl FocusableView for Editor {
14405    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14406        self.focus_handle.clone()
14407    }
14408}
14409
14410impl Render for Editor {
14411    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14412        let settings = ThemeSettings::get_global(cx);
14413
14414        let mut text_style = match self.mode {
14415            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14416                color: cx.theme().colors().editor_foreground,
14417                font_family: settings.ui_font.family.clone(),
14418                font_features: settings.ui_font.features.clone(),
14419                font_fallbacks: settings.ui_font.fallbacks.clone(),
14420                font_size: rems(0.875).into(),
14421                font_weight: settings.ui_font.weight,
14422                line_height: relative(settings.buffer_line_height.value()),
14423                ..Default::default()
14424            },
14425            EditorMode::Full => TextStyle {
14426                color: cx.theme().colors().editor_foreground,
14427                font_family: settings.buffer_font.family.clone(),
14428                font_features: settings.buffer_font.features.clone(),
14429                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14430                font_size: settings.buffer_font_size(cx).into(),
14431                font_weight: settings.buffer_font.weight,
14432                line_height: relative(settings.buffer_line_height.value()),
14433                ..Default::default()
14434            },
14435        };
14436        if let Some(text_style_refinement) = &self.text_style_refinement {
14437            text_style.refine(text_style_refinement)
14438        }
14439
14440        let background = match self.mode {
14441            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14442            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14443            EditorMode::Full => cx.theme().colors().editor_background,
14444        };
14445
14446        EditorElement::new(
14447            cx.view(),
14448            EditorStyle {
14449                background,
14450                local_player: cx.theme().players().local(),
14451                text: text_style,
14452                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14453                syntax: cx.theme().syntax().clone(),
14454                status: cx.theme().status().clone(),
14455                inlay_hints_style: make_inlay_hints_style(cx),
14456                suggestions_style: HighlightStyle {
14457                    color: Some(cx.theme().status().predictive),
14458                    ..HighlightStyle::default()
14459                },
14460                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14461            },
14462        )
14463    }
14464}
14465
14466impl ViewInputHandler for Editor {
14467    fn text_for_range(
14468        &mut self,
14469        range_utf16: Range<usize>,
14470        adjusted_range: &mut Option<Range<usize>>,
14471        cx: &mut ViewContext<Self>,
14472    ) -> Option<String> {
14473        let snapshot = self.buffer.read(cx).read(cx);
14474        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14475        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14476        if (start.0..end.0) != range_utf16 {
14477            adjusted_range.replace(start.0..end.0);
14478        }
14479        Some(snapshot.text_for_range(start..end).collect())
14480    }
14481
14482    fn selected_text_range(
14483        &mut self,
14484        ignore_disabled_input: bool,
14485        cx: &mut ViewContext<Self>,
14486    ) -> Option<UTF16Selection> {
14487        // Prevent the IME menu from appearing when holding down an alphabetic key
14488        // while input is disabled.
14489        if !ignore_disabled_input && !self.input_enabled {
14490            return None;
14491        }
14492
14493        let selection = self.selections.newest::<OffsetUtf16>(cx);
14494        let range = selection.range();
14495
14496        Some(UTF16Selection {
14497            range: range.start.0..range.end.0,
14498            reversed: selection.reversed,
14499        })
14500    }
14501
14502    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14503        let snapshot = self.buffer.read(cx).read(cx);
14504        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14505        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14506    }
14507
14508    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14509        self.clear_highlights::<InputComposition>(cx);
14510        self.ime_transaction.take();
14511    }
14512
14513    fn replace_text_in_range(
14514        &mut self,
14515        range_utf16: Option<Range<usize>>,
14516        text: &str,
14517        cx: &mut ViewContext<Self>,
14518    ) {
14519        if !self.input_enabled {
14520            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14521            return;
14522        }
14523
14524        self.transact(cx, |this, cx| {
14525            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14526                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14527                Some(this.selection_replacement_ranges(range_utf16, cx))
14528            } else {
14529                this.marked_text_ranges(cx)
14530            };
14531
14532            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14533                let newest_selection_id = this.selections.newest_anchor().id;
14534                this.selections
14535                    .all::<OffsetUtf16>(cx)
14536                    .iter()
14537                    .zip(ranges_to_replace.iter())
14538                    .find_map(|(selection, range)| {
14539                        if selection.id == newest_selection_id {
14540                            Some(
14541                                (range.start.0 as isize - selection.head().0 as isize)
14542                                    ..(range.end.0 as isize - selection.head().0 as isize),
14543                            )
14544                        } else {
14545                            None
14546                        }
14547                    })
14548            });
14549
14550            cx.emit(EditorEvent::InputHandled {
14551                utf16_range_to_replace: range_to_replace,
14552                text: text.into(),
14553            });
14554
14555            if let Some(new_selected_ranges) = new_selected_ranges {
14556                this.change_selections(None, cx, |selections| {
14557                    selections.select_ranges(new_selected_ranges)
14558                });
14559                this.backspace(&Default::default(), cx);
14560            }
14561
14562            this.handle_input(text, cx);
14563        });
14564
14565        if let Some(transaction) = self.ime_transaction {
14566            self.buffer.update(cx, |buffer, cx| {
14567                buffer.group_until_transaction(transaction, cx);
14568            });
14569        }
14570
14571        self.unmark_text(cx);
14572    }
14573
14574    fn replace_and_mark_text_in_range(
14575        &mut self,
14576        range_utf16: Option<Range<usize>>,
14577        text: &str,
14578        new_selected_range_utf16: Option<Range<usize>>,
14579        cx: &mut ViewContext<Self>,
14580    ) {
14581        if !self.input_enabled {
14582            return;
14583        }
14584
14585        let transaction = self.transact(cx, |this, cx| {
14586            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14587                let snapshot = this.buffer.read(cx).read(cx);
14588                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14589                    for marked_range in &mut marked_ranges {
14590                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14591                        marked_range.start.0 += relative_range_utf16.start;
14592                        marked_range.start =
14593                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14594                        marked_range.end =
14595                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14596                    }
14597                }
14598                Some(marked_ranges)
14599            } else if let Some(range_utf16) = range_utf16 {
14600                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14601                Some(this.selection_replacement_ranges(range_utf16, cx))
14602            } else {
14603                None
14604            };
14605
14606            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14607                let newest_selection_id = this.selections.newest_anchor().id;
14608                this.selections
14609                    .all::<OffsetUtf16>(cx)
14610                    .iter()
14611                    .zip(ranges_to_replace.iter())
14612                    .find_map(|(selection, range)| {
14613                        if selection.id == newest_selection_id {
14614                            Some(
14615                                (range.start.0 as isize - selection.head().0 as isize)
14616                                    ..(range.end.0 as isize - selection.head().0 as isize),
14617                            )
14618                        } else {
14619                            None
14620                        }
14621                    })
14622            });
14623
14624            cx.emit(EditorEvent::InputHandled {
14625                utf16_range_to_replace: range_to_replace,
14626                text: text.into(),
14627            });
14628
14629            if let Some(ranges) = ranges_to_replace {
14630                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14631            }
14632
14633            let marked_ranges = {
14634                let snapshot = this.buffer.read(cx).read(cx);
14635                this.selections
14636                    .disjoint_anchors()
14637                    .iter()
14638                    .map(|selection| {
14639                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14640                    })
14641                    .collect::<Vec<_>>()
14642            };
14643
14644            if text.is_empty() {
14645                this.unmark_text(cx);
14646            } else {
14647                this.highlight_text::<InputComposition>(
14648                    marked_ranges.clone(),
14649                    HighlightStyle {
14650                        underline: Some(UnderlineStyle {
14651                            thickness: px(1.),
14652                            color: None,
14653                            wavy: false,
14654                        }),
14655                        ..Default::default()
14656                    },
14657                    cx,
14658                );
14659            }
14660
14661            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14662            let use_autoclose = this.use_autoclose;
14663            let use_auto_surround = this.use_auto_surround;
14664            this.set_use_autoclose(false);
14665            this.set_use_auto_surround(false);
14666            this.handle_input(text, cx);
14667            this.set_use_autoclose(use_autoclose);
14668            this.set_use_auto_surround(use_auto_surround);
14669
14670            if let Some(new_selected_range) = new_selected_range_utf16 {
14671                let snapshot = this.buffer.read(cx).read(cx);
14672                let new_selected_ranges = marked_ranges
14673                    .into_iter()
14674                    .map(|marked_range| {
14675                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14676                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14677                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14678                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14679                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14680                    })
14681                    .collect::<Vec<_>>();
14682
14683                drop(snapshot);
14684                this.change_selections(None, cx, |selections| {
14685                    selections.select_ranges(new_selected_ranges)
14686                });
14687            }
14688        });
14689
14690        self.ime_transaction = self.ime_transaction.or(transaction);
14691        if let Some(transaction) = self.ime_transaction {
14692            self.buffer.update(cx, |buffer, cx| {
14693                buffer.group_until_transaction(transaction, cx);
14694            });
14695        }
14696
14697        if self.text_highlights::<InputComposition>(cx).is_none() {
14698            self.ime_transaction.take();
14699        }
14700    }
14701
14702    fn bounds_for_range(
14703        &mut self,
14704        range_utf16: Range<usize>,
14705        element_bounds: gpui::Bounds<Pixels>,
14706        cx: &mut ViewContext<Self>,
14707    ) -> Option<gpui::Bounds<Pixels>> {
14708        let text_layout_details = self.text_layout_details(cx);
14709        let style = &text_layout_details.editor_style;
14710        let font_id = cx.text_system().resolve_font(&style.text.font());
14711        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14712        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14713
14714        let em_width = cx
14715            .text_system()
14716            .typographic_bounds(font_id, font_size, 'm')
14717            .unwrap()
14718            .size
14719            .width;
14720
14721        let snapshot = self.snapshot(cx);
14722        let scroll_position = snapshot.scroll_position();
14723        let scroll_left = scroll_position.x * em_width;
14724
14725        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14726        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14727            + self.gutter_dimensions.width
14728            + self.gutter_dimensions.margin;
14729        let y = line_height * (start.row().as_f32() - scroll_position.y);
14730
14731        Some(Bounds {
14732            origin: element_bounds.origin + point(x, y),
14733            size: size(em_width, line_height),
14734        })
14735    }
14736}
14737
14738trait SelectionExt {
14739    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14740    fn spanned_rows(
14741        &self,
14742        include_end_if_at_line_start: bool,
14743        map: &DisplaySnapshot,
14744    ) -> Range<MultiBufferRow>;
14745}
14746
14747impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14748    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14749        let start = self
14750            .start
14751            .to_point(&map.buffer_snapshot)
14752            .to_display_point(map);
14753        let end = self
14754            .end
14755            .to_point(&map.buffer_snapshot)
14756            .to_display_point(map);
14757        if self.reversed {
14758            end..start
14759        } else {
14760            start..end
14761        }
14762    }
14763
14764    fn spanned_rows(
14765        &self,
14766        include_end_if_at_line_start: bool,
14767        map: &DisplaySnapshot,
14768    ) -> Range<MultiBufferRow> {
14769        let start = self.start.to_point(&map.buffer_snapshot);
14770        let mut end = self.end.to_point(&map.buffer_snapshot);
14771        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14772            end.row -= 1;
14773        }
14774
14775        let buffer_start = map.prev_line_boundary(start).0;
14776        let buffer_end = map.next_line_boundary(end).0;
14777        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14778    }
14779}
14780
14781impl<T: InvalidationRegion> InvalidationStack<T> {
14782    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14783    where
14784        S: Clone + ToOffset,
14785    {
14786        while let Some(region) = self.last() {
14787            let all_selections_inside_invalidation_ranges =
14788                if selections.len() == region.ranges().len() {
14789                    selections
14790                        .iter()
14791                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14792                        .all(|(selection, invalidation_range)| {
14793                            let head = selection.head().to_offset(buffer);
14794                            invalidation_range.start <= head && invalidation_range.end >= head
14795                        })
14796                } else {
14797                    false
14798                };
14799
14800            if all_selections_inside_invalidation_ranges {
14801                break;
14802            } else {
14803                self.pop();
14804            }
14805        }
14806    }
14807}
14808
14809impl<T> Default for InvalidationStack<T> {
14810    fn default() -> Self {
14811        Self(Default::default())
14812    }
14813}
14814
14815impl<T> Deref for InvalidationStack<T> {
14816    type Target = Vec<T>;
14817
14818    fn deref(&self) -> &Self::Target {
14819        &self.0
14820    }
14821}
14822
14823impl<T> DerefMut for InvalidationStack<T> {
14824    fn deref_mut(&mut self) -> &mut Self::Target {
14825        &mut self.0
14826    }
14827}
14828
14829impl InvalidationRegion for SnippetState {
14830    fn ranges(&self) -> &[Range<Anchor>] {
14831        &self.ranges[self.active_index]
14832    }
14833}
14834
14835pub fn diagnostic_block_renderer(
14836    diagnostic: Diagnostic,
14837    max_message_rows: Option<u8>,
14838    allow_closing: bool,
14839    _is_valid: bool,
14840) -> RenderBlock {
14841    let (text_without_backticks, code_ranges) =
14842        highlight_diagnostic_message(&diagnostic, max_message_rows);
14843
14844    Arc::new(move |cx: &mut BlockContext| {
14845        let group_id: SharedString = cx.block_id.to_string().into();
14846
14847        let mut text_style = cx.text_style().clone();
14848        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14849        let theme_settings = ThemeSettings::get_global(cx);
14850        text_style.font_family = theme_settings.buffer_font.family.clone();
14851        text_style.font_style = theme_settings.buffer_font.style;
14852        text_style.font_features = theme_settings.buffer_font.features.clone();
14853        text_style.font_weight = theme_settings.buffer_font.weight;
14854
14855        let multi_line_diagnostic = diagnostic.message.contains('\n');
14856
14857        let buttons = |diagnostic: &Diagnostic| {
14858            if multi_line_diagnostic {
14859                v_flex()
14860            } else {
14861                h_flex()
14862            }
14863            .when(allow_closing, |div| {
14864                div.children(diagnostic.is_primary.then(|| {
14865                    IconButton::new("close-block", IconName::XCircle)
14866                        .icon_color(Color::Muted)
14867                        .size(ButtonSize::Compact)
14868                        .style(ButtonStyle::Transparent)
14869                        .visible_on_hover(group_id.clone())
14870                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14871                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14872                }))
14873            })
14874            .child(
14875                IconButton::new("copy-block", IconName::Copy)
14876                    .icon_color(Color::Muted)
14877                    .size(ButtonSize::Compact)
14878                    .style(ButtonStyle::Transparent)
14879                    .visible_on_hover(group_id.clone())
14880                    .on_click({
14881                        let message = diagnostic.message.clone();
14882                        move |_click, cx| {
14883                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14884                        }
14885                    })
14886                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14887            )
14888        };
14889
14890        let icon_size = buttons(&diagnostic)
14891            .into_any_element()
14892            .layout_as_root(AvailableSpace::min_size(), cx);
14893
14894        h_flex()
14895            .id(cx.block_id)
14896            .group(group_id.clone())
14897            .relative()
14898            .size_full()
14899            .block_mouse_down()
14900            .pl(cx.gutter_dimensions.width)
14901            .w(cx.max_width - cx.gutter_dimensions.full_width())
14902            .child(
14903                div()
14904                    .flex()
14905                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14906                    .flex_shrink(),
14907            )
14908            .child(buttons(&diagnostic))
14909            .child(div().flex().flex_shrink_0().child(
14910                StyledText::new(text_without_backticks.clone()).with_highlights(
14911                    &text_style,
14912                    code_ranges.iter().map(|range| {
14913                        (
14914                            range.clone(),
14915                            HighlightStyle {
14916                                font_weight: Some(FontWeight::BOLD),
14917                                ..Default::default()
14918                            },
14919                        )
14920                    }),
14921                ),
14922            ))
14923            .into_any_element()
14924    })
14925}
14926
14927pub fn highlight_diagnostic_message(
14928    diagnostic: &Diagnostic,
14929    mut max_message_rows: Option<u8>,
14930) -> (SharedString, Vec<Range<usize>>) {
14931    let mut text_without_backticks = String::new();
14932    let mut code_ranges = Vec::new();
14933
14934    if let Some(source) = &diagnostic.source {
14935        text_without_backticks.push_str(source);
14936        code_ranges.push(0..source.len());
14937        text_without_backticks.push_str(": ");
14938    }
14939
14940    let mut prev_offset = 0;
14941    let mut in_code_block = false;
14942    let has_row_limit = max_message_rows.is_some();
14943    let mut newline_indices = diagnostic
14944        .message
14945        .match_indices('\n')
14946        .filter(|_| has_row_limit)
14947        .map(|(ix, _)| ix)
14948        .fuse()
14949        .peekable();
14950
14951    for (quote_ix, _) in diagnostic
14952        .message
14953        .match_indices('`')
14954        .chain([(diagnostic.message.len(), "")])
14955    {
14956        let mut first_newline_ix = None;
14957        let mut last_newline_ix = None;
14958        while let Some(newline_ix) = newline_indices.peek() {
14959            if *newline_ix < quote_ix {
14960                if first_newline_ix.is_none() {
14961                    first_newline_ix = Some(*newline_ix);
14962                }
14963                last_newline_ix = Some(*newline_ix);
14964
14965                if let Some(rows_left) = &mut max_message_rows {
14966                    if *rows_left == 0 {
14967                        break;
14968                    } else {
14969                        *rows_left -= 1;
14970                    }
14971                }
14972                let _ = newline_indices.next();
14973            } else {
14974                break;
14975            }
14976        }
14977        let prev_len = text_without_backticks.len();
14978        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14979        text_without_backticks.push_str(new_text);
14980        if in_code_block {
14981            code_ranges.push(prev_len..text_without_backticks.len());
14982        }
14983        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14984        in_code_block = !in_code_block;
14985        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14986            text_without_backticks.push_str("...");
14987            break;
14988        }
14989    }
14990
14991    (text_without_backticks.into(), code_ranges)
14992}
14993
14994fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14995    match severity {
14996        DiagnosticSeverity::ERROR => colors.error,
14997        DiagnosticSeverity::WARNING => colors.warning,
14998        DiagnosticSeverity::INFORMATION => colors.info,
14999        DiagnosticSeverity::HINT => colors.info,
15000        _ => colors.ignored,
15001    }
15002}
15003
15004pub fn styled_runs_for_code_label<'a>(
15005    label: &'a CodeLabel,
15006    syntax_theme: &'a theme::SyntaxTheme,
15007) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15008    let fade_out = HighlightStyle {
15009        fade_out: Some(0.35),
15010        ..Default::default()
15011    };
15012
15013    let mut prev_end = label.filter_range.end;
15014    label
15015        .runs
15016        .iter()
15017        .enumerate()
15018        .flat_map(move |(ix, (range, highlight_id))| {
15019            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15020                style
15021            } else {
15022                return Default::default();
15023            };
15024            let mut muted_style = style;
15025            muted_style.highlight(fade_out);
15026
15027            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15028            if range.start >= label.filter_range.end {
15029                if range.start > prev_end {
15030                    runs.push((prev_end..range.start, fade_out));
15031                }
15032                runs.push((range.clone(), muted_style));
15033            } else if range.end <= label.filter_range.end {
15034                runs.push((range.clone(), style));
15035            } else {
15036                runs.push((range.start..label.filter_range.end, style));
15037                runs.push((label.filter_range.end..range.end, muted_style));
15038            }
15039            prev_end = cmp::max(prev_end, range.end);
15040
15041            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15042                runs.push((prev_end..label.text.len(), fade_out));
15043            }
15044
15045            runs
15046        })
15047}
15048
15049pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15050    let mut prev_index = 0;
15051    let mut prev_codepoint: Option<char> = None;
15052    text.char_indices()
15053        .chain([(text.len(), '\0')])
15054        .filter_map(move |(index, codepoint)| {
15055            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15056            let is_boundary = index == text.len()
15057                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15058                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15059            if is_boundary {
15060                let chunk = &text[prev_index..index];
15061                prev_index = index;
15062                Some(chunk)
15063            } else {
15064                None
15065            }
15066        })
15067}
15068
15069pub trait RangeToAnchorExt: Sized {
15070    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15071
15072    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15073        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15074        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15075    }
15076}
15077
15078impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15079    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15080        let start_offset = self.start.to_offset(snapshot);
15081        let end_offset = self.end.to_offset(snapshot);
15082        if start_offset == end_offset {
15083            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15084        } else {
15085            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15086        }
15087    }
15088}
15089
15090pub trait RowExt {
15091    fn as_f32(&self) -> f32;
15092
15093    fn next_row(&self) -> Self;
15094
15095    fn previous_row(&self) -> Self;
15096
15097    fn minus(&self, other: Self) -> u32;
15098}
15099
15100impl RowExt for DisplayRow {
15101    fn as_f32(&self) -> f32 {
15102        self.0 as f32
15103    }
15104
15105    fn next_row(&self) -> Self {
15106        Self(self.0 + 1)
15107    }
15108
15109    fn previous_row(&self) -> Self {
15110        Self(self.0.saturating_sub(1))
15111    }
15112
15113    fn minus(&self, other: Self) -> u32 {
15114        self.0 - other.0
15115    }
15116}
15117
15118impl RowExt for MultiBufferRow {
15119    fn as_f32(&self) -> f32 {
15120        self.0 as f32
15121    }
15122
15123    fn next_row(&self) -> Self {
15124        Self(self.0 + 1)
15125    }
15126
15127    fn previous_row(&self) -> Self {
15128        Self(self.0.saturating_sub(1))
15129    }
15130
15131    fn minus(&self, other: Self) -> u32 {
15132        self.0 - other.0
15133    }
15134}
15135
15136trait RowRangeExt {
15137    type Row;
15138
15139    fn len(&self) -> usize;
15140
15141    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15142}
15143
15144impl RowRangeExt for Range<MultiBufferRow> {
15145    type Row = MultiBufferRow;
15146
15147    fn len(&self) -> usize {
15148        (self.end.0 - self.start.0) as usize
15149    }
15150
15151    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15152        (self.start.0..self.end.0).map(MultiBufferRow)
15153    }
15154}
15155
15156impl RowRangeExt for Range<DisplayRow> {
15157    type Row = DisplayRow;
15158
15159    fn len(&self) -> usize {
15160        (self.end.0 - self.start.0) as usize
15161    }
15162
15163    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15164        (self.start.0..self.end.0).map(DisplayRow)
15165    }
15166}
15167
15168fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15169    if hunk.diff_base_byte_range.is_empty() {
15170        DiffHunkStatus::Added
15171    } else if hunk.row_range.is_empty() {
15172        DiffHunkStatus::Removed
15173    } else {
15174        DiffHunkStatus::Modified
15175    }
15176}
15177
15178/// If select range has more than one line, we
15179/// just point the cursor to range.start.
15180fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15181    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15182        range
15183    } else {
15184        range.start..range.start
15185    }
15186}
15187
15188pub struct KillRing(ClipboardItem);
15189impl Global for KillRing {}
15190
15191const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);